(use the Space key to navigate through all slides)
Prof. Andrea Gallegati |
Prof. Dario Abbondanza |
while
loops write Python programs that
repeat the same code execution
while condition:
# Code to repeat (indented block)
pass
True
, the loop executes.False
, the loop stops.count = 1 # Start at 1
while count <= 5: # Keep going while count is ≤ 5
print("Count:", count)
count += 1 # Increase count by 1
count
starts at 1.count
increases.countdown = 5
while countdown > 0:
print("T-minus", countdown)
countdown -= 1 # Reduce countdown
print("🚀 Liftoff!")
countdown > 0
.countdown
."Liftoff!"
prints.password = ""
while password != "python123": # Keep asking
password = input("Enter the password: ")
print("Access granted! ✅")
Useful when we don't know how many times we'll repeat an action.
"python123"
, the loop stops.break
to Exit a Loop Early
number = 1
while number <= 10:
print("Checking number:", number)
if number == 7: # Stop when number is 7
print("Number 7 found! Stopping loop.")
break
number += 1
Sometimes, we need to exit a loop immediately.
break
exits the loop even if the condition is still True
.continue
to Skip an Iterationnumber = 0
while number < 10:
number += 1
if number % 2 == 0:
continue # Skip even numbers
print(number)
It skips the rest of the loop's code for the current iteration.
continue
skips print()
statement.else
within a while
Loopnumber = 1
while number <= 5:
print(number)
number += 1
else:
print("Loop finished successfully!")
else
block runs if the loop
completes normally (without break
).
break
, then else
block runs.False
, it runs forever.
False
.count
).while True:
print("This loop runs forever!")
If the loop condition never becomes False
, it runs forever.
True
, it never stops.Ctrl+C
to STOP the program.🎲
import random
roll = 0
while roll != 6:
roll = random.randint(1, 6) # Roll a die (1 to 6)
print("Rolled:", roll)
print("🎲 Got a 6! Loop stopped.")
we don’t know how many times
it will run!
6
while
loop repeats actions as long as condition is True
.break
to exit a loop immediately.continue
to skip an iteration.while
loop can have an else
block break
).Be careful of infinite loops—always make sure the condition eventually becomes False
.
number = 0 # Start with a number less than 10
while number <= 10:
number = int(input("Enter a number greater than 10: "))
print("Thanks! You entered", number)
A Framework created by Hakim El Hattab and contributors
to make stunning HTML presentations