🐍 Python Tutorial
← PrevNext →
Python Loops
Master for and while loops in Python.
Python Loops
Loops are used to repeat actions multiple times.
The for Loop
for i in range(3):
print("Hello", i)
The while Loop
count = 0
while count < 3:
print("Count:", count)
count += 1
Breaking Out of a Loop
for i in range(10):
if i == 5:
break
print(i)
Common Errors & Troubleshooting
IndentationError: expected an indented block— the line(s) inside afor/whileloop must be indented (4 spaces is the Python convention). Forgetting to indent the body under the loop line causes this.- Infinite loop that never stops — a common
whileloop bug: forgetting to update the condition variable inside the loop (e.g. leaving outcount += 1), socount < 3is always true. PressCtrl+Cin the terminal to force-stop a runaway script. range(3)doesn't include 3 —range(3)produces0, 1, 2— it's exclusive of the stop value. Userange(1, 4)if you actually want1, 2, 3.
Advertisement320 x 100