Conditional and iterative statements 01204111 – Computer and Programming
Agenda Boolean expressions Conditional statements Iterative statements
Boolean Expressions A Boolean expression is an expression whose value is either True or False. Examples: Do you want the coffee? (yes/no) Is x greater than 10? (yes/no) Have you found the answer? (yes/no) Does 5 divide 153? (yes/no)
Boolean values Yes True No False
Watch out! Python is case sensitive. I.e., For Boolean constants, use: False and false are not equal. For Boolean constants, use: True, or False
How to get Boolean results Comparison operators: To get Boolean result, we compare two things Equal == Not equal != Greater than > Greater than or equal >= Less than < Less than or equal <=
How to get Boolean results Boolean operators To get Boolean results, we combine one or two Boolean results Boolean operators operators And and Or or Not not
Quick review True and True True True and False False False and True False and False not True False not False True True or True True True or False False or True False or False False
Examples of Boolean expressions Suppose that variable x is 4. Expression Value x < 5 x > 5 x <= 5 5 == x x != 5 (3!=4) and (7<5) (4>4) or (5<=10) True False True False True False True
More examples x*x + 9*x + 10 == 0 (y%2 == 0) (y%2 != 1) To check if x is a root of equation X2 + 9X + 10 = 0 x*x + 9*x + 10 == 0 To check if y is an even number (y%2 == 0) or (y%2 != 1)
Source: http://www.ryt9.com/s/prg/774090 If-statement MRT Children whose height is no larger than 140cm can enjoy a free ride. Source: http://www.ryt9.com/s/prg/774090
If-statement if statement evaluates a condition, and controls if the following statements shall be executed. The statements inside the block will be executed when the condition is True.
Example price = 40 False height<=140 True print('Hello kids') True price = 0 False print('price =',price) price = 40 price = 40 if height <= 140: print('Hello kids!') price = 0 print('price =',price)
Syntax and meaning false bool-expr true statement 1 statement 2 : statement n false Statement syntax if bool-expr: statement 1 statement 2 : statement n
Program flow control Normal sequential program x = int(input()) y = int(input()) print(x+y) print("Hello",x) z = x * y + 10 print(z)
Program flow control A program with if-statement price = 40 height <= 140 True False price = 40 if height <= 140: print('Hello kids!') price = 0 print('price =',price) When height = 160 When height = 120
Block The aligned indented statements are grouped into a block. price = 40 if height <= 140: print('Hello kids!') price = 0 print('price =',price) The aligned indented statements are grouped into a block. A condition in the if-statement decides whether the statements inside the block will be executed.
Good Bad Be careful Python uses the concept of blocks extensively. Thus, you must be very careful about indentation. Fdskfjsdlkfslkdjfdsff fdskfsdflksdlkfdsf: fddslfldskf fdsfkdsfdsfd fdkfddfdfd fdkfdlf fdslkdskslkdjsld Fdskfjsdlkfslkdjfdsff fdskfsdflksdlkfdsf: fddslfldskf fdsfkdsfdsfd fdkfddfdfd fdkfdlf fdslkdskslkdjsld Good Bad
pass-statement for empty blocks In Python, we cannot have an empty block. if height <= 140: print("I'm here") X If you want a block that does nothing, put the pass statement inside it. if height <= 140: pass print("I'm here")
Block can be nested Guess the output for various values of x. 3 5 7 9 10 x = int(input()) if x > 5: print("hello") if x < 10: print("foofoo") print("barbar") print("well") print("cheers")
Final words Indented block is a distinctive feature of Python. It is one of the reason people like Python. Be careful about indentation and blocks.
Thinking Corner 0 x = y Y = x y = x x = y t = x x = y y = t Given two variables x and y, can you swap their values? E.g., if x = 10 and y = 25, after executing your program, x = 25 and y = 10. x = y Y = x y = x x = y t = x x = y y = t This again won't work. Why? This won't work. Why?
Thinking Corner 1 A candy store sales a certain kind of candy. However, it has a condition that the number of candies must be at least some limit s. Given that variable x equals the actual number of candies you want to buy, write a program that modifies x so that it is the number of candies you end up buying. E.g., For s = 5 and x = 7, at the end x = 7. For s = 10 and x = 5, at the end x = 10.
Thinking Corner 1 (solution) if x < s: x = s
Thinking Corner 1 (function) def num_candies(want, limit): if want < limit: return limit return want limit = 20 x = int(input("How many?")) print("You should buy", num_candies(x,limit), "candies.")
Source: http://splinedoctors.com/2009/02/hurry-up-and-choose/ if – else statements Source: http://splinedoctors.com/2009/02/hurry-up-and-choose/
If-else-statement If-statement If-else-statement
if - else statement When condition is True, statements in group T will be executed. When condition is False, statements in group F will be executed. Syntax if condition: statement T1 statement T2 : statement Tn else : statement F1 statement F2 : statement Fn
Meaning Syntax condition statement T1 true statement T2 : statement Tn false statement F1 statement F2 statement Fn Syntax if condition: statement T1 statement T2 : statement Tn else : statement F1 statement F2 : statement Fn
Example for the if – else statement Check if n is an even number or an odd number. Value in N Output Even Number It is an even number. Odd Number It is an odd number. if n%2 == 0: print('It is an even number') else: print('It is an odd number')
Program Flow Control n % 2 == 0 print('It is an even number') True False print('It is an odd number')
Thinking Corner 2 Based on the following table, write a program that determines if your score will pass the exam. score Output Less than 50 You failed. Other You passed. if score<50: print('You failed.') else: print('You passed.')
Thinking Corner 3 Write a program that reads an integer and then tells if it is a positive integer, a negative integer, or a zero.
Thinking Corner 3 x > 0 x == 0 x < 0
Thinking Corner 3 x > 0 x < 0 x == 0 x > 0 x < 0 True False x == 0 False
Thinking Corner 3 x = int(input("Enter an integer:")) if x > 0: print("A positive integer") else: if x < 0: print("A negative integer") print("A zero") Note that we are using if-statement inside a block in another if-statement.
Nested if-statement An if-statements is just a kind of statements, so we can write it in a block inside another if-statement
Example: evaluation (if) You a given an exam: If you score > 8, then you are good If you score > 4 but <= 8, you pass If you score <= 4, you fail. if score > 8: print("Good") if score > 4 and score <= 8: print("Passed") If score <= 4: print("Failed")
Example: evaluation (nested-if) You a given an exam: If you score > 8, then you are good If you score > 4 but <= 8, you pass If you score <= 4, you fail. if score > 8: print("Good") else: if score > 4: print("Passed") print("Failed")
Example: evaluation (nested-if) When do you get to this line? if score > 8: print("Good") else: if score > 4: print("Passed") print("Failed") score > 8 score <= 8 and score > 4 score <= 8 and score <= 4 score <= 4
Example: evaluation (elif) if score > 8: print("Good") else: if score > 4: print("Passed") print("Failed") if score > 8: print("Good") elif score > 4: print("Passed") else: print("Failed") This flow structure can be made more clear, using elif
if – elif – else statements Source http://www.flickr.com/photos/29104098@N00/285609610/
if – elif – else statements Syntax if – elif – else – statement can be used when there are more than two choices. if condition1: statement 1 elif condition2: statement 2 elif condition3: statement 3 : : : else: statement n
if – elif – else statements condition1 . statement 1 true false condition2 statement 2 statement 3 Syntax if condition1: statement 1 elif condition2: statement 2 else: statement 3
Thinking Corner 4 Write a function fun that computes the following function def fun(x): if x <= 5: return 2*x + 10 elif x <= 20: return x*x + 10 elif x < 30: return x*x*x + 10 else: return 3*x f(x) = 2x+10, x ≤ 5 x2+10, 5 < x ≤ 20 x-10, 20 < x < 30 3x, x ≥ 30
Iterations Source: http://gamedesignconcepts.wordpress.com/2009/07/02/level-2-game-design-iteration-and-rapid-prototyping/
Repetitive work Computers are very good at doing repetitive work. But how can we "program" them to do so?
print('I like Bossanova') Repetitive Work What is the output of the following program What should we do if we want a program that prints that sentence for 2553 times? print('I like Bossanova')
Repetitive work You can do it pretty easily with while-statement. What should we do if we want a program that prints that sentence for 2553 times? count = 1 while count <= 8: print('I like Bossanova') count = count + 1
How does it work? count <= 8 print('I like Bossanova') False count <= 8 True print('I like Bossanova') count = count + 1
while-statement Syntax While the condition is True, the statements in the block inside the while statement are executed. The condition is checked before every round. Syntax while condition: statement 1 statement 2 : statement n
While-statement Syntax condition statement 1 True statement 2 : statement n False while condition: statement 1 statement 2 : statement n Syntax
Example A program that prints integers from 1 to 100 n = 1 while : print(n) n = 1 n <= 100 n += 1
Thinking Corner 5 Write a program that prints all even number from 100 down to 2 n = 100 while : while : print(n) n = 100 n >= 2 n >= 1 or if n%2 == 0: print(n) n = n - 2 n = n - 1
Thinking Corner 6 Write a function sum_to(n) that computes 1 + 2 + … + n. Please don't use the formula n*(n+1)/2. You can start by writing a program that computes that and then turning it into a function.
Thinking Corner 6: hints You want to add 1, 2, up to n In each round: What do you want to keep? What do you want to change? condition False True
Thinking Corner 6: more hints First, think about the values 1, 2, …, n. We will use variable i to keep tracks of these number. Write a loop that do just this: ________ while ________: _________ i = 1 i <= n i += 1
Thinking Corner 6: more and more hints What do you want to do with i. Keep the summation You will need a variable for it.
Thinking Corner 6: program n = int(input()) total = 0 i = 1 while i <= n: total = total + i i = i + 1 print(total)
Thinking Corner 6: solution def sum_to(n): total = 0 i = 1 while i <= n: total = total + i i = i + 1 return total
Thinking Corner 7: Password Write a program that asks for a password until the user enters the correct one. Let the password be 'happy204111'. Enter password: sad111 Sorry. Enter password: happy111 Enter password: happy204111 Correct.
Thinking Corner 7: hints Answer the following questions: What condition do keep your loop going? What do you want to do in each iteration? What do you have to do before checking the first condition?
Thinking Corner 7: more hints pwd = input("Enter password: ") while ______________________: ____________________ print("Correct.") print("Sorry.")
Thinking Corner 7: solutions pwd = input("Enter password: ") while ______________________: _______________ ________________________________ print("Correct.") pwd != 'happy204111' print("Sorry.") pwd = input("Enter password: ")
Loop control Usually how we control the loops falls into two broad categories: Counter-controlled repetition Sentinel-controlled repetition Note: This clearly is not exhaustive. There are other ways of controlling loop.
Counter-controlled repetition Look closely on the structure of this loop. def sum_to(n): total = 0 i = 1 while i <= n: total = total+i i = i + 1 return total Initialization Condition Updates
Thinking Corner 8 Consider the following program What happen if we change the operator from >= to <= ? n = 100 while n >= 2: print(n) n = n - 2 What happen if we change this line from n = n-2 to n = n + 2
Sentinel-controlled repetition pwd = input("Enter password: ") while pwd != 'happy204111': print("Sorry.") print("Correct.") Look closely on the structure of this loop. What is the loop waiting for? It won't stop until pwd == 'happy204111'
Thinking Corner 9 total = 0 n = 0 while n >= 0: n = input('Input n : ') if n >= 0: total = total + n print('total =", total) What is this loop waiting for? It won't stop until n < 0
Thinking Corner 10 A factorial of n (denoted by n!) is defined as 1 x 2 x … x n, or 1 when n = 0. Write a function fact(n) that computes the value of n!. For the first version, you can ignore the case when n=0.