Python While Loops Cheat Sheet
by Nouha_Thabet via [Link]/103894/cs/21437/
Example The else Statement
i = 1 i = 1
while i < 4: while i < 4:
print(i) print(i)
i += 1 i += 1
>>> 1 else:
>>> 2 print("i is no longer less than 4")
>>> 3 >>> 1
With the while loop we can execute a set of statements as long as >>> 2
a condition is true. In this example the condition was that i must be >>> 3
less than 4. >>> i is no longer less than 4
With the else statement we can run a block of code once when the
The break Statement condition no longer is true.
i = 1
while i < 4:
print(i)
if (i == 2):
break
i += 1
>>> 1
With the break statement we can stop the loop even if the while
condition is true. In this example the loop stopped when i is equal to
2.
The continue Statement
i = 1
while i < 4:
print(i)
if (i == 2):
continue
i += 1
>>> 1
>>> 3
With the continue statement we can stop the current iteration, and
continue with the next. In this example the loop stopped when i is
equal to 2 and continued the next iterations.
By Nouha_Thabet Not published yet. Sponsored by [Link]
[Link]/nouha- Last updated 20th December, 2019. Measure your website readability!
thabet/ Page 1 of 1. [Link]