Presentation is loading. Please wait.

Presentation is loading. Please wait.

Topics Introduction to Repetition Structures

Similar presentations


Presentation on theme: "Topics Introduction to Repetition Structures"— Presentation transcript:

1

2 Topics Introduction to Repetition Structures
The while Loop: a Condition-Controlled Loop The for Loop: a Count-Controlled Loop Calculating a Running Total

3 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 code Includes condition-controlled loops and count-controlled loops

4 The while Loop while loop: while condition is true, do something
Two parts: Condition tested (just like in If/else) Set of Statements repeated as long as condition is true General format: while condition: statements Notice Indentation like If statement. while statement ends when indentation ends ‘:’ after condition

5 The while Loop Flow Control

6 The while Loop 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 at start Requires performing some steps prior to the loop

7

8 Commission Program # This program calculates sales commissions. keep_going = 'y‘ # Create a variable to control the loop. # Calculate a series of commissions. while keep_going == 'y': sales = float(input('Enter the amount of sales: ')) comm_rate = float(input('Enter the commission rate: ')) commission = sales * comm_rate # Calculate the commission. # Display the commission. print('The commission is $', format(commission, ',.2f'), sep='') # See if the user wants to do another one. keep_going = input('Do you want to calculate another ' + \ 'commission (Enter y for yes): ')

9 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 does not set the loop condition to be false

10 The for Loop Count-Controlled loop: performs loop 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 [val1, val2, etc]: statements Target variable: the variable which is the target of the assignment at the beginning of each iteration

11

12 Simple Loop With List of Numbers
print('I will display the numbers 1 through 5.') for num in [1, 2, 3, 4, 5]: print(num) Output I will display the numbers 1 through

13 Simple Loop With List of Odd Numbers
print('I will display the odd numbers 1 through 9.') for num in [1, 3, 5, 7, 9]: print(num) Output I will display the odd numbers 1 through

14 Simple Loop With List of Strings
for name in ['Winken', 'Blinken', 'Nod']: print(name) Output Winken Blinken Nod

15 Using range Function in for Loop
Simplifies the process of writing a for loop range returns an iterable object Iterable: contains a sequence of values that can be iterated over For num in range (arg1, [arg2, [arg3]]) statements range characteristics: One argument: used as ending limit Two arguments: starting value and ending limit Three arguments: third argument is step value

16 Range Example For num in range (5): print(num) Same as
Output 1 2 3 4 Same as For num in [0, 1, 2, 3, 4]:

17 Range Examples For num in range (1,5): print(num) Output For num in range (1,10,2): 7 9

18 Using Target Variable Inside 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 Ending value will not be included in loop since that is when loop stops

19 Speed Converter Example
start_speed = 60 # Starting speed end_speed = 131 # Ending speed increment = 10 # Speed increment conversion_factor = # Km/hr to MPH conversion factor # Print the table headings. print('KPH\tMPH') print(' ') # Print the speeds. for kph in range(start_speed, end_speed, increment): mph = kph * conversion_factor print(kph, '\t', format(mph, '.1f'))

20 Speed Converter Output
KPH MPH

21 Letting User Control Loop Iterations
Sometimes the programmer does not know exactly how many times the loop will execute Can receive range inputs from the user, place them in variables, and call range function in for clause using these variables Be sure to consider the end cases: range does not include the ending limit

22 Find Squares Example # Get the ending limit. print('This program displays a list of numbers') print('(starting at 1) and their squares.') end = int(input('How high should I go? ')) # Print the table headings. print() print('Number\tSquare') print(' ') # Print the numbers and their squares. for number in range(1, end + 1): # Add 1 since loop stops at end square = number**2 print(number, '\t', square)

23 Find Squares Output This program displays a list of numbers (starting at 1) and their squares. How high should I go? 5 Number Square

24 Generating an Iterable Sequence that Ranges from Highest to Lowest
The range function can be used to generate a sequence with numbers in descending order Make sure starting number is larger than end limit, and step value is negative Example: range (10, 0, -1)


Download ppt "Topics Introduction to Repetition Structures"

Similar presentations


Ads by Google