While Loops
While Loops
Syntax:
while <condition is true>:
# do something
else:
# do something else...
Example:
# This is an infinite loop:
x = 0
while x < 10:
print(x)
else:
print("x is not less than 10")
We need to make this condition false
eventually:
# This is an infinite loop:
x = 0
while x < 10:
print(x)
x = x + 1 # This will add 1 every time the loop runs
# Can also do x += 1
# To add 3 you can do x += 3
else:
print("x is not less than 10")
# This is an infinite loop:
x = 0
while x < 10:
x += 3
if x == 6:
continue
print(x)
else:
print("x is not less than 10")
This will print 3, 9, 12
Due to the continue statement the loop restarts but the value is still 9, after that 3 is added and as the print is at the end it will print 12
Once this is printed loop restarts goes to 12 < 10 and breaks the loop, but it is too late, 12 is already printed
Last updated