Yandex

Python Loops



Loops help us repeat actions in Python. Imagine telling the computer: "Do this again and again." That’s what loops are for!

Why Use Loops?

Let’s say you want to print "Hi!" five times. Without a loop, you’d write:

print("Hi!")
print("Hi!")
print("Hi!")
print("Hi!")
print("Hi!")

That works… but what if you wanted to print it 100 times? That’s where loops save time.

Types of Loops in Python

  • for loop – repeats a certain number of times
  • while loop – repeats while a condition is true

1. for Loop

for loops are great when you know how many times you want to repeat something.

for i in range(5):
    print("Hi!")
Hi!
Hi!
Hi!
Hi!
Hi!

Explanation:

  • range(5) means: go from 0 to 4 (5 numbers in total).
  • i takes values 0, 1, 2, 3, 4 — one at a time.
  • print("Hi!") runs 5 times, once for each value of i.

2. while Loop

while loops repeat as long as a condition is true.

count = 1
while count <= 3:
    print("Welcome!")
    count = count + 1
Welcome!
Welcome!
Welcome!

Explanation:

  • count starts at 1.
  • It prints "Welcome!" and then adds 1 to count.
  • It stops when count becomes 4 (because 4 is not ≤ 3).

Looping Through a List

We can also use for loops to go through a list of items.

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

Explanation:

Each time, fruit takes one value from the list and prints it.

Using break in a Loop

break stops the loop early.

for i in range(5):
    if i == 3:
        break
    print(i)
0
1
2

Explanation:

  • When i becomes 3, the break line runs and stops the loop.
  • So 3 and 4 are never printed.

Using continue in a Loop

continue skips the rest of the loop for that time only.

for i in range(5):
    if i == 2:
        continue
    print(i)
0
1
3
4

Explanation:

  • When i is 2, it skips print(i).
  • Everything else runs normally.

Conclusion

Loops are a powerful way to repeat actions in Python. You learned:

  • How to use for and while loops
  • How to go through lists using loops
  • How to use break to stop a loop
  • How to use continue to skip one step in a loop

Practice using loops in different ways — that’s the best way to understand how they work!



Welcome to ProgramGuru

Sign up to start your journey with us

Support ProgramGuru.org

You can support this website with a contribution of your choice.

When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.

PayPal

UPI

PhonePe QR

MALLIKARJUNA M