Free tutorials & notes in Hindi & English · Clean code examples 🧰 Free PDF & Image Tools →
🟢 Beginner  ·  Lesson 09

Loops in Python (for and while)

In this lesson: Learn for and while loops in Python — range(), break, continue, else on loops — with patterns and programs.

Why Loops?

A loop repeats a block of code many times without writing it again and again. Python has two loops: for (repeat a known number of times) and while (repeat until a condition becomes false).

The for Loop & range()

for repeats over a sequence. range(start, stop, step) generates numbers (stop is not included).

Python – range.py
for i in range(1, 6):
    print(i, end=" ")
Dry Run — Python for i in range(1, 6)
Stepirange me hai? (1 se 5)print
11haan1
22haan2
33haan3
44haan4
55haan5
66nahirange(1,6) me 6 nahi aata — loop ruk gaya
💡 Aise samajhiye

Python me range(1, 6) 1 se 5 tak deta hai — aakhri number (6) shaamil nahi hota. Isliye output 1 2 3 4 5 aata hai, 6 nahi. Ye ek bahut common confusion hai.

1 2 3 4 5
  • range(1, 6) gives 1,2,3,4,5 (6 is excluded).
  • i takes each value one by one.

The while Loop

while keeps running as long as its condition is True. You must change something inside, or it loops forever.

Python – while.py
count = 1
while count <= 3:
    print("Count:", count)
    count += 1   # this line ends the loop eventually
Count: 1 Count: 2 Count: 3

Program 1: Print 1 to 10

Python – ten.py
for i in range(1, 11):
    print(i)
1 2 3 ... 10

range(1, 11) covers 1 to 10. Each pass prints one number.

Program 2: Multiplication Table

Python – table.py
n = int(input("Table of: "))
for i in range(1, 11):
    print(n, "x", i, "=", n * i)
Table of: 5 5 x 1 = 5 5 x 2 = 10 ... 5 x 10 = 50

The loop runs 10 times; each time i grows from 1 to 10 and we print n * i.

Program 3: Sum & Average of N Numbers

Python – sumavg.py
n = int(input("How many numbers? "))
total = 0
for i in range(n):
    num = int(input("Enter number: "))
    total += num

print("Sum     =", total)
print("Average =", total / n)
How many numbers? 3 Enter number: 10 Enter number: 20 Enter number: 30 Sum = 60 Average = 20.0
  • total = 0 starts an accumulator before the loop.
  • total += num adds each input to the running total.

Program 4: Factorial using while

Python – factorial.py
n = int(input("Enter n: "))
fact = 1
while n > 0:
    fact *= n
    n -= 1
print("Factorial =", fact)
Enter n: 5 Factorial = 120

5! = 5x4x3x2x1 = 120. Each pass multiplies fact by n, then reduces n.

Program 5: Star Pattern (nested loop)

Python – stars.py
rows = 5
for i in range(1, rows + 1):
    for j in range(i):
        print("*", end="")
    print()
* ** *** **** *****
  • The outer loop controls rows; the inner loop prints stars in each row.
  • Row i prints i stars, then print() moves to a new line.

Program 6: Number Guess with break & continue

Python – guess.py
secret = 7
while True:
    g = int(input("Guess (1-10): "))
    if g == secret:
        print("Correct!")
        break          # exit the loop
    if g < 1 or g > 10:
        print("Out of range, try again")
        continue       # skip to next loop
    print("Wrong, try again")
Guess (1-10): 3 Wrong, try again Guess (1-10): 7 Correct!

break, continue and loop-else

  • break — exit the loop immediately.
  • continue — skip the rest of this pass, go to the next.
  • else on a loop — runs once if the loop finished without break.

Common Mistakes

  • Forgetting to update the variable in a while → infinite loop.
  • Off-by-one with range() (remember stop is excluded).
  • Wrong indentation for the loop body.

Practice Tasks

  1. Print all even numbers from 1 to 50.
  2. Print the table of any number entered by the user.
  3. Find the sum of digits of a number using a while loop.
  4. Print an inverted star triangle (5 stars down to 1).
  5. Count how many numbers in a list are positive.

Summary

  • for repeats a known number of times (often with range()).
  • while repeats until its condition is false — update the variable inside.
  • break exits, continue skips a pass.
  • Nested loops make patterns and tables.

Frequently Asked Questions

What is the difference between for and while loops?
Use for when you know how many times to repeat or are going through a sequence; use while when you repeat until a condition becomes false.
Why does range(1, 10) not include 10?
range stops before the end value. Use range(1, 11) to include 10.
What do break and continue do?
break exits the loop immediately; continue skips the rest of the current iteration and moves to the next one.
← Back to Python Tutorial
🔗

Share this topic with a friend

यह topic किसी दोस्त को भेजें

Found it useful? Send it to a classmate learning the same thing.

अच्छा लगा? जो दोस्त यही सीख रहा है, उसे भेज दीजिए।

💻 Live Code Editor

This page's programs are ready here — run them, edit them, and learn. No installation needed.
Powered by OneCompiler. The code loads into the editor automatically — press Run to see the output. If the editor does not open, open it in a new tab.
Next topicFunctions in Python Your progress: 9 / 66 (14%) · Lesson 10 / 66 Continue →

How was this lesson?

Your feedback helps us make the content better.

Write a review or suggestion (optional)

After approval, your name and city may appear publicly with your review. Please do not write your email or phone number.

▶ CodingEasily on YouTube

Learn with video lessons in easy Hindi

Featured video: RDBMS Part 3 – Class XI Commerce IT

▶ Subscribe – it’s free