Iteration is the process of repeating a process over and over. Often in programming you need to repeat a block of code several times.
WHILE Loops
A while
loop is known as a condition controlled loop, you should use it when you do not know how many times the code needs to repeat as you can say repeat while
a condition is True
.
When run in IDLE:
How the while loop works
- there is a condition after the word
while
, it works like anif
condition.while
the variableuserentry
is not equal ton
the code inside the loop (that is indented) will repeat - when
n
is entered by the user, the loop will end and it will continue with the code after the loop (not indented). In this case it willprint
“Game Over”.
Example Program 1 - Guess the Number
This program asks the user to guess the number, it will keep asking them to guess the number until they guess it correctly. Once they have guessed it correctly it will tell them how many attempts it took.
When run in IDLE:
Example Program 2 - Adding User Numbers Program
This program asks the user to enter a number. It then asks them whether they want to enter another. If they do it will ask them another and add it to the previous number, it will keep doing this until they say they do not want to enter any more numbers. Finally it will output the total.
When run in IDLE: