Iteration
Most programs need some process to be repeated many times. A process usually needs many lines of code. To avoid having to write that part of the code many times, the Repeat Structure is used. This comes in two basic forms:
- Test first loop - unknown number of loops
- Fixed number of loops
Common boolean operators
Test First Loop
Getting a part of a program to repeat using a Test First Loop structure.
The Test First Loop gives the option to enter into a code segment, and continue using this code until a condition is met. The code may never be activated if the appropriate condition is met.
The general form is:
While condition expression:
… statements
The loop condition controls the outcome and must be a Boolean expression. An example would be Age < 6 where Age is a variable, < is a boolean operator and 6 is a test value.
Example - simple guessing game
# simple guessing game
secret = 12
guess = int(raw_input("Guess the secret number <0..100> -> "))
# Loop until the number is guessed
while (guess != secret):
guess = int(raw_input("Guess the secret number <0..100> -> "))
#output
print 'You guessed it.'
Note:
- The secret number is set as an integer value
- The value for guess is read as a string and so needs to be converted to an integer for comparison
Fixed Loop Structure - For .. Next Structure
Sometimes it is necessary to repeat a section of code a set amount of times. The For..Next loop structure is used to handle these problems. It has a "built in" counter that is automatically increased as the code is repeated.
Example - add up scores of members of a cricket team (11 players)
#Adding up scores written in Python
#adds up 11 scores
print 'Cricket Scores.' #program heading
#initialise total
total = 0
#use the range function to set up team list of 11 players
team = range(1,12)
for player in team:
score = int(raw_input('Enter a score for player ' + repr(player) + ' -> '))
total = total + score
print 'Total so far is %d' %(total)
print 'You have finished.'
Exercises
- Don Ladly, coach for the Bilby footy team, needs a program that will add up the goals kicked by a given player over the season. Write a program that will accept the player's name and the goals kicked each game (if any) and display a message such as "Bill Jones kicked 65 goals this season".
- Bunnys hardware needs a program that will allow stock control of a paint sale where 80 cans of paint are available. Write a program that will allow the check-out operator to enter the number of cans purchased and advise when no more paint is left.
- Write a program that will show a list of the temperatures from 0-20 degrees celcieus in farenheit
[Python_Tutorial] [Sequence_Python] [Decision_Making_Python] [Arrays_Python] [Files_Python]
Comments (0)
You don't have permission to comment on this page.