Download Python Exercise Set 1: Basic Concepts

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Python Exercise Set 1: Basic Concepts
Some exercises adapted from “The Python Tutorial”, by G. van Rossum, and “Introduction to Programming using Python: Programming Course for
Biologists at the Pasteur Institute”, by K. Schuerer,
C. Maufrais, C. Letondal, E. Deveaud, and M. Petit
Terminology The operating system command
shell (e.g. bash) will be referred to as the command
shell and will generally have have a $ sign in the
prompt. The Python interactive shell will be referred to as the Python shell and will have a prompt
of >>>. Some commands are executed using the
command shell, while others from the Python shell.
Please check the instructions carefully to know
which to use.
>>> float (1 / 2)
>>> 1 / 2.0
>>> 1/ float (2)
# Floating point math operations
>>> 3 * 3.75 / 1.5
# Numeric variables
>>> width = 20
>>> height = 5*9
>>> width * height
# Group initialization
>>> x = y = z = 0
>>> a ,b , c = 5 ,10 ,20
# Use of " _ " variable for the last result
>>> tax = 12.5 / 100
>>> price = 100.50
>>> price * tax
>>> price + _
>>> round (_ , 2)
Part A: Starting Python
1. Start the standard Python interpreter using an
icon on the desktop or Dock, or via a Terminal command shell session and the command
python. To exit from the Python shell, type
CTRL-d.
2. Sometimes you want to know what kind of variable you are dealing with. This can be achieved
by the type() method.
>>>
>>>
>>>
>>>
2. At the command shell, execute python -V to
check the python version installed.
Part B: Literals, Expresions, Variables, and
Syntax
type (3)
type (3.0)
type ( ’3 ’)
type ( tax )
3. For the next set of questions, consider the sample Python code below:
1. Execute the following commands from the
Python shell, but try to guess the result of each
operation first. Ask an instructor if you don’t
understand.
# if / elif / else
import random
grade = random . randint (1 ,100)
# Integer math operations
>>> 2+2
>>> 7/3
if grade >= 80:
print " top student "
elif grade >= 60:
print " pass "
else :
print " fail "
# Use float () to coerce value
# from integer to floating point :
1
Python Exercise Set 1: Basic Concepts
nested blocks and lists. Note the special characters by putting a blue dot below them.
# while loop : Fibonacci
a, b = 0, 1
while b < 1000:
print b ,
a, b = b, a+b
print " done "
11. There are a few other aspects of the Python
language which show up in the example but
are not included in the categories above. Are
there any parts of the example Python program
# for loop : using implicit iterator
do you not understand, in terms of syntax or
mylist = [ ’ cat ’ , ’ window ’ , ’ defenestrate ’]
behavior?
mylist . sort ()
for item in mylist :
print item , len ( item )
Part C: Literals, Expresions, Variables, and
Syntax
4. Reserved words: Along with special characters and operators provide the framework for a
programming language. Highlight these in the
code.
1. Python has powerful and easy to use “grouped
object” functionality. Square brackets are used
to define Lists, and for indexing into lists. Note
that Python indexes from zero (the first element in a group is accessed with [0]). Look
at each statement below and try to guess what
the output is before entering it yourself into the
Python interactive interpreter.
5. Literals: These are strings and numbers. Underline these in red.
6. Variables: Provides a named reference to an
”object”. The object may be a string, a number, a list, or some other ”data type”, or ”object class”. Underline these in blue.
>>> numbers
= [12 , 35 , 4 , -32 , 81 , 24]
>>> mixed
= [3 , ‘‘ Tuesday ’ ’ , 7.8 , (45 , 72)]
>>> more_numbers = [ -5 , -3 , 7 , 12 , 4 , 9]
>>> add_numbers
= numbers + more_numbers
>>> mult_numbers = numbers * 3
>>> len ( numbers )
>>> 12 in numbers
>>> 99 in numbers
>>> numbers [0]
>>> numbers [4]
>>> numbers [ -1]
>>> numbers [ -2]
>>> numbers [ len ( numbers ) - 2]
7. Comments: These allow the programmer to
include arbitrary text describing a variable, a
function, an algorithm, or just to leave a note
saying a particular part of a program needs to
be fixed, or has some shortcoming. Place a red
dot beside all comment lines.
8. Functions: These encapsulate a set of operations, possibly with a set of parameters which
vary the behavior. Function calls in Python are
always indicated by a word (the function name)
followed by round brackets, even if there are no
parameters. Put a red box around each function call and a blue box around the function
parameters.
2. Python has four “group” types: Lists, Tuples, Dictionaries, and Sets. It is often desireable to operate on more than one element
from the group, and to do this Python provides
“slices” which select a subset of elements from
the group, as illustrated in the following exercise. Notice that the second index for the slice
is not included in the resulting group.
9. Operators: These typically use ”infix” notation with two operands and perform operations such as addition or comparison. Underline these in black.
>>> numbers [0:3]
>>> numbers [3:6]
>>> numbers [:3]
10. Special characters: These provide delimiters
(start and stop points) for tokens, such as
2
Python Exercise Set 1: Basic Concepts
5. Use the for <item> in <list>: loop to print
out every item in long numbers, one per line.
>>> numbers [ -4: -2]
>>> numbers [ -3: -1]
>>> numbers [ -3:]
6. Dictionaries (also called Hash Maps in other
languages) are a powerful way to associate a
value with a key. Create a dictionary as follows:
Note three things: when a range starts from
zero, the first index can be ignored; when a
range finishes with the length of the list, it can
be ignored; and that negative values index from
the end of the list backwards (e.g. −3 is 3 elements from the end).
>>> bob ={ " name " : " Bob " , " id " :3 , " age " :42}
7. You can access a dictionary value by using its
key as the reference:
3. It is also possible to use slice notation to overwrite, insert, and delete parts of a set. Inspect
long numbers after each operation to see the
current value of the variable
>>> bob [ " name " ]
8. Adding new key/value pairs to the dictionary
>>> long_nums = ( numbers + more_numbers ) * 2 is simple:
>>> long_nums [12:15] = [3 , 4 , 5] # replace
>>> bob [ " gender " ] = " male "
>>> long_nums [4:8]
= []
# delete
>>> long_nums [2:2]
= [1 ,2 ,3]
9. Anything can be assigned as a dictionary value,
# insert
but only immutable types may be used as keys.
# replace + insert
For example here we add a key location which
>>> long_nums [7:10] = [4 ,5 ,6 ,7 ,8 ,9 ,0]
is a latitude/longitude tuple:
4. There are more methods available for easily
working with sets. Here you will see the object oriented nature of Python, as these are all
methods on the list object. After each statement, print out long numbers to see what it
contains. Note that methods that change the
list object are not valid for immutable tuples or
strings, although both of these can be coerced
into a list with the list() function.
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>> bob [ " location " ] = (42.19 , -71.05)
You can equally add a list, another dictionary,
or some more complex object.
10. Dictionaries have several special built-in operations. Execute the statements below to observe
some of these:
>>>
>>>
>>>
>>>
long_nums . count (4)
long_nums . append (22)
long_nums . extend ([8 ,27 ,64])
long_nums . insert (5 ,27)
long_nums . count (27)
long_nums . index (22)
long_nums . reverse ()
long_nums . sort ()
long_nums . pop ()
long_nums . remove (27)
long_nums . append ([100 ,200 ,300])
bob . keys ()
bob . values ()
bob . has_key ( " name " )
bob . has_key ( " address " )
11. Write a for loop which outputs the key/value
pairs for the dictionary variable bob.
12. Create your own dictionaries for two more variables named sally and stuart. Add these dictionaries to a list.
>>> employees = [ bob , sally , stuart ]
Notice
the
difference
between
the
long numbers.append()
operation
and
long numbers.extend(). If you are extending
a list with another list, you want to use
extend().
13. Use a for loop which outputs the id value for
all the employees.
14. Create a tuple to hold your birthdate.
3
Python Exercise Set 1: Basic Concepts
>>> birthday = (05 ,02 ,1975)
15. Now try to extend this tuple to add your name
at the end. What happens? Do you know why?
Try changing the year by assignment.
>>> birthday . extend ( " Ian " )
>>> birthday [2] = 1980
Part D: Bonus
1. We are now going to experiment with some of
the examples shown in the lesson. To do this,
you will need to access course files.
2. From the Terminal command shell, change to
your Python directory, make the .py files executable, and then run them.
cd / path / to / course / files
chmod a + x program . py
./ program . py
3. Modify class average.py to print out grades
A, B, C, D, or Fail, depending on the result.
Run it several times to test it.
4. Modify class average.py to automatically
run 30 times, printing out the letter and numeric grade for each student. Hint: Consider
using for and range.
Python Reserved Words
and
as
assert
break
class
continue
def
del
elif
else
except
exec
finally
for
from
global
if
import
in
is
lambda
not
or
pass
print
raise
return
try
while
with
yield
4