Presentation is loading. Please wait.

Presentation is loading. Please wait.

Conditional and iterative statements

Similar presentations


Presentation on theme: "Conditional and iterative statements"— Presentation transcript:

1 Conditional and iterative statements
– Computer and Programming

2 Agenda Boolean expressions Conditional statements Iterative statements

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

4 Boolean values Yes True No False

5 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

6 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 <=

7 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

8 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

9 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

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

11 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:

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

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

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

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

16 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

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

18 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

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

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

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

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

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

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

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

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

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

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

29 Meaning Syntax condition statement T1 true statement T2 : statement Tn
false statement F1 statement F2 statement Fn Syntax if condition: statement T statement T : statement Tn else : statement F statement F : statement Fn

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

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

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

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

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

35 Thinking Corner 3 x > 0 x < 0 x == 0 x > 0 x < 0 True
False x == 0 False

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

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

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

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

40 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

41 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

42 if – elif – else statements
Source

43 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

44 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

45 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, < x < 30 3x, x ≥ 30

46 Iterations Source:

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

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

49 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

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

51 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 statement : statement n

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

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

54 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

55 Thinking Corner 6 Write a function sum_to(n) that computes … + 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.

56 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

57 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

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

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

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

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

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

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

64 Thinking Corner 7: solutions
pwd = input("Enter password: ") while ______________________: _______________ ________________________________ print("Correct.") pwd != 'happy204111' print("Sorry.") pwd = input("Enter password: ")

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

66 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

67 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

68 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'

69 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

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


Download ppt "Conditional and iterative statements"

Similar presentations


Ads by Google