while condition: statement(s) # notice the indent from of this line relative to the while
for variable in [value1, value2, etc.]: statement(s) # notice the indent from of this line relative to the for
# 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
for variable in [value1, value2, etc.]: statement(s) # notice the indent from of this line relative to the for
# 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 numOutput:
I will display the numbers 1 through 5. 1 2 3 4 5Example:
# 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 9Example:
# This program also demonstrates a simple for # loop that uses a list of strings. for name in ['Winken', 'Blinken', 'Nod']: print nameOutput:
Winken Blinken Nod
for num in range(5): print num
for num in [0, 1, 2, 3, 4]: print num
for num in range(1, 5): print numOutput:
1 2 3 4
for num in range(1, 10, 2): print numOutput:
1 3 5 7 9
# Print the table headings. print '%-10s%-10s' % ('Number', 'Square') print '--------------------' # Print the numbers 1 through 10 # and their squares. for number in range(1, 11): square = number**2 print '%10d%10d' % (number, square)Output:
Number Square -------------------- 1 1 2 4 3 9 4 16 5 25 6 36 7 49 8 64 9 81 10 100