Python Tutorials
Python File Handling
Python Modules
Python has two classic loop commands:
while
loopsfor
loopsWith a while
loop we can make a set of statements as long as the situation is real.
Print i as long as i is less than 6:
i = 1
while i < 6:
print(i)
i += 1
Note: remember to enlarge i, otherwise the loop will continue permanently.
The while
loop requires a variable that is right for you, in this example we need to define the variable variable, i
, that we have set to 1.
With a break
statement we can stop the loop even if the timing is true:
Exit the loop when i is 3:
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
With an continue
statement we can stop the current recurrence, and proceed with the following:
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
In other words we can use the else
code block once the situation is no longer true:
Print a message once the condition is false:
i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")