Python 03 Ly Reduced
Python 03 Ly Reduced
Introduction
• Pre-programming
– Have a through understanding of the problem
– Have a carefully planned approach to the solution
• When writing the program
– Understand the types of building blocks available
– Use proven program-construction principles
• Repetition Structures
– Allow a program to repeat an action while a statement is true
• Using while Repetition
– The action is contained within the body of the loop
• Can be one or more than one action
– Condition should evaluate to false at some point
• Creates a infinite loop and program hangs
product = 2
true
Product <= 1000 Product = 2 * product
false
• Essentials
– The counter
• A named variable to control the loop
– Initial value
• That which the counter starts at
– Increment
• Modifying the counter to make the loop eventually terminate
– Condition
• The test that the counter must pass in order to continue looping
Program Output
0
1
2
3
4
5
6
7
8
9
• Exercise:
• A class has a list of test results (1 = pass, 2 = fail) for
10 students. Write a program that analyzes the results
and display “Good class!”, if more than 8 students
have passed. Display the number of passes and failures.
• Note: You will receive the results (1 = pass, 2 = fail)
during run time
Program Output
0
1
2
3
4
5
6
7
8
9
• Techniques
– If the third value passed is negative then the loop will count
backwards through the provided numbers
Program Output
Sum is 2550
Program Output
1 2 3 4
Broke out of loop at x = 5
1 2 3 4 6 7 8 9 10
Used continue to skip printing the value 5