0% found this document useful (0 votes)
2 views2 pages

Python Loops Explained

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views2 pages

Python Loops Explained

Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Loops in Python

1. for loop
# Print numbers from 1 to 5
for i in range(1, 6):
print(i)

2. while loop
# Print numbers from 1 to 5
i = 1
while i <= 5:
print(i)
i += 1

3. for loop with else


for i in range(3):
print(i)
else:
print("Loop completed")

4. while loop with else


i = 0
while i < 3:
print(i)
i += 1
else:
print("While loop done")

5. Nested loops
for i in range(1, 4):
for j in range(1, 4):
print(i, "*", j, "=", i * j)

6. break statement
for i in range(1, 10):
if i == 5:
break
print(i)
Loops in Python

7. continue statement
for i in range(1, 6):
if i == 3:
continue
print(i)

8. Infinite loop
while True:
print("This will run forever (Press Ctrl+C to stop)")
break # Prevents true infinite loop

You might also like