While Loop
The first type of loop we will look at is the while loop. Imagine you want to print numbers 1-10. We would write this using a while loop as follows:
number = 1
while number <= 10: # While number is less than or equal to 10
print(number) # Print the number
number = number + 1 # Increase the number by 1You can see that the while loop has a similar structure to if-else statements.
It works as follows: after the word while comes a condition, which, as long as it holds true, the block of code within the while loop will repeat. As a reminder, a block of code is the indented code following statements like if, else, or while.
Our code will therefore perform the following steps:
- Set the value of the
numbervariable to 1. - Check if
numberis less than or equal to 10. - If yes, print the value of the
numbervariable, increase its value by 1, and go back to step 2. - If no, the program ends.
Note that if we forgot to increase number by 1 in our loop, number would always be 1 and our loop would repeat indefinitely. This would cause a non-responsive program that would likely terminate itself after a while. This is always undesirable, so as programmers, we must be careful to avoid this error.
Instructions
Create a variable number with the value 10.
Create a while loop that prints numbers from 10 to 20 using the number variable.
Don't forget to increase the number variable by 1.
Start programming for free
2/8