Python Loops Explained – for Loop and while Loop with Examples and Output

 

Python Loops Explained – for Loop and while Loop with Examples and Output

Published on Code with Py  |  Category: Python Basics  |  Reading time: ~13 min

When learning Python, you will often need to repeat a task multiple times — printing numbers, processing a list, or checking user input again and again. Writing the same code repeatedly is not efficient. This is exactly where loops help. In this guide, you will learn what loops are, how the for loop and while loop work, when to use each one, and how they compare — with clear examples and outputs at every step.

Table of Contents

  1. What is a Loop in Python?
  2. Types of Loops in Python
  3. for Loop – Syntax and How it Works
  4. for Loop Examples
  5. When to Use a for Loop
  6. while Loop – Syntax and How it Works
  7. while Loop Examples
  8. Infinite Loop and How to Avoid It
  9. for Loop vs while Loop – Comparison
  10. Real-Life Use Cases
  11. Practice Problems
  12. FAQ

1. What is a Loop in Python?

loop is a programming construct that lets a block of code run repeatedly — either for a fixed number of times or until a certain condition becomes False. Without loops, you would have to write the same line of code again and again, which makes programs long, messy, and hard to maintain.

Here is what loops help you do:

  • Avoid repeating the same code multiple times
  • Reduce the length of your program significantly
  • Automate repetitive tasks like printing tables or processing lists
  • Build logic for real-world programs like ATMs, games, and forms

2. Types of Loops in Python

Python provides two main types of loops. Both can achieve the same results, but each is suited for different situations.

for loop

  • Used when iterations are known in advance
  • Works over sequences — lists, strings, ranges
  • Cleaner and more readable for fixed repetitions
  • Automatically stops at end of sequence

while loop

  • Used when iterations depend on a condition
  • Keeps running as long as condition is True
  • Best for user input, real-time checks
  • You must manually update the condition variable

3. for Loop – Syntax and How it Works

The for loop in Python iterates over items in a sequence one by one. For each item, it runs the code block inside the loop. When all items are exhausted, the loop stops automatically.

for variable in sequence:
    # code block to run for each item

The variable takes the value of each item in the sequence one at a time. The sequence can be a range(), a list, a string, a tuple, or any iterable.


4. for Loop Examples

Example 1 – Print numbers using range()

for i in range(1, 6):
    print(i)
1
2
3
4
5
range(1, 6) generates the numbers 1, 2, 3, 4, 5. The stop value 6 is never included. The loop variable i takes each value automatically.

Example 2 – Iterate through a string

for ch in "Python":
    print(ch)
P
y
t
h
o
n
A string is a sequence of characters. The for loop picks each character one by one and runs the block for each one.

Example 3 – Loop through a list

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)
Apple
Banana
Mango

Example 4 – Loop with index using enumerate()

Sometimes you need both the item and its position. Use enumerate() for this.

fruits = ["Apple", "Banana", "Mango"]

for index, fruit in enumerate(fruits):
    print(f"{index + 1}. {fruit}")
1. Apple
2. Banana
3. Mango

Example 5 – Sum of numbers using for loop

total = 0

for i in range(1, 11):
    total += i

print(f"Sum of 1 to 10: {total}")
Sum of 1 to 10: 55

Example 6 – Multiplication table

num = 5

for i in range(1, 11):
    print(f"{num} x {i} = {num * i}")
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50

5. When to Use a for Loop

Use for loop when:

  • Number of repetitions is known
  • Iterating over a list, string, or tuple
  • Using range() to count steps
  • Generating tables or sequences

Real-life examples:

  • Printing marks of each student
  • Displaying items in a shopping cart
  • Checking each character in a password
  • Printing a multiplication table

6. while Loop – Syntax and How it Works

The while loop keeps running a block of code as long as the condition is True. Unlike a for loop, it does not iterate over a sequence — it checks a condition before each iteration and stops only when that condition becomes False.

while condition:
    # code block runs as long as condition is True
    # update the condition variable here
Always update your condition variable inside the loop body. If you forget, the condition will never become False and the loop will run forever — this is called an infinite loop.

7. while Loop Examples

Example 1 – Print numbers 1 to 5

i = 1

while i <= 5:
    print(i)
    i += 1
1
2
3
4
5
The variable i starts at 1. After each iteration, i += 1 increases it by 1. When i becomes 6, the condition i <= 5 is False and the loop stops.

Example 2 – Countdown program

count = 5

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

print("Go!")
5
4
3
2
1
Go!

Example 3 – User input loop

This is one of the most practical uses of a while loop — keep asking the user for input until they type a specific value.

user_input = ""

while user_input != "exit":
    user_input = input("Type 'exit' to stop: ")
    print(f"You typed: {user_input}")

print("Loop ended.")
Type 'exit' to stop: hello
You typed: hello
Type 'exit' to stop: python
You typed: python
Type 'exit' to stop: exit
You typed: exit
Loop ended.

Example 4 – Sum of digits of a number

num = 1234
total = 0

while num > 0:
    total += num % 10
    num //= 10

print(f"Sum of digits: {total}")
Sum of digits: 10
This while loop extracts the last digit using % 10, adds it to total, then removes the last digit using // 10. It stops when no digits remain.

8. Infinite Loop and How to Avoid It

An infinite loop runs forever because its condition never becomes False. This can freeze or crash your program. Here is what one looks like:

while True:
    print("This runs forever!")
Never run an infinite loop without a break condition. To stop it manually in the terminal, press Ctrl + C. Always make sure your condition variable is updated inside the loop.

A controlled infinite loop with a break is acceptable and commonly used:

while True:
    answer = input("Enter 'quit' to exit: ")
    if answer == "quit":
        print("Goodbye!")
        break
Enter 'quit' to exit: hello
Enter 'quit' to exit: quit
Goodbye!

9. for Loop vs while Loop – Comparison

Featurefor Loopwhile Loop
Best used whenIterations are known in advanceIterations depend on a condition
Iterates overSequences, ranges, lists, stringsA condition (True/False)
Stops automaticallyYes – when sequence endsOnly when condition is False
Risk of infinite loopVery lowHigh if condition never changes
Counter variableManaged by loop automaticallyMust be updated manually
ReadabilityCleaner for known repetitionsCleaner for condition-based logic
Common usePrinting tables, iterating listsUser input, ATM PIN, game loop

10. Real-Life Use Cases

for loop real-life uses

  • Printing marks of all students in a class
  • Displaying items in a shopping cart
  • Sending emails to a contact list
  • Checking each character in a password
  • Generating OTP digits

while loop real-life uses

  • ATM asking for PIN until correct
  • Game running until player quits
  • Login page: allow 3 attempts
  • Downloading file until complete
  • Waiting for server response

11. Practice Problems

Try solving these on your own before searching for the answer. Understanding the logic is more important than getting the output immediately.

for loop problems

  1. Print 1 to 10
  2. Print all even numbers 1–20
  3. Print each character of a string
  4. Sum of numbers 1 to 100
  5. Multiplication table of any number
  6. Count vowels in a string
  7. Print list items with index
  8. Print 10 to 1 in reverse

while loop problems

  1. Print 1 to 10 using while
  2. Print 10 to 1 using while
  3. Sum of digits of a number
  4. Check if a number is palindrome
  5. Reverse a given number
  6. Ask user until they enter 0
  7. Multiplication table using while
  8. Login with 3 attempt limit
Write code yourself first. Test with at least 3 different inputs. If your output is wrong, trace through the loop manually — step by step — to find where the logic breaks.

Quick Summary – What You Learned
  • A loop repeats a block of code to avoid writing it multiple times
  • The for loop is best when the number of iterations is fixed
  • The while loop is best when iterations depend on a condition
  • range(start, stop, step) controls the for loop's counting
  • Always update the condition variable inside a while loop
  • An infinite loop runs forever — use break or fix the condition
  • Both loops can use breakcontinue, and else

Frequently Asked Questions (FAQ)

Q1. What is the main difference between a for loop and a while loop?

A for loop is used when the number of iterations is known in advance, such as looping through a list or a range. A while loop is used when the number of iterations depends on a condition that may change during execution.

Q2. Can a for loop replace a while loop in Python?

In most cases, yes — but it depends on the problem. For fixed repetitions and sequences, use for. For condition-based repetitions like user input or real-time checks, while is more natural and readable.

Q3. What is an infinite loop and how do I fix it?

An infinite loop runs forever because its condition never becomes False. Fix it by ensuring the condition variable is updated inside the loop body, or by adding a break statement when the goal is met.

Q4. Can I use a for loop without range() in Python?

Yes. You can loop directly over any iterable — a list, string, tuple, or dictionary. range() is just one way to generate a sequence of numbers for the loop to iterate over.

Q5. What happens if the while loop condition is False from the start?

The while loop body never executes even once. Python checks the condition before running the loop body, so if it is already False, the entire loop is skipped completely.

Q6. What is a nested loop in Python?

A nested loop is a loop placed inside another loop. The inner loop runs completely for each iteration of the outer loop. They are commonly used to work with 2D data like matrices or to print patterns.


Found this helpful? Share it with a friend who is learning Python. Drop your practice solutions in the comments — let's learn together!

"Practice daily, make mistakes, learn from them, and keep moving forward."

Comments

Popular posts from this blog

Python Strings – A Complete Guide for Beginners (with Examples)

Python Control Flow Statements – Complete Guide with Real-Life Examples