Presentation is loading. Please wait.

Presentation is loading. Please wait.

Python: Control Structures

Similar presentations


Presentation on theme: "Python: Control Structures"— Presentation transcript:

1 Python: Control Structures
Dennis Y. W. Liu (Adapted from John Zelle’s slides)

2 Objectives To understand the programming pattern simple/two-way/multiway decision and its implementation using a Python if/if-else/if-elif-else statement. To understand the concept of Boolean expressions and the bool data type To be able to read, write, and implement algorithms that employ decision structures, including those that employ sequences of decisions and nested control structures. To understand the concepts of definite and indefinite loops as they are realized in the Python for and while statements. To understand the programming patterns interactive loop and sentinel loop and their implementations using a Python while statement. To understand the programming pattern end-of-file loop and ways of implementing such loops in Python.

3 Control structures Sequential control vs selection control vs iterative control A control statement is a statement that determines the control flow of a set of statements. A control structure is a set of statements and the control statements controlling their execution. Three fundamental forms of control in programming are Sequential Selection Iteration. Python Programming, 1/e

4 Simple decisions For example,
if n < 1: print("Your input number is too low.") if n > 10000: print("Your input number is too large.") A relational statement gives either True or False (Python's keywords) Try print(int(True)) print(int(False))

5 To do or not to do The Python if statement is used to implement the decision. if <condition>: <body> The body is a sequence of one or more statements indented under the if heading. The body is executed if condition is evaluated to True. The body is skipped if condition is evaluated to False.

6

7 Boolean Expressions (Conditions)
The Boolean data type contains two Boolean values, denoted as True and False in Python. A Boolean expression is an expression that evaluates to a Boolean value. Need a relational operator to evaluate a boolean expression. The relational operators on the next slide can be applied to any set of values that has an ordering. Number comparison Lexicographical ordering for string comparison

8 Relational Operators Python Mathematics Meaning < Less than <= ≤
Less than or equal to == = Equal to >= Greater than or equal to > Greater than != Not equal to

9 Exercise 1 Try x, y ,z = 1, 2, 3 x == y; x > y; x + y + z > 10
False = True; False == True; False > True; True > False

10 Exercise 2 Try x, y ,z = "Benjamin", "Ben", "ben"
x > y; y > z; y + z > x "abc" > "123"; "abc" > ">>>"

11 Two other membership operators
The in operator is used to determine if a specific value is in a given list, returning True if found, and False otherwise. The not in operator returns the opposite result. Try 10 in [10, 20, 30, 40] 10 not in [10, 20, 30, 40] "blue" in ["red", "yellow", "black"] "blue" not in ["red", "yellow", "black"] "o" in "peter paul and mary"

12 Boolean Operators Source: Charles Dierbach Introduction to Computer Science Using Python. Wiley.

13 Exercise 3 Try True and False; True or False
not (True) and False; not (True and False) (10 < 0) and (10 > 2); (10 < 0) or (10 > 2) not (10 < 0) or (10 > 2); not (10 < 0 or 10 > 2)

14 Operator Precedence Source: Charles Dierbach Introduction to Computer Science Using Python. Wiley.

15 Exercise 4 Try to figure out the answers before running them:
True or False and True and True True or not False and True and not True ((True or not False) and True) and not True

16 Two-Way Decisions In Python, a two-way decision can be implemented by attaching an else clause onto an if clause. This is called an if-else statement: if <condition>: <statements> else: <statements> E.g., if 1 <= n and n <= 10000: print("Your input number is ", str(n)+ ".") else: print("Your input must be between 1 and 1000.")

17 Multi-Way Decisions Use nested if-else statement to implement multi-way decisions. if <condition1>: <case1 statements> else: if <condition2>: <case2 statements> else: if <condition3>: <case3 statements> else: <default statements>

18 Multi-Way Decisions using elif
In Python, else-if can be combined into elif: if <condition1>: <case1 statements> elif <condition2>: <case2 statements> elif <condition3>: <case3 statements> else: <default statements> The else is optional. If there is no else, it is possible that no indented block would be executed.

19 Exercise 5 Write a program to ask for a user's IQ and use if-elif statements to print out the IQ classification according to the table on the next slide.

20 Source: http://en.wikipedia.org/wiki/IQ_classification

21 Exercise 6 Ask user to enter 3 numbers. Your program will output the numbers in descending order. Write down the steps (pseudocode to solve the problem before coding. Note that no sorting algorithm is required.

22 For Loops: A Quick Review
The for statement allows us to iterate through a sequence of values. for <var> in <sequence>: <body> The loop index variable var takes on each successive value in the sequence, and the statements in the body of the loop are executed once for each value. For example, for num in range(0, 10): print(num) Python Programming, 1/e

23 Indefinite Loops The for loop is a definite loop, meaning that the number of iterations is determined when the loop starts. We can’t use a definite loop unless we know the number of iterations ahead of time. The indefinite or conditional loop keeps iterating until certain conditions are met.

24 Indefinite Loops while <condition>: <body>
condition is a Boolean expression, just like in if statements. The body is a sequence of one or more statements. Semantically, the body of the loop executes repeatedly as long as the condition remains true. When the condition is false, the loop terminates.

25 A Pre-test Loop

26 An example Here’s an example of using a while loop to print out range(10). i = 0 while i <= 9: print(i) i = i + 1 The code has the same output as this for loop: for i in range(10): print i

27 Exercise 7 Use a while loop to print out range(2, 10, 2).
Note: The 3rd argument of range() here means each time the number is incremented by 2.

28 Try i = 0 while i <= 9: print(i)
Exercise 8 Try i = 0 while i <= 9: print(i)

29 Interactive Loops # average2.py # A program to average a set of numbers # Illustrates interactive loop with two accumulators moredata = "yes" sum = 0.0 count = 0 while moredata[0] == 'y': x = int(input("Enter a number >> ")) sum = sum + x count = count + 1 moredata = input("Do you have more numbers (yes or no)? ") print ("\nThe average of the numbers is", sum / count)

30 Exercise 9 One problem with the program is that if you type too fast, you may enter a number as an answer to the yes/no question. What will the program respond to this "error"? How will you modify the program to rectify the response?

31 Sentinel Loops A sentinel loop continues to process data until reaching a special value that signals the end. This special value is called the sentinel. The sentinel must be distinguishable from the data since it is not processed as part of the data. get the first data item while item is not the sentinel process the item get the next data item

32 Exercise 10 Apply the sentinel approach to implementing the program for returning the average on slide 29.

33 Nested Loops Consider the following code in A4 What is the aim of it?
def main(): for i in range(1, 6): for j in range(1, 6): print("*", end=""); print() main() What is the aim of it?

34 Designing Nested Loops
Break the problem into two parts. The first is to process line by line (outer loop). The second is to process the items on each line (inner loop). Note that the two parts are not inter-dependent.

35 Post-Test Loop Say we want to write a program that is supposed to get a nonnegative number from the user. If the user types an incorrect input, the program asks for another value. This process continues until a valid value has been entered. This process is input validation.

36 Post-Test Loop repeat get a number from the user until number is >= 0

37 Post-Test Loop Python doesn’t have a built-in statement to do this, but we can do it with a slightly modified while loop. We could simulate a post-test loop by number = -1 while number < 0: number = eval(input("Enter a positive number: "))

38 Using a break Some programmers prefer to simulate a post-test loop by using the Python break statement. Executing break causes Python to immediately exit the enclosing loop. For example, while True: number = eval(input("Enter a positive number: ")) if number >= 0: break # Exit loop if number is valid Avoid using break often within loops, because the logic of a loop is hard to follow when there are multiple exits.

39 Exercise 11 Enhance the codes in the previous page by printing out an error message if the input is not valid and ask the user to input again, until the input is valid.

40 End


Download ppt "Python: Control Structures"

Similar presentations


Ads by Google