Presentation is loading. Please wait.

Presentation is loading. Please wait.

Determinate Loops with the

Similar presentations


Presentation on theme: "Determinate Loops with the"— Presentation transcript:

1 Determinate Loops with the
Python for statement Rick Mercer 1

2 Algorithmic Pattern: The Determinate loop
We often need to perform some action a specific number of times: Produce 89 paychecks Count down to 0 (take 1 second of the clock) Compute grades for 81 students Visit every element in a list The determinate loop pattern repeats some action a specific number of times iterates over all elements in a sequence 2

3

4 Determinate Loops for<var> in <sequence> : <body>
The determinate loop pattern can be implemented with the Python for loop We use this pattern so often, there is a statement for<var> in <sequence> : <body> for integer in range(3): print(integer) 4

5 For loops Determinate loops know the number of repetitions before they begin to loop How many employees, or students, or .. The number of lines in a file Numbers of characters in a string Number of elements in a list

6 Examples for ch in 'UofA': print(ch) list = [1, 2, 3]
for lcv in range(n): print(lcv, end =' ') for num in range(0, 6, 2): print(num, end =' ') for ch in 'UofA': print(ch) list = [1, 2, 3] for integer in list: print(integer, end= ' ')

7 Example loop that produces an average
n = int(input('Average how many numbers? ')) sum = 0; for lcv in range(n): number = eval(input('Number: ')) sum = sum + number; average = sum / n print('Average', average) Sample Dialog Average how many numbers? 3 Number: 78 Number: 89.5 Number: 97 Average 88.2

8 Example loop that produces an average
n = int(input('Average how many numbers? ')) sum = 0; for lcv in range(n): number = eval(input('Number: ')) sum = sum + number; average = sum / n print('Average', average) Sample Dialog Average how many numbers? 3 Number: 78 Number: 89.5 Number: 97 Average 88.2


Download ppt "Determinate Loops with the"

Similar presentations


Ads by Google