0% found this document useful (0 votes)
30 views

Laboratory No. 1 - PYTHON

The document discusses an introductory Python programming lab. It covers interactive and script modes, basic math operations and variables in Python, strings including indexing, slicing and concatenation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Laboratory No. 1 - PYTHON

The document discusses an introductory Python programming lab. It covers interactive and script modes, basic math operations and variables in Python, strings including indexing, slicing and concatenation.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

BULACAN STATE UNIVERSITY

COLLEGE OF ENGINEERING
COMPUTER ENGINEERING DEPARTMENT
City of Malolos Bulacan

CVE106 COMPUTER FUNDAMENTALS AND PROGRAMMING


LABORATORY NO. 1
“HELLO, PYTHON!”

NAME: ___________________________________
MARQUEZ, DENISE ANN B. SCORE: _______________
C/Y/S: __________________________________
BSCE - 1B DATE: ________________
22/04/2024

1. Objective: To know what is Python programming language, its structure, its operation and its
difference & significance on other programming languages and familiarized with numbers and
strings manipulation.
2. Software: Python 2.7.14 or newer version
3. Introduction
When programming in Python, you have two basic options for running code: interactive
mode and script mode.
INTERACTIVE MODE (a.k.a. shell mode) is great for quickly and conveniently running
single lines or blocks of code.
The “>>>” indicates that the shell is ready to accept interactive commands. In this mode it
prompts for the next command with the primary prompt, usually three greater-than signs (>>>);
for continuation lines it prompts with the secondary prompt, by default three dots (...). The
interpreter prints a welcome message stating its version number and a copyright notice before
printing the first prompt.

4. Procedures
1. Go to command prompt and type python.

2. The “>>>” indicates that the shell is ready to accept interactive commands.
3. Type the following text at the Python prompt and press Enter: print “Hello, Python!”
Hello, Python!
The output on the screen is __________________.
4. Comments in Python start with the hash character, #, and extend to the end of the physical
line. A comment may appear at the start of a line or following whitespace or code, but not
within a string literal. A hash character within a string literal is just a hash character.

1
Note: The following process/commands will be dealing with NUMBERS. Write the
result or your answers if you encountered a blank space like _____________.
5. The interpreter acts as a simple calculator: you can type an expression at it and it will write
the value. Expression syntax is straightforward: the operators +, -, * and / work just like in
most other languages (for example, Pascal or C); parentheses (()) can be used for grouping.
Try the following and write the result on the space provided.
>>> 2 + 2
4
_____________
>>> 50 - 5*6
20
_____________
>>> (50 - 5.0*6) / 4
5.0
_____________
>>> 8 / 5.0
1.6
_____________
>>> 17 / 3
5
_____________
>>> 17 / 3.0
5.666666666666667
_____________
>>> 17 // 3.0
5.0
_____________
>>> 17 % 3
2
_____________
>>> 5 * 3 + 2
17
_____________
>>> 5 ** 2
25
_____________
>>> 2 ** 7
128
_____________

>>> width = 20
>>> height = 5 * 9
>>> width * height
900
_____________

If a variable is not “defined” (assigned a value), trying to use it will give you an error. Write on
the space provided the message from the screen.
>>> n
Traceback
_____________(most recent call last):
File "<stdin>", line 1, in <module>
_____________
NameError:
_____________ name 'n' is not defined

2
There is full support for floating point; operators with mixed type operands convert the integer
operand to floating point:

>>> 3 * 3.75 / 1.5


7.5
_____________
>>> 7.0 / 2
3.5
_____________

In interactive mode, the last printed expression is assigned to the variable _. This means that when
you are using Python as a desk calculator, it is somewhat easier to continue calculations,

>>> tax = 12.5 / 100


>>> price = 100.50
>>> price * tax
12.5625
_____________
>>> price + _
113.0625
_____________
>>> round(_, 2)
113.06
_____________

6. Besides numbers, Python can also manipulate strings, which can be expressed in several
ways. They can be enclosed in single quotes ('...') or double quotes ("...") with the same
result [2]. \ can be used to escape quotes:

>>> 'spam eggs' # single quotes


'spam eggs'
_____________
>>> 'doesn\'t' # use \' to escape the single quote...
"doesn't"
_____________
>>> "doesn't" # ...or use double quotes instead
"doesn't"
_____________
>>> '"Yes," they said.'
'"Yes," they said.'
_____________
>>> "\"Yes,\" they said."
'"Yes," they said.'
_____________
>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
_____________
The string is enclosed in double quotes if the string contains a single quote and no double quotes,
otherwise it is enclosed in single quotes. The print statement produces a more readable output, by
omitting the enclosing quotes and by printing escaped and special characters:
>> '"Isn\'t," they said.'
'"Isn\'t," they said.'
_____________
>>> print '"Isn\'t," they said.'
"Isn't," they said.
_____________
>>> s = 'First line.\nSecond line.'
3
>>> s
'First line.\nSecond line.'
_____________
>>> print s
First line.
_____________
Second line.
_____________
If you don’t want characters prefaced by \ to be interpreted as special characters, you can
use raw strings by adding an r before the first quote:
>>> print 'C:\some\name' # here \n means newline!
C:\some
_____________
ame
_____________
>>> print r'C:\some\name' # note the r before the quote
C:\some\name
_____________
String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''. End of
lines are automatically included in the string, but it’s possible to prevent this by adding a \ at the
end of the line.
>>> print """\
... Usage: thingy [OPTIONS]
... -h Display this usage message
... -H hostname Hostname to connect to
... """
Usage: thingy [OPTIONS]
________________________________
-h Display this usage message
________________________________
-H ________________________________
hostname Hostname to connect to

Strings can be concatenated (glued together) with the + operator, and repeated with *
>>> # 3 times 'un', followed by 'ium'
>>> 3 * 'un' + 'ium'
'unununium'
_____________
Two or more string literals (i.e. the ones enclosed between quotes) next to each other are
automatically concatenated.
>>> 'Py' 'thon'
'Python'
_____________
This feature is particularly useful when you want to break long strings:
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'
________________________________
This only works with two literals though, not with variables or expressions:
>>> prefix = 'Py'
>>> prefix 'thon' # can't concatenate a variable and a string literal
...
SyntaxError: invalid syntax
>>> ('un' * 3) 'ium'
...
4
SyntaxError: invalid syntax

If you want to concatenate variables or a variable and a literal, use +


>>> prefix + 'thon'
'Python'
_____________
Strings can be indexed (subscripted), with the first character having index 0. There is no separate
character type; a character is simply a string of size one:
>>> word = 'Python'
>>> word[0] # character in position 0
'P'
_____________
>>> word[5] # character in position 5
'n'
_____________
Indices may also be negative numbers, to start counting from the right:
>>> word[-1] # last character
'n'
_____________
>>> word[-2] # second-last character
'o'
_____________
>>> word[-6]
'P'
_____________

Note that since -0 is the same as 0, negative indices start from -1.

In addition to indexing, slicing is also supported. While indexing is used to obtain individual
characters, slicing allows you to obtain a substring:

>>> word[0:2] # characters from position 0 (included) to 2 (excluded)


'Py'
_____________
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'
_____________
Note how the start is always included, and the end always excluded. This makes sure that
s[:i] + s[i:] is always equal to s:
>>> word[:2] + word[2:]
'Python'
_____________
>>> word[:4] + word[4:]
'Python'
_____________

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second
index defaults to the size of the string being sliced.
>>> word[:2] # character from the beginning to position 2 (excluded)
'Py'
_____________
>>> word[4:] # characters from position 4 (included) to the end
'on'
_____________
>>> word[-2:] # characters from the second-last (included) to the end
_____________ 'on'

5
One way to remember how slices work is to think of the indices as pointing between
characters, with the left edge of the first character numbered 0. Then the right edge of the last
character of a string of n characters has index n, for example:

+---+---+---+---+---+---+
|P|y|t|h|o|n|
+---+---+---+---+---+---+
0 1 2 3 4 5 6
-6 -5 -4 -3 -2 -1

The first row of numbers gives the position of the indices 0…6 in the string; the second row gives
the corresponding negative indices. The slice from i to j consists of all characters between the
edges labeled i and j, respectively.

For non-negative indices, the length of a slice is the difference of the indices, if both are within
bounds. For example, the length of word[1:3] is 2.

Attempting to use an index that is too large will result in an error:

>>> word[42] # the word only has 6 characters


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: string index out of range

However, out of range slice indexes are handled gracefully when used for slicing:
>>> word[4:42]
'on'
_____________

>>> word[42:]
''
_____________

Python strings cannot be changed — they are immutable. Therefore, assigning to an indexed
position in the string results in an error:
>>> word[0] = 'J'
...
TypeError: 'str' object does not support item assignment
>>> word[2:] = 'py'
...
TypeError: 'str' object does not support item assignment

If you need a different string, you should create a new one:


>>> 'J' + word[1:]
'Jython'
_____________
6
>>> word[:2] + 'py'
'Pypy'
_____________

The built-in function len() returns the length of a string:


>>> s = 'supercalifragilisticexpialidocious'
>>> len(s)
34
_____________
The output of the command print("\033[2J") is similar to the cls
>>>print "\033[2J" command in the CMD prompt. However, in Python, the output
does not clear everything on the screen, which creates blank
Describe the output: ____________________________________________
space that acts as a new workspace in the program.

7. Use exit() or Ctrl-Z plus Return to exit from python.

You might also like