4 - 1 Starting out with Python Fifth Edition Chapter 4 Repetition Structures Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved 4 - 2 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved Topics • Introduction to Repetition Structures • The while Loop: a Condition - Controlled Loop • The for Loop: a Count - Controlled Loop • Calculating a Running Total • Sentinels • Input Validation Loops • Nested Loops 4 - 3 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved Introduction to Repetition Structures • Often have to write code that performs the same task multiple times – Disadvantages to duplicating code ▪ Makes program large ▪ Time consuming ▪ May need to be corrected in many places • Repetition structure : makes computer repeat included code as necessary – Includes condition - controlled loops and count - controlled loops 4 - 4 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved The while Loop: a Condition - Controlled Loop ( 1 of 4 ) • while loop : while condition is true, do something – Two parts: ▪ Condition tested for true or false value ▪ Statements repeated as long as condition is true – In flow chart, line goes back to previous part – General format: while condition : statements 4 - 5 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved The while Loop: a Condition - Controlled Loop ( 2 of 4 ) Figure 4 - 1 The logic of a while loop count = 0 ans = "y “ while ans == "y": count += 1 print("I'm on loop", count, "!") ans = input("Keep going? ") 4 - 6 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved The while Loop: a Condition - Controlled Loop ( 3 of 4 ) • In order for a loop to stop executing, something has to happen inside the loop to make the condition false • Iteration : one execution of the body of a loop • while loop is known as a pretest loop – Tests condition before performing an iteration ▪ Will never execute if condition is false to start with ▪ Requires performing some steps prior to the loop • A while loop is typically used when you don ’ t know the exact number of times you need to repeat. 4 - 7 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved The while Loop ( 4 of 4 ) 4 - 8 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved Infinite Loops • Loops must contain within themselves a way to terminate – Something inside a while loop must eventually make the condition false • Infinite loop : loop that does not have a way of stopping – Repeats until program is interrupted – Occurs when programmer forgets to include stopping code in the loop 4 - 9 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved While Loop Examples • i = 1 while i < 6 : print (i) i += 1 num = 5 while num != 0 : print (num, " squared is :", num ** 2 ) num - = 1 i = 1 while i < 6 : print (i) if i == 3 : break i += 1 4 - 10 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved • Write a program with a loop that asks the user to enter a series of positive numbers. The user should enter a negative number to signal the end of the series. After all the positive numbers have been entered, the program should display their sum. Format sum to display 2 decimal places. • Hints: You will need two variables ‘ number ’ , and ‘ total ’ Use float() when ask for user input. In - class exercise 4 - 11 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved Sentinels • Sentinel : special value that marks the end of a sequence of items – When program reaches a sentinel, it knows that the end of the sequence of items was reached, and the loop terminates – Must be distinctive enough so as not to be mistaken for a regular value in the sequence – Example: when reading an input file, empty line can be used as a sentinel 4 - 12 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved Sentinels example • You want to calculate a square of the number num = int(input("Enter a number ( - 1 to stop): ")) while num != - 1 : print(num, "squared is:", num ** 2 ) num = int(input("Enter a number ( - 1 to stop): ")) • We exit loop after entering “ - 1 ” • - 1 is a sentinel 4 - 13 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved The for Loop: a Count - Controlled Loop ( 1 of 2 ) • Count - Controlled loop : iterates a specific number of times – Use a for statement to write count - controlled loop ▪ Designed to work with sequence of data items – Iterates once for each item in the sequence ▪ General format: for variable in [val 1 , val 2 , etc ] : statements ▪ Target variable : the variable which is the target of the assignment at the beginning of each iteration 4 - 14 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved The for Loop: a Count - Controlled Loop ( 2 of 2 ) Figure 4 - 4 The for loop 4 - 15 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved Using the range Function with the for Loop • The range function simplifies the process of writing a for loop – range returns an iterable object ▪ Iterable : contains a sequence of values that can be iterated over • range characteristics: – One argument: used as ending limit – Two arguments: starting value and ending limit – Three arguments: third argument is step value 4 - 16 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved Using the range Function • range characteristics: – One argument: used as ending limit: range( 5 ) is equivalent to [ 0 , 1 , 2 , 3 , 4 ]. Always start at 0 with range – Two arguments: starting value and ending limit: range( 2,8 ) is equivalent to [ 2 , 3 , 4 , 5 , 6 , 7 ] – Three arguments: third argument is step value: range ( 1 , 10 , 2 ) is equivalent to [ 1 , 3 , 5 , 7 , 9 ] for i in range( 2 , 8 ): # prints: 2 , 3 , 4 , 5 , 6 , 7 print(i, end=", ") for i in range( 1 , 10 , 2 ): # prints: 1 , 3 , 5 , 7 , 9 print(i, end=", ") for i in range( 5 ): # prints: 0,1,2,3,4 print(i, end=", ") 4 - 17 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved Using the Target Variable Inside the Loop • Purpose of target variable is to reference each item in a sequence as the loop iterates • Target variable can be used in calculations or tasks in the body of the loop – Example: calculate square root of each number in a range 4 - 18 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved For Loop Examples • fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: print (x) • for x in "banana" : print (x) • fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: print (x) if x == "banana" : break 4 - 19 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved For Loop Examples • fruits = [ "apple" , "banana" , "cherry" ] for x in fruits: if x == "banana" : continue print (x) • Output is: apple cherry >>> f ruits = [ "apple" , "banana" , "cherry" ] for x in fruits: if x == "banana" : print (x) Output is: Banana >>> 4 - 20 Copyright © 2021 , 2018 , 2015 Pearson Education, Inc. All Rights Reserved • Write a program that displays a table of the Celsius temperatures 0 through 20 and their Fahrenheit equivalents. The formula for converting a temperature from Celsius to Fahrenheit is • F is the Fahrenheit temperature. • C is the Celsius temperature. Your program must use a loop to display the table and output should be formatted using ‘ \ t ’ In - class exercise