Oct. 9, 2021
Teacher Resources
Originally posted: Oct. 9, 2021
Last edited: 3 years ago
What you will learn:
In this lesson, you will learn the while statement.
What you will need:
Our Python Compiler:
https://www.aeroweb.info/python/code
Our turtle user interface:
https://www.aeroweb.info/python/turtle
What is a loop?
A loop is a repetition of a block of code for a fixed number of times. Python provides two statements for creating loops:
- while ... else statement
- for ... in statement
The syntax for the while ... else statement looks like this:
while boolean_expression:
... block
else:
... block
A Boolean value is either True or False.
NOTE: The else_ part is OPTIONAL and used only if needed.
How this while statement works?
As long as the boolean_expression is True, the while block is executed. If the boolean_expression becomes False, the while loop
terminates, and if the optional else is present, its block is executed.
The else part
There are 3 cases where the else statement is not executed:
- If the loop is broken out of due to a break statement, or
- If the loop is broken out of due to a return statement (if we write the loop inside a function or method), or
- If an exception is raised
NOTE: The behavior of else is the same in the while loops, for ... in loops, and try ... except blocks.
For this example you will use our Python Compiler located in our resources tab:
n = 10
while n > 0:
print("my number is", n)
n-=1
else:
print("my number is", 0)
my number is 10
my number is 9
my number is 8
my number is 7
my number is 6
my number is 5
my number is 4
my number is 3
my number is 2
my number is 1
my number is 0