Conditional and iterative statements 01204111 Computer and Programming

  • Slides: 70
Download presentation
Conditional and iterative statements 01204111 – Computer and Programming

Conditional and iterative statements 01204111 – Computer and Programming

Agenda • Boolean expressions • Conditional statements • Iterative statements 2

Agenda • Boolean expressions • Conditional statements • Iterative statements 2

Boolean Expressions • A Boolean expression is an expression whose value is either True

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) 3

Boolean values Yes No True False 4

Boolean values Yes No True False 4

Watch out! • Python is case sensitive. I. e. , Ø False and false

Watch out! • Python is case sensitive. I. e. , Ø False and false are not equal. • For Boolean constants, use: Ø Ø True, or False 5

How to get Boolean results • Comparison operators: Ø To get Boolean result, we

How to get Boolean results • Comparison operators: Ø To get Boolean result, we compare two things Equal Not equal Greater than or equal Less than or equal == != > >= < <= 6

How to get Boolean results • Boolean operators Ø To get Boolean results, we

How to get Boolean results • Boolean operators Ø To get Boolean results, we combine or two Boolean results Boolean operators And Or Not operators and or not 7

Quick review True and False and True False and False True or False or

Quick review True and False and True False and False True or False or True False or False not True False not False True 8

Examples of Boolean expressions Suppose that variable x is 4. Expression x<5 x>5 x

Examples of Boolean expressions Suppose that variable x is 4. Expression x<5 x>5 x <= 5 5 == x x != 5 (3!=4) and (7<5) (4>4) or (5<=10) Value True False True 9

More examples • To check if x is a root of equation X 2

More examples • To check if x is a root of equation X 2 + 9 X + 10 = 0 x*x + 9*x + 10 == 0 • To check if y is an even number (y%2 == 0) or (y%2 != 1) 10

If-statement MRT Children whose height is no larger than 140 cm can enjoy a

If-statement MRT Children whose height is no larger than 140 cm can enjoy a free ride. Source: http: //www. ryt 9. com/s/prg/774090 11

If-statement • if statement evaluates a condition, and controls if the following statements shall

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. 12

Example price = 40 height<=140 False True price = 40 if height <= 140:

Example price = 40 height<=140 False True price = 40 if height <= 140: print('Hello kids!') price = 0 print('Hello kids') price = 0 print('price =', price) 13

Syntax and meaning • Statement syntax if bool-expr: statement 1 statement 2 : statement

Syntax and meaning • Statement syntax if bool-expr: statement 1 statement 2 : statement n bool-expr false true statement 1 statement 2 : statement n 14

Program flow control • Normal sequential program x = int(input()) y = int(input()) print(x+y)

Program flow control • Normal sequential program x = int(input()) y = int(input()) print(x+y) print("Hello", x) z = x * y + 10 print(z) 15

Program flow control • A program with if-statement height <= 140 True e ls

Program flow control • A program with if-statement height <= 140 True e ls Fa When height = 160 120 price = 40 if height <= 140: print('Hello kids!') price = 0 print('price =', price) 16

Block price = 40 if height <= 140: print('Hello kids!') price = 0 print('price

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 ifstatement decides whether the statements inside the block will be executed. 17

Be careful • Python uses the concept of blocks extensively. • Thus, you must

Be careful • Python uses the concept of blocks extensively. • Thus, you must be very careful about indentation. Fdskfjsdlkfslkdjfdsff fdskfsdflksdlkfdsf: fddslfldskf fdsfkdsfdsfd fdkfddfdfd fdkfdlf Good fdslkdskslkdjsld fdsfkdsfdsfd fdkfddfdfd fdkfdlf Bad fdslkdskslkdjsld 18

pass-statement for empty blocks • In Python, we cannot have an empty block. if

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") 19

Block can be nested x = int(input()) if x > 5: print("hello") if x

Block can be nested x = int(input()) if x > 5: print("hello") if x < 10: print("foofoo") print("barbar") • Guess the output for various values of x. Ø Ø Ø print("well") print("cheers") Ø Ø 3 5 7 9 10 20

Final words • Indented block is a distinctive feature of Python. Ø It is

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. 21

Thinking Corner 0 • Given two variables x and y, can you swap their

Thinking Corner 0 • 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 This again won't work. Why? This won't work. Why? t = x x = y y = t 22

Thinking Corner 1 • A candy store sales a certain kind of candy. However,

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. 23

Thinking Corner 1 (solution) if x < s: x = s 24

Thinking Corner 1 (solution) if x < s: x = s 24

Thinking Corner 1 (function) def num_candies(want, limit): if want < limit: return limit return

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. ") 25

if – else statements Source: http: //splinedoctors. com/2009/02/hurry-up-and-choose/ 26

if – else statements Source: http: //splinedoctors. com/2009/02/hurry-up-and-choose/ 26

If-else-statement • If-statement • If-else-statement 27

If-else-statement • If-statement • If-else-statement 27

if - else statement • When condition is True, statements in group T will

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 T 1 statement T 2 : statement Tn else : statement F 1 statement F 2 : statement Fn 28

Meaning true • Syntax if condition: statement T 1 statement T 2 : statement

Meaning true • Syntax if condition: statement T 1 statement T 2 : statement Tn else : statement F 1 statement F 2 : statement Fn condition false statement T 1 statement F 1 statement T 2 statement F 2 : statement Tn : statement Fn 29

Example for the if – else statement • Check if n is an even

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') 30

Program Flow Control n % 2 == 0 True print('It is an even number')

Program Flow Control n % 2 == 0 True print('It is an even number') e ls Fa print('It is an odd number') 31

Thinking Corner 2 • Based on the following table, write a program that determines

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. ') 32

Thinking Corner 3 • Write a program that reads an integer and then tells

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. 33

Thinking Corner 3 x > 0 x == 0 x < 0 34

Thinking Corner 3 x > 0 x == 0 x < 0 34

Thinking Corner 3 x > 0 True x < 0 e ls Fa x

Thinking Corner 3 x > 0 True x < 0 e ls Fa x == 0 35

Thinking Corner 3 x = int(input("Enter an integer: ")) if x > 0: print("A

Thinking Corner 3 x = int(input("Enter an integer: ")) if x > 0: print("A positive integer") else: if x < 0: print("A negative integer") else: print("A zero") • Note that we are using if-statement inside a block in another if-statement. 36

Nested if-statement • An if-statements is just a kind of statements, so we can

Nested if-statement • An if-statements is just a kind of statements, so we can write it in a block inside another if-statement 37

Example: evaluation (if) • You a given an exam: Ø Ø Ø If you

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") 38

Example: evaluation (nested-if) • You a given an exam: Ø Ø Ø If you

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") else: print("Failed") 39

Example: evaluation (nested-if) When do you get to this line? if score > 8:

Example: evaluation (nested-if) When do you get to this line? if score > 8: print("Good") score > 8 else: score <= 8 and score > 4 if score > 4: print("Passed") score <= 8 and score <= 4 else: print("Failed") score <= 4 40

Example: evaluation (elif) if score > 8: print("Good") else: if score > 4: print("Passed")

Example: evaluation (elif) if score > 8: print("Good") else: if score > 4: print("Passed") else: 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 41

if – else statements Source http: //www. flickr. com/photos/29104098@N 00/285609610/ 42

if – else statements Source http: //www. flickr. com/photos/29104098@N 00/285609610/ 42

if – else statements • if – else – statement can be used when

if – else statements • if – else – statement can be used when there are more than two choices. • Syntax if condition 1: statement 1 elif condition 2: statement 2 elif condition 3: statement 3 : : : else: statement n 43

if – else true condition 1 false statements true. statement 1 • Syntax if

if – else true condition 1 false statements true. statement 1 • Syntax if condition 1: statement 1 elif condition 2: statement 2 else: statement 3 false condition 2 . statement 3 44

Thinking Corner 4 • Write a function fun that computes the following function 2

Thinking Corner 4 • Write a function fun that computes the following function 2 x+10, x ≤ 5 f(x) = x 2+10, 5 < x ≤ 20 x-10, 20 < x < 30 3 x, x ≥ 30 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 45

Iterations Source: http: //gamedesignconcepts. wordpress. com/2009/07/02/level-2 -game-designiteration-and-rapid-prototyping/ 46

Iterations Source: http: //gamedesignconcepts. wordpress. com/2009/07/02/level-2 -game-designiteration-and-rapid-prototyping/ 46

Repetitive work • Computers are very good at doing repetitive work. • But how

Repetitive work • Computers are very good at doing repetitive work. • But how can we "program" them to do so? 47

Repetitive Work • What is the output of the following program print('I print('I like

Repetitive Work • What is the output of the following program print('I print('I like like Bossanova') Bossanova') What should we do if we want a program that prints that sentence for 2553 times? 48

Repetitive work • You can do it pretty easily with whilestatement. count = 1

Repetitive work • You can do it pretty easily with whilestatement. count = 1 while count <= 8: print('I like Bossanova') count = count + 1 What should we do if we want a program that prints that sentence for 2553 times? 49

Fa ls e How does it work? count <= 8 True print('I like Bossanova')

Fa ls e How does it work? count <= 8 True print('I like Bossanova') count = count + 1 50

while-statement • While the condition is True, the statements in the block inside the

while-statement • 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 51

While-statement • Syntax while condition: statement 1 statement 2 : statement n condition False

While-statement • Syntax while condition: statement 1 statement 2 : statement n condition False True statement 1 statement 2 : statement n 52

Example • A program that prints integers from 1 to 100 n = 1

Example • A program that prints integers from 1 to 100 n = 1 while n <= 100 : print(n) n += 1 53

Thinking Corner 5 • Write a program that prints all even number from 100

Thinking Corner 5 • Write a program that prints all even number from 100 down to 2 n = 100 while n >= 2 : print(n) n = n - 2 or n = 100 while n >= 1 : if n%2 == 0: print(n) n = n - 1 54

Thinking Corner 6 • Write a function sum_to(n) that computes 1 + 2 +

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. 55

Thinking Corner 6: hints Ø Ø Ø 1, 2, up to n e Fa

Thinking Corner 6: hints Ø Ø Ø 1, 2, up to n e Fa ls • You want to add condition True • In each round: Ø Ø What do you want to keep? What do you want to change? 56

Thinking Corner 6: more hints • First, think about the values 1, 2, …,

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: ____ i = 1 i <= n while ____: i += 1 _____ 57

Thinking Corner 6: more and more hints • What do you want to do

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. 58

Thinking Corner 6: program n = int(input()) total = 0 i = 1 while

Thinking Corner 6: program n = int(input()) total = 0 i = 1 while i <= n: total = total + i i = i + 1 print(total) 59

Thinking Corner 6: solution def sum_to(n): total = 0 i = 1 while i

Thinking Corner 6: solution def sum_to(n): total = 0 i = 1 while i <= n: total = total + i i = i + 1 return total 60

Thinking Corner 7: Password • Write a program that asks for a password until

Thinking Corner 7: Password • Write a program that asks for a password until the user enters the correct one. Ø Let the password be 'happy 204111'. Enter password: sad 111 Sorry. Enter password: happy 204111 Correct. 61

Thinking Corner 7: hints • Answer the following questions: Ø Ø Ø What condition

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? 62

Thinking Corner 7: more hints pwd = input("Enter password: ") while ___________: print("Sorry. ")

Thinking Corner 7: more hints pwd = input("Enter password: ") while ___________: print("Sorry. ") ____________________ print("Correct. ") 63

Thinking Corner 7: solutions pwd = input("Enter password: ") pwd != 'happy 204111' while

Thinking Corner 7: solutions pwd = input("Enter password: ") pwd != 'happy 204111' while ___________: print("Sorry. ") ________ pwd = input("Enter password: ") ________________ print("Correct. ") 64

Loop control • Usually how we control the loops falls into two broad categories:

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. 65

Counter-controlled repetition Look closely on the structure of this loop. def sum_to(n): total =

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 66

Thinking Corner 8 • Consider the following program n = 100 while n >=

Thinking Corner 8 • Consider the following program n = 100 while n >= 2: print(n) n = n - 2 What happen if we change the operator from =< to? => What happen if we change this line from n = n-2 to n = n + 2 67

Sentinel-controlled repetition pwd = input("Enter password: ") Look closely on the structure of this

Sentinel-controlled repetition pwd = input("Enter password: ") Look closely on the structure of this loop. while pwd != 'happy 204111': print("Sorry. ") pwd = input("Enter password: ") print("Correct. ") What is the loop waiting for? It won't stop until pwd == 'happy 204111' 68

Thinking Corner 9 total = 0 n = 0 while n >= 0: n

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 69

Thinking Corner 10 • A factorial of n (denoted by n!) is defined as

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. 70