Python Loops
PythonLoops let you repeat code. Python has two main loops: for and while.
Key Points
forloop — iterate over a sequence (list, range, string)whileloop — repeat as long as a condition is truebreak— exit the loop earlycontinue— skip current iterationrange(start, stop, step)— generates numbers
Example — PYTHON
# For loop with range
for i in range(1, 6):
print(f"Count: {i}")
# Loop through a list
fruits = ["Mango", "Banana", "Apple"]
for fruit in fruits:
print(f"I like {fruit}")
# While loop
num = 1
while num <= 5:
print(f"Number: {num}")
num += 1
# Break and Continue
for i in range(1, 11):
if i == 5:
break
if i % 2 == 0:
continue
print(i)
# Multiplication table
n = 7
for i in range(1, 11):
print(f"{n} x {i} = {n * i}") Result
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
I like Mango
I like Banana
I like Apple
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
1
3
7 x 1 = 7
7 x 2 = 14
... (up to 7 x 10 = 70)
Count: 2
Count: 3
Count: 4
Count: 5
I like Mango
I like Banana
I like Apple
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
1
3
7 x 1 = 7
7 x 2 = 14
... (up to 7 x 10 = 70)