H' L Lab-Python 1
H' L Lab-Python 1
Goals. Lab goals: (1) get you started with Python, particularly with the command shell; (2)
give you hands-on experience with Python types and errors.
There are two ways to run Python. One is to execute “scripts”, or “files” that contain
Python commands. The other is to use Python interactively, typing in just one command at
a time.
run hello1.py
Now start a text editor (e.g., Nodepad++) and create a file, called hello1.py. Add the
following lines in it:
print( 'Hello World!')
print( 'Welcome to COS4015B!')
and save the file to a new folder called Lab1 on Desktop. In order to make sure you are
working on the right directory, run this:
cd ~/Desktop/Lab1
Once again, run the script hello1.py by typing run hello1.py in the command
shell. What do you see?
Now add the the # character at the beginning of the second line, so the file now contains
print 'Hello World!'
#print 'Welcome to COS4015B!'
1
What do you see this time?
To run Python interactively, just type the scripts into the command shell (>>> represents
Python prompt). It responds to commands that you type.
>>> 1+1
and hit Return (do not type the >>>). What happens?
In is section, you use Python in interactive mode. Proceed row-wise through the tables
below. For each example (row), write down what you think the result should be. You
can cut-and-paste from this handout.
If what you see doesn’t match what you expected, try to figure out why Python gave the
answer that it did. Ask a staff member for clarification if necessary.
1 10/4
2 10./4
3 float(10/4)
4 1.0 + 10/4
5 1 + 10/4.
6 int(10/4)
7 int(3.9)
8 float(int(10.)/4)
9 int(float(10/4))
10 1.0/3.0
11 10 % 4
12 4 % 10
13 9**2
14 9**.5
15 9**(1/2)
16 4**2**0
2
2.2 Strings
Reproduce this example of string slicing by entering the first two commands
>>> s = 'abcdef'
>>> s[0:3]
'abc'
1 s[1]
2 s[0]
3 s[1:2]
4 s[0:2]
5 s[:3]
6 s[3:]
>>> s1 = '12.34'
>>> 2*float(s1)
24.68
>>> 2*int(s1[0:2])
24
>>> s2 = str(12)
>>> s2+s2
'1212'
>>> s3 = str(12.34)
1 s2+s2+s2
2 float(s1[2:4])
3 s3[2]
4 s3+s3
2.4 Errors
If you do something illegal, Python complains. Roughly, it tries to tell you the type of error
and where it occurs. In time, you will learn how to decipher error messages. For now, let’s
ignore the ”where it occurs” part and interpret the rest of the message.
3
1. If we enter
>>> 10*(5+6) = x
>>> s = 'abcdef'
>>> c = s[7]
3. If we enter
>>> s = 'abc'
>>> t = s - s
4. If we enter
>>> s = 'abc'
>>> t = s(2)