While Loops
A while loop repeats a block of code while a condition is true. For a basic understanding of while loops work through the examples of W3Schools.
The following code will repeat the indented code as long as count remains less than 5
count = 1
while count < 5:
print(count)
count += 1
Sometimes this means that we don't know how many times the loop will execute. In the following example, the user enters a random number which is subtracted from the variable num. Depending on the number they enter the while loop may run just one time ( if they enter 100 or more ) or infinitely ( if they enter 0 or less)!
num = 100
while( num > 0):
sub = input("Enter an amount to subtract")
num = num - sub
If you want code to repeat a set number of times use a for loop.
The following code will repeat the indented code as long as count remains less than 5
count = 1
while count < 5:
print(count)
count += 1
Sometimes this means that we don't know how many times the loop will execute. In the following example, the user enters a random number which is subtracted from the variable num. Depending on the number they enter the while loop may run just one time ( if they enter 100 or more ) or infinitely ( if they enter 0 or less)!
num = 100
while( num > 0):
sub = input("Enter an amount to subtract")
num = num - sub
If you want code to repeat a set number of times use a for loop.
The following code shows a while loop. The while loop will continue until the user enters "Yes" on the keyboard. Each time the while loop runs one is added to the variable total. Once the user enters "Yes" the while loop code will terminate and the code below will be run. The total will be displayed.
Example - A while loop that calls a function
The example below shows a while loop which calls a simple function. Each time the loop runs the function is called and total is passed as a parameter variable. Inside the function the parameter variable is incremented ( one is added). Then the variable is returned,