Exercises Pythonbasics Exercises v1.0
Exercises Pythonbasics Exercises v1.0
Check all syntactically correct statements. 1.) Which input statements are correct? a = raw_input() a = raw_input(enter a number) a = raw_input(enter your name) 5.) Which are correct type conversions? int(7.0+0.1) str(1.2 * 3.4) float(77+.0) str( 9 / 0 ) 2.) Which print statements are correct? print 9 + 9 print int(nine) print str(9) + nine print 9 + 9 nine = 9 print nine 3.) Which are correct arithmetical operations? a = 1 * 2 2 = 1 + 1 5 + 6 = y seven = 3 * 4 4.) Which are correct variable names? result my.result print result77
K. Rother, A. Philips & K. Milanowska
7.) Which lines are commented? This is a comment # This is a comment // this is a comment '''This is a comment'''
Data Types
Find the matching pairs of expressions and values.
1023
boolean
None
int
[2, 4, 8, 16]
tuple
True
list
17.54
str
dict
NoneType
{'name':'Roger', 'birth':1952}
float
Manipulating Strings
Write the result of each operation into the fields.
s.startswith(cat)
s.split()
s.replace(c,r)
s[-6]
s = my fat cat\n
s.find(fat)
s.upper()
s[7:10]
s.strip()
String formatting
Find the matching pairs of expressions and values.
expressions
"R.%s"%("GB")
values
3. RGB
"%2i. %4s"%(3,"RGB")
3.14
"%5.2f"%3.1415
R.GB
'%s\t%s\tRG'%(B,'\t')
RG
7B
"%5i"%(3.1415)
"RG%4iB"%(7)
RG
Regular Expressions
Find the expressions that fit to each row.
found
ROMA ROMA ROMA ROMA R123 ROMA
found
ROZA ROOMA RO MA OMAR R456 REMY
found
ROPA ROOOMA
excluded
HORA ROMMA ROLMA
Expression
AMOR
TORA ROMA
RICO
COMA
An optional parameter
An import statement
A package
Every package
A function in Python
A function
Manipulating Lists
Write the result of each operation into the fields.
li[1:-1]
li.count(0)
li[2]
li.append(A)
li = [2,0,1,0]
li.sort()
2 in li
li.pop()
len(li)
1
a = ['A','B','c',None,3]
2 3
a == ['A','B','B','c',None,3]
4 5
a == ['B','c',None]
a == ['c','c']
a == ['c','c','c']
a == ['c','c']
a = [1,3,4,5]
1 2
a == [1,3,4]
3 4
a == [1,3,4,5,3]
5 6
a == [3,5,4,3,1]
a == [3,4,3,1]
a == [1,3,3,4]
a == [1,3,3,4,4]
K. Rother, A. Philips & K. Milanowska
sum(b)
sum(range(5))
range(3)
a = ['a','b','c'] b = [10,12,14,16]
Manipulating Lists
Check the correct answer. 1.) What does the list b contain? a = [8,7,6,5,4] b = a[2:4] [7,6,5] [7,6] [6,5] [6,5,4] 2.) Which of the following code pieces results in a == [2,4,6] a = [1,2,3] * 2 a = [int(s) for s in 246] a = [x*2 for x in range(3)] a = [2**1]+[2**2]+[2**3]
3.) On what data types does the len() function work on? lists dictionaries. strings. tuples.
Manipulating Dictionaries
Write the result of each operation into the fields.
len(d)
d.has_key(3)
d.keys()
d.setdefault(2,)
d = { 1:A, 3:X }
d[3] = B
d.values()
d[A]
d.get(1)
Manipulating Dictionaries
Check the correct answer. 1.) What do these commands produce? d = {1:'A', 'B':1, 'A':True} print d['A'] False B True 1 2.) What do these commands produce? d = {1:'A', 'B':1, 'A':True} print d.has_key('B') 1 True 'B' False 3.) What do these commands produce? d = {1:'A', 'B':1, 'A':True} print d.values() True ['A',1,True] 3 [1,'B','A'] 4.) What do these commands produce? d = {1:'A', 'B':1, 'A':True} print d.keys() [1,'B','A'] ['A','B',1] [1,'A','B'] The order may vary. 5.) What do these commands produce? d = {1:'A', 'B':1, 'A':True} print d['C'] None 'C' an Error False 6.) What do these commands produce? d = {1:'A', 'B':1, 'A':True} d.setdefault('C',3) print d['C'] 3 C None an Error
K. Rother, A. Philips & K. Milanowska
5.) Which of these if statements are syntactically correct? if a and b: if len(s) == 23: if a but not b<3: if a ** 2 >= 49: if a != 3: if (a and b) or (c and d):
3.) What are possible structures of a conditional statement? if <expression> .. else if <expression> .. else if <expression> if <expression> .. elif <expression> .. else if <expression> .. elif <expression> ..else <expression> If <expression>.. else <expression> .. efli
4.) Which packages are installed by default? os manipulating files and directories. psyco makes Python faster time accessing date and time. csv reads and writes tables. numpy number crunching. pdb Python debugging.
While loops
Match the expressions for the while loops run the designated number of times
a = 5 while : a = a -1
5x
a = 2 while : a += 4
a != 0
a >= 0
5x
a = 2 while : a = -a * 2
a < 19
2x
a = 7 while : a -= 2 abs(a) < 7
4x
Files
Close a file.
Error Handling
Check all correct answers. 1.) Which commands result in an Exception? f = open(:::) char = abc[7] a = (5+9) / (6-(2*3)) num = [1,2,3][0] l = range(10)[:20] num = {1:'a'}['a'] 2.) Which are common types of Exceptions? ZeroDivisionError IOError ValueError NullPointerException KeyError InfiniteLoopError 3.) Which commands for managing Exceptions exist? try: else: ... raise ValueError('text') try: except: error: try: except: ...
Language Basics
What is a variable? What names may variables have? What is an integer? What is a string? How to assign a variable? How to add, substract, and multiply numbers? What can be printed with print? How can text be read from the keyboard? How are comments written in a program?
functions
y = math.cos(x)
values
x = 180 y == 3.14159..
y = math.radians(x)
x = 1
y == 3.14159..
y = math.factorial(x)
x = 81
y == 9.0
y = math.pi * x
x = 32
y == 5.0
y = math.sqrt(x)
x = 6.28318..
y == 1.0
y = math.log(x,2)
x = 4
y == 24
The os module
Insert the correct functions into the gaps.
is very useful for interactions with the operating system. In fact, it is a . Before any of them can be used, the modules need to be function, that returns a list of all files in the given . statement.
directory. If a program already has a filename, but it needs to be checked whether the file really exists, will return True or False. If a file needs to be deleted, this can be done using , that separates a file name from directory names. - However, A very useful feature of the os.path module is that it helps operating with directory names. Probably the most frequently used function is But os can do even more: You can use any shell command from a Python program with
this method has disadvantages: it depends on the operating system, and is a potentially insecure.
1 2 3 4
5 6 7 8
Creating plots
Write the result of each operation into the fields. 1.) Which of these for commands are necessary to create a figure in matplotlib?
p = plot(x_data,y_data, 'k-') title(''Name of the graph') xlabel('x axis name') axis([0,15,0,10]) savefig('figure1.png' show()