Real programs repeat work. Writing the same code again and again is stupidity. Loops solve this.
A loop runs the same block of code multiple times until a condition is met.
for Loop
for loop is used when you know
how many times something should run.
for i in range(5):
print(i)
Output:
0 1 2 3 4
range()
for i in range(1, 6):
print(i)
Starts from 1, stops before 6.
name = "Python"
for ch in name:
print(ch)
while Loop
while loop runs
as long as condition is True.
count = 1
while count <= 5:
print(count)
count += 1
If condition never becomes False, loop never stops.
while True:
print("This will run forever")
break Statement
break stops the loop immediately.
for i in range(1, 10):
if i == 5:
break
print(i)
continue Statement
continue skips current iteration.
for i in range(1, 6):
if i == 3:
continue
print(i)
attempts = 0
while attempts < 3:
password = input("Enter password: ")
if password == "python123":
print("Access granted")
break
else:
print("Wrong password")
attempts += 1
If you understand loops, you understand automation. This is how software scales.
Next part: Data Structures — List, Tuple, Set, Dictionary.