= 0
count while count < 5:
print(count)
= count + 1 count
0
1
2
3
4
We have seen that for
loops can repeatedly execute a block of code for each element specified. We can think of another scenario where we only want to continue executing a block of code as long as a given condition is True
. The basic idea is:
WHILE there is money in my account
have lunch out
update my bank statement
In while
loops the condition is checked at the beginning of each iteration and the loop continues executing as long as the condition is True
. The basic syntax in Python which has a similar scaffolding to an if
clause:
while condition:
# code to execute while condition is True
To ensure that the condition will eventually become False
, it is common usage to increment/decrement a counter variable in the loop body:
= 0
count while count < 5:
print(count)
= count + 1 count
0
1
2
3
4
There are some extra flow control instructions in while
loops that we are not going to see here in detail but it is important to mention them. They are:
break
: exits the loop immediatelycontinue
: skips the rest of the current iteration and moves to the nextelse
: executes when the loop condition becomes False
while True:
= input("Enter 'q' to quit: ")
user_input if user_input == 'q':
break