Iteration Chapter 7 Prof. Mauro Gaspari: gaspari@cs.unibo.it
Multiple assigments bruce = 5 print bruce, bruce = 7 print bruce
Assigment and equality With multiple assignment it is especially important to distinguish between an assignment operation (=) and a statement of equality (==). Equality is a symmetric relation and assignment is not. Furthermore, in mathematics, a statement of equality is either true or false, for all time. If a = b now, then a will always equal b. In Python, an assignment statement can make two variables equal, but they don t have to stay that way: a = 5 b = a # a and b are now equal a = 3 # a and b are no longer equal
Updating variables One of the most common forms of multiple assignment is an update, where the new value of the variable depends on the old. X = X + 1 If you try to update a variable that doesn t exist, you get an error. Before you can update a variable, you have to initialize it, usually with a simple assignment: Updating a variable by adding 1 is called an increment; subtracting 1 is called a decrement.
Iteration Computers are often used to automate repetitive tasks. Repeating identical or similar tasks without making errors is something that computers do well and people do poorly. We can program repetition with recursion, however: The programming task is sometimes difficult. Maximum recursion depth problem. Python provides several language features to make repetition easier. One is the while statement and another is the for statement.
The while statement: def countdown(n): while n > 0: print n n = n 1 print "Blastoff!" Note: recursion is not used. You can almost read the while statement as if it were English. It means, While n is greater than 0, display the value of n and then reduce the value of n by 1. When the condition becomes false the while terminates and the next instruction is executed.
Semantics of while 1) Evaluate the boolean condition. 2) If the condition is false, exit the while statement and continue execution at the next statement. 3) If the condition is true, execute the body and then go back to step 1. This type of flow is called a loop because the third step loops back around to the top. The body of the loop should change the value of one or more. variables so that eventually the condition becomes false and the loop terminates. Otherwise the loop will repeat forever (infinite loop).
Examples def nlines(n): while n!= 0: print n = n 1 What happens if you remove the last line?
Try this example while True: print Sorry
break Sometimes you don t know it s time to end a loop until you get half way through the body. In that case you can use the break statement to jump out of the loop. Suppose you want to take input from the user until they type exit. while True: line = raw_input('>> ') if line == 'exit': break print line print 'Stopped!'
Exercise 1 Write a dummy python interpreter using while and break to exit. The dummy interpeter returns False when reads True and viceversa, otherwise always returns syntax error.
Tables One of the things loops are good for is generating tabular data. Tables can be useful for displaying financial data. As characters and strings are displayed on the screen, an invisible marker called the cursor keeps track of where the next character will go. After a print statement, the cursor normally goes to the beginning of the next line. The tab character shifts the cursor to the right until it reaches one of the tab stops. Tabs are useful for making columns of text line up.
Example of a table The following program outputs a sequence of values in the left column and their logarithms in the right column: import math x = 1.0 while x < 20.0: print x, '\t', math.log(x) x = x + 1.0
Considerations Remember that the log function uses base e. Since powers of two are so important in computer science, we often want to find logarithms with respect to base 2. To do that, we can use the following formula: log 2 (x) = log e (x)/log e (2) The log 2 table can be computed changing the output statement to: print x, '\t', math.log(x)/math.log(2.0)
Exercise 2 Modify the program to show logarithms of other powers of two only. Hint: x should be a power of two.
A string is a sequence A string is a sequence of characters. You can access the characters one at a time with the bracket operator: Example >>> fruit = "banana" >>> letter = fruit[1] >>> print letter a The expression in brackets is called an index. Why 'a'??? The first letter of banana is not 'a'.
Understanding strings The index is an offset from the beginning of the string, and the offset of the first letter is 0. So if a string has n chars its indexes ranges from 0 to n-1. You can use any expression, including variables and operators, as an index, but the value of the index has to be an integer. >>> letter = fruit[0] >>> letter2 = banana [0] >>> print letter b >>> type(letter) <type 'str'> >>> print letter2 b
Length of a string: len >>> fruit = "banana" >>> len(fruit) 6 Accessing the last letter: length = len(fruit) last = fruit[length] last = fruit[length 1] # ERROR!
Traversal with a for loop index = 0 while index < len(fruit): letter = fruit[index] print letter index = index + 1 It is possible to specify this in this way: for char in fruit: print char
Example >>>prefixes = "JKLMNOPQ" >>>suffix = "ack" >>>for letter in prefixes:... print letter + suffix Jack Kack Lack Mack Nack Oack Pack Qack
Exercise 3 Write a function indent_string(n,string) which prints the string n+1 times indenting it from 0 to n as follows: indent_string(5, duffy ) duffy duffy duffy duffy duffy duffy n+1 Hint: use the expression ' '*i to print i blanks.
Exercise 4 GREATEST COMMON DIVISOR IMPERATIVE KNOWLEDGE (EUCLID) IF A<B, exchange A and B. Divide A by B and get the remainder, R. If R=0, GCD(A,B) = B. Replace A by B and replace B by R. Return to the previous step. Write a function gcd that takes two arguments and returns the greatest common divisor.