Control Structures - Repetition

Repetition Statements

while loops

Examples

 
# This program calculates sales commissions.

# Create a variable to control the loop.
keep_going = 'y'

# Calculate a series of commissions.
while keep_going == 'y':
    # Get a salesperson's sales and commission rate.
    sales = float(input('Enter the amount of sales: '))
    comm_rate = float(input('Enter the commission rate: '))

    # Calculate the commission.
    commission = sales * comm_rate

    # Display the commission.
    print 'The commission is $%.2f' % commission
    
    # See if the user wants to do another one.
    keep_going = raw_input('Do you want to calculate another ' + \
                       'commission (Enter y for yes): ')


Code: commission.py

In all but some rare cases, loops must contain within themselves a way to terminate. Something in the loop usually makes the test condition false. When this is missing the loop is called an infinite loop. You have to interrupt the program to exit an infinite loop. Avoid infinite loops most of the time.
# This program demonstrates an infinite loop.

# Create a variable to control the loop.
keep_going = 'y'

# Warning! Infinite loop!
while keep_going == 'y':
    # Get a salesperson's sales and commission rate.
    sales = float(input('Enter the amount of sales: '))
    comm_rate = float(input('Enter the commission rate: '))

    # Calculate the commission.
    commission = sales * comm_rate

    # Display the commission.
    print 'The commission is $%.2f' % commission

Code: infinite.py


The for loop


Examples of for loops

Example:
# This program demonstrates a simple for loop
# that uses a 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 5.
1
2
3
4
5
Example:
# This program also demonstrates a simple for
# loop that uses a list of 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 9.
1
3
5
7
9
Example:
# This program also demonstrates a simple for
# loop that uses a list of strings.

for name in ['Winken', 'Blinken', 'Nod']:
    print name
Output:
Winken
Blinken
Nod

Using the range function with the for loop