























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
Prepare for your exams
Study with the several resources on Docsity
Earn points to download
Earn points by helping other students or get them with a premium plan
The third lecture notes for the cs 696 - introduction to ci & grid computing course at san diego state university. It covers the topics of control statements (if, while, for) and functions in python programming language.
Typology: Study notes
1 / 31
This page cannot be seen from the preview
Don't miss anything!
























http://www.python.org/doc/current/tut/tut.html
Out of print, but we will get electronic copy soon.
if while for Basic Structure
Block are indicated by indentation Space Tab Indentation always indicates a block Following does not compile print "Good Start" print "This is a compile error"
while
break Jump out of closest enclosing loop continue Jump to top of the closest enclosing loop pass Does nothing, empty statement
while x<5: ... x=x+ ... print x ...
1 2 3 4 5
while x<5: ... x=x+ ... if x == 3: ... break ... print x ... x= while x<5: ... x=x+ ... if x == 3: ... break ... print x ... 1 2
range(5) [0, 1, 2, 3, 4] range(5, 10) [5, 6, 7, 8, 9] range(5, 10, 3) [5, 8] for k in range(10): print k, #prints 1 2 3 4 5 6 7 8 9 for k in range(1, 20, 2): print k #prints odd number < than 20 list = ['cat', 'rat', 'bat']
for k in range(len(list)): print k, list[k], range(upto) range(start, upto) range(start, upto, increment)
def fibonacci(n): result = [] a, b = 0, 1 while b < n: result.append(b) a,b = b,a+b return result def doesNothing(): pass print fibonacci(20) print doesNothing() Output [1, 1, 2, 3, 5, 8, 13] None Can define default arg values def f(a=5): or use key-value pairs Def f( action=‘go’ )
What does this print? x = 10 def whichValue(x): print x whichValue(5)
Each call to a function creates a new local scope Arguments to the function are local Assigned names are local, unless declared global x = 10 def printGlobal(): print x printGlobal() # prints 10 x = 5 printGlobal() # prints 5 x = 10 def printLocal(): x = 5 #Makes a local x print x
x = 10 def globalDeclaration(): global x x = 5 globalDeclaration() print x # prints 5 Seems like something to avoid
def factorial(x): if x == 1: return 1 else: return x * factorial(x - 1) print factorial(4)
def defaultValues(x, y=10): return x + y defaultValues(2,3) #returns 5 defaultValues(2) #returns 12 ouch = 1 def tricky(x = ouch ): print x tricky() ouch = 2 tricky() Output 1 1
def concat(x, y, z): return x + y + z concat('a', 'b', 'c') #'abc’ concat('a', z='b', y='c') #'acb’ concat('a', y='c',z='b') #'acb’ concat(y='a', x='c',z='b') #'cab'