Python Programming

python loops, while and for

Python Loops (While Loop and For Loop)

Introduction

In programming, we often need to execute the same code multiple times.

Imagine printing:

print("Hello")
print("Hello")
print("Hello")
print("Hello")
print("Hello")

This works, but it is inefficient.

Loops solve this problem.


What is a Loop?

A loop repeatedly executes a block of code until a condition becomes False or until all items have been processed.

Example:

for i in range(5):
    print("Hello")

Output:

Hello
Hello
Hello
Hello
Hello

Why Do We Need Loops?

Without loops:

print(1)
print(2)
print(3)
print(4)
print(5)

With loops:

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

Output:

1
2
3
4
5

Benefits:

  • Less code
  • Better readability
  • Easier maintenance
  • Better scalability

Types of Loops in Python

Python mainly provides:

  1. while Loop
  2. for Loop

Python does not have a traditional do-while loop.


While Loop

A while loop executes as long as a condition remains True.

Syntax:

while condition:
    statements

Basic While Loop Example

count = 1

while count <= 5:
    print(count)

    count += 1

Output:

1
2
3
4
5

How While Loop Works

count = 1

Condition?
count <= 5

Yes → Execute Block

count += 1

Condition Again?

Repeat...

Flow Chart of While Loop

      Start
        |
        V
   Condition?
    /      \
 True      False
   |          |
 Execute     End
   |
 Update
   |
 Back to Condition

Infinite Loop

An infinite loop never ends.

Example:

while True:
    print("Hello")

Output:

Hello
Hello
Hello
...

Runs forever.


Common Infinite Loop Mistake

❌ Wrong

count = 1

while count <= 5:
    print(count)

Output:

1
1
1
1
...

Reason:

count += 1

is missing.


✅ Correct

count = 1

while count <= 5:
    print(count)

    count += 1

While Loop Example: Sum of Numbers

total = 0
num = 1

while num <= 5:

    total += num

    num += 1

print(total)

Output:

15

Calculation:

1 + 2 + 3 + 4 + 5 = 15

While Loop Example: Countdown Timer

count = 5

while count > 0:

    print(count)

    count -= 1

print("Blast Off!")

Output:

5
4
3
2
1
Blast Off!

While Loop Example: Password System

password = ""

while password != "python123":

    password = input("Enter Password: ")

print("Login Successful")

Loop continues until correct password is entered.


While Loop Example: Multiplication Table

number = 5
i = 1

while i <= 10:

    print(number * i)

    i += 1

Output:

5
10
15
20
25
30
35
40
45
50

For Loop

Used for iterating over sequences.

Examples:

  • String
  • List
  • Tuple
  • Set
  • Dictionary
  • Range

Syntax:

for variable in sequence:
    statements

Basic For Loop Example

for i in range(5):
    print(i)

Output:

0
1
2
3
4

Understanding range()

The most common function used with for loops.


range(stop)

for i in range(5):
    print(i)

Output:

0
1
2
3
4

range(start, stop)

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

Output:

1
2
3
4
5

range(start, stop, step)

for i in range(0, 11, 2):
    print(i)

Output:

0
2
4
6
8
10

Negative Step

for i in range(10, 0, -1):
    print(i)

Output:

10
9
8
7
6
5
4
3
2
1

For Loop with String

name = "Python"

for letter in name:
    print(letter)

Output:

P
y
t
h
o
n

For Loop with List

numbers = [10, 20, 30]

for item in numbers:
    print(item)

Output:

10
20
30

For Loop with Tuple

data = (1, 2, 3)

for value in data:
    print(value)

Output:

1
2
3

For Loop with Set

items = {10, 20, 30}

for item in items:
    print(item)

Output order may vary.


For Loop with Dictionary

Keys

student = {
    "name": "John",
    "age": 25
}

for key in student:
    print(key)

Output:

name
age

Values

for value in student.values():
    print(value)

Output:

John
25

Key and Value

for key, value in student.items():
    print(key, value)

Output:

name John
age 25

Practical Example: Total Marks

marks = [50, 60, 70, 80]

total = 0

for mark in marks:
    total += mark

print(total)

Output:

260

Practical Example: Count Characters

text = "Python"

count = 0

for char in text:
    count += 1

print(count)

Output:

6

Nested Loops

A loop inside another loop.

Syntax:

for x in sequence:

    for y in sequence:
        statements

Nested Loop Example

for row in range(3):

    for col in range(3):

        print("*", end=" ")

    print()

Output:

* * *
* * *
* * *

Multiplication Table Using Nested Loops

for i in range(1, 4):

    for j in range(1, 4):

        print(i * j, end=" ")

    print()

Output:

1 2 3
2 4 6
3 6 9

Loop Control Statements

Python provides:

  1. break
  2. continue
  3. pass

break Statement

Stops the loop immediately.

Example:

for i in range(10):

    if i == 5:
        break

    print(i)

Output:

0
1
2
3
4

Real Life Example of break

numbers = [5, 8, 10, 15, 20]

for num in numbers:

    if num == 15:
        break

    print(num)

Output:

5
8
10

continue Statement

Skips current iteration.

Example:

for i in range(5):

    if i == 2:
        continue

    print(i)

Output:

0
1
3
4

Real Life Example of continue

for num in range(1, 11):

    if num % 2 == 0:
        continue

    print(num)

Output:

1
3
5
7
9

pass Statement

Placeholder statement.

Does nothing.

Example:

for i in range(5):

    pass

No output.


while vs for Loop

Feature while for
Condition Based Yes Usually No
Sequence Based No Yes
Known Iterations Less Convenient Best Choice
Unknown Iterations Best Choice Less Convenient

When to Use While Loop

Use when:

  • Number of iterations unknown
  • Waiting for user input
  • Menu systems
  • Login systems
  • Game loops

Example:

while password != correct_password:
    ...

When to Use For Loop

Use when:

  • Iterating through a sequence
  • Known number of repetitions
  • Lists
  • Strings
  • Files

Example:

for item in products:
    ...

Common Mistakes


Mistake 1: Infinite Loop

❌ Wrong

i = 1

while i <= 5:
    print(i)

✅ Correct

i += 1

Mistake 2: Wrong range()

❌ Wrong

range(1,5)

Expected:

1 2 3 4 5

Actual:

1 2 3 4

Because stop value is excluded.


Mistake 3: Modifying Loop Variable Incorrectly

❌ Wrong

for i in range(5):
    i += 10

This does not change the loop sequence.


Mistake 4: Using break Accidentally

❌ Wrong

for i in range(10):
    break

Output:

No iterations after first break

Mistake 5: Forgetting Colon

❌ Wrong

for i in range(5)

Output:

SyntaxError

Mistake 6: Indentation Error

❌ Wrong

for i in range(5):
print(i)

Output:

IndentationError

Best Practices


Use Meaningful Variable Names

❌ Avoid

for x in products:

✅ Better

for product in products:

Prefer for Loop for Sequences

for item in items:
    print(item)

Prefer while Loop for Conditions

while balance > 0:
    ...

Homework 1

Print numbers from 1 to 10 using a while loop.


Solution

i = 1

while i <= 10:
    print(i)

    i += 1

Homework 2

Print numbers from 1 to 10 using a for loop.


Solution

for i in range(1, 11):
    print(i)

Homework 3

Print all even numbers from 1 to 20.


Solution

for i in range(2, 21, 2):
    print(i)

Homework 4

Find sum of numbers from 1 to 100.


Solution

total = 0

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

print(total)

Output:

5050

Homework 5

Print multiplication table of 7.


Solution

for i in range(1, 11):
    print(7 * i)

Homework 6

Print each character of your name using a for loop.


Solution

name = "Rahul"

for letter in name:
    print(letter)

Homework 7

Print odd numbers from 1 to 20 using continue.


Solution

for i in range(1, 21):

    if i % 2 == 0:
        continue

    print(i)

Homework 8

Stop printing numbers when 8 is reached using break.


Solution

for i in range(1, 11):

    if i == 8:
        break

    print(i)

Output:

1
2
3
4
5
6
7

Homework 9

Create a 5×5 star pattern using nested loops.


Solution

for row in range(5):

    for col in range(5):

        print("*", end=" ")

    print()

Output:

* * * * *
* * * * *
* * * * *
* * * * *
* * * * *

Quick Revision

Loop Purpose
while Repeat while condition is True
for Iterate through sequence
break Stop loop immediately
continue Skip current iteration
pass Placeholder
Nested Loop Loop inside loop
range() Generate sequence of numbers

Loop Control Flow

while
│
├── Condition True
│     │
│     └── Execute
│
└── Condition False
      │
      └── End


for
│
├── Next Item
│
├── Execute Block
│
└── Repeat Until End

Summary

Concept Description
while Loop Runs while condition is True
for Loop Iterates through sequences
range() Generates numbers
Nested Loop Loop inside another loop
break Terminates loop
continue Skips iteration
pass Empty placeholder
Infinite Loop Loop that never ends

Loops are one of the most important concepts in Python and are heavily used in:

  • Automation Scripts
  • Data Analysis
  • Games
  • Web Applications
  • APIs
  • Machine Learning
  • File Processing
  • Data Structures and Algorithms

Master loops thoroughly before moving to Functions because functions and loops are frequently used together in real-world Python programs.

Filters

No filters available for this view.

Reset All