Loops Examples

Looping over a range of numbers using for loop:

for num in range(1, 6):
    print(num)

Output:

1
2
3
4
5

Looping over items in a list using for loop:

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

Printing numbers from 1 to 5 using while loop:

num = 1
while num <= 5:
    print(num)
    num += 1

Output:

1
2
3
4
5

Countdown from 10 to 1 using while loop:

count = 10
while count >= 1:
    print(count)
    count -= 1

Output:

10 9 8 7 6 5 4 3 2 1

Multiplication table using Nested Loop:

for i in range(1, 4):
    for j in range(1, 6):
        print(i, "*", j, "=", i * j)
    print()

Output:

10 9 8 7 6 5 4 3 2 1

Skipping even numbers:

for num in range(1, 11):
    if num % 2 == 0:
        continue  # Skip even numbers
    print(num)

Output:

1 3 5 7 9

Exiting the loop early:

num = 1
while True:
    print(num)
    num += 1
    if num > 5:
        break

Output:

1 2 3 4 5