Python

Python Loops

A loop allows a program to execute the same block of code repeatedly.

Without loops, if we wanted to print numbers from 1 to 100, we would have to write print() 100 times. Loops allow us to perform repetitive tasks with just a few lines of code.

Python mainly provides two types of loops:

  1. for loop — used when we want to iterate over a sequence or a known range of values.
  2. while loop — used when we want to continue running code as long as a condition remains True.

Python also provides:

  • range()
  • break
  • continue
  • pass
  • Nested loops
  • Loop else
  • Iterating over strings, lists, tuples, sets, and dictionaries
  • List comprehensions

1. Why Do We Need Loops?

Suppose we want to print five messages.

Without a loop:

print("Welcome")
print("Welcome")
print("Welcome")
print("Welcome")
print("Welcome")

With a loop:

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

The second approach is shorter, easier to maintain, and can easily be changed to repeat 100 or 1,000 times.

2. The for Loop

A for loop is used to iterate over items in a sequence or collection.

Syntax

for variable in sequence:
    # code

Example:

fruits = ["apple", "mango", "banana"]

for fruit in fruits:
    print(fruit)

 

Output:

apple
mango
banana

The loop takes one item at a time from the list and stores it in fruit.

3. How a for Loop Works

Consider:

fruits = ["apple", "mango", "banana"]

for fruit in fruits:
    print(fruit)

The loop works conceptually like this:

fruit = "apple"  → print
fruit = "mango"  → print
fruit = "banana" → print

Once there are no more items, the loop ends.

4. Looping Through a String

A string is also iterable.

name = "Python"

for character in name:
    print(character)

Output:

P
y
t
h
o
n

Each character is processed separately.

5. range()

range() is commonly used when we want to repeat something a specific number of times.

Example:

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

Output:

0
1
2
3
4

Notice that range(5) starts from 0 and stops before 5.

6. range(start, stop)

We can specify where the range starts.

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

Output:

1
2
3
4
5

The structure is:

range(start, stop)

The stop value is not included.

7. range(start, stop, step)

We can also specify how much the value should increase or decrease each time.

for number in range(1, 11, 2):
    print(number)

Output:

1
3
5
7
9

Here:

start = 1
stop = 11
step = 2

8. Counting Backwards

A negative step allows us to move backwards.

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

Output:

10
9
8
7
6
5
4
3
2
1

9. Printing Even Numbers

range() makes it easy to generate even numbers.

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

Output:

2
4
6
8
10
12
14
16
18
20

10. Printing Odd Numbers

for number in range(1, 20, 2):
    print(number)

Output:

1
3
5
7
9
11
13
15
17
19

11. Looping Through a List

students = ["Raj", "John", "Sita", "Michael"]

for student in students:
    print(student)

Output:

Raj
John
Sita
Michael

This is one of the most common uses of a for loop.

12. Looping Through a Tuple

courses = ("Python", "Django", "MERN")

for course in courses:
    print(course)

Output:

Python
Django
MERN

13. Looping Through a Set

skills = {"Python", "Django", "SQL"}

for skill in skills:
    print(skill)

The order may vary because sets are unordered collections.

14. Looping Through a Dictionary

When we directly loop through a dictionary, Python gives us its keys.

student = {
    "name": "Raj",
    "age": 25,
    "course": "Python"
}

for key in student:
    print(key)

Output:

name
age
course

15. Dictionary Keys and Values

We can explicitly use .keys():

for key in student.keys():
    print(key)

To get values:

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

Output:

Raj
25
Python

16. Dictionary Items

The .items() method gives both key and value.

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

Output:

name : Raj
age : 25
course : Python

This is particularly useful when processing dictionary data.

17. Accessing List Indexes

Sometimes we need both the index and the value.

One way is:

fruits = ["apple", "mango", "banana"]

for i in range(len(fruits)):
    print(i, fruits[i])

Output:

0 apple
1 mango
2 banana

But Python provides a cleaner way.

18. Using enumerate()

enumerate() gives us both the index and the value.

fruits = ["apple", "mango", "banana"]

for index, fruit in enumerate(fruits):
    print(index, fruit)

Output:

0 apple
1 mango
2 banana

We can also start the index from another number:

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)

Output:

1 apple
2 mango
3 banana

19. The while Loop

A while loop repeats code as long as its condition remains True.

Syntax

while condition:
    # code

Example:

count = 1

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

Output:

1
2
3
4
5

20. How a while Loop Works

Initially:

count = 1

Python checks:

count <= 5

If true, it executes the loop.

Then:

count += 1

updates the value.

The process continues until the condition becomes false.

21. Important: Update the Variable

Be careful with while loops.

Correct:

count = 1

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

If we forget:

count += 1

the condition may remain true forever.

That creates an infinite loop.

22. Infinite Loop

Example:

count = 1

while count <= 5:
    print(count)

count never changes, so:

count <= 5

always remains true.

Avoid accidental infinite loops.

23. while Loop with User Input

A while loop is useful when we don't know in advance how many times something should happen.

password = ""

while password != "python123":
    password = input("Enter password: ")

print("Login successful")

The program keeps asking until the correct password is entered.

24. break

The break statement immediately stops a loop.

Example:

for number in range(1, 11):

    if number == 6:
        break

    print(number)

Output:

1
2
3
4
5

When number becomes 6, break terminates the loop.

25. break with while

count = 1

while True:
    print(count)

    if count == 5:
        break

    count += 1

Output:

1
2
3
4
5

while True creates an intentional loop that we terminate using break.

26. continue

continue skips the current iteration and moves to the next iteration.

Example:

for number in range(1, 6):

    if number == 3:
        continue

    print(number)

Output:

1
2
4
5

When number is 3, the print() statement is skipped.

27. break vs continue

break

Stops the entire loop.

1
2
3
STOP

continue

Skips only the current iteration.

1
2
SKIP 3
4
5

28. pass

pass does nothing.

It can be used when you want to leave a block empty temporarily.

for number in range(5):
    pass

It is useful as a placeholder while developing a program.

29. Nested Loops

A loop inside another loop is called a nested loop.

Example:

for i in range(3):
    for j in range(2):
        print(i, j)

Output:

0 0
0 1
1 0
1 1
2 0
2 1

For every iteration of the outer loop, the inner loop runs completely.

30. Nested Loop Example

for row in range(1, 4):
    for column in range(1, 4):
        print(row, column)

This can be used for:

  • Tables
  • Matrix processing
  • Grids
  • Pattern generation
  • Nested data structures

31. Multiplication Table

Nested loops are not necessary for a single table, but for + range() makes it easy.

number = 5

for i in range(1, 11):
    print(number, "x", i, "=", number * i)

Output:

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

32. Multiple Tables

for number in range(2, 5):

    print("Table of", number)

    for i in range(1, 11):
        print(number, "x", i, "=", number * i)

    print()

This creates tables for 2, 3, and 4.

33. Looping Through a List with Conditions

Loops and conditions are commonly combined.

numbers = [10, 15, 20, 25, 30]

for number in numbers:

    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")

Output:

10 is even
15 is odd
20 is even
25 is odd
30 is even

34. Finding Numbers Greater Than 50

numbers = [10, 75, 30, 90, 45, 60]

for number in numbers:

    if number > 50:
        print(number)

Output:

75
90
60

35. Searching for an Item

courses = ["Python", "Django", "MERN", "Data Science"]

for course in courses:

    if course == "Django":
        print("Django course found")

36. Searching with break

Once we find the item, we can stop searching.

courses = ["Python", "Django", "MERN", "Data Science"]

for course in courses:

    if course == "Django":
        print("Course found")
        break

This avoids unnecessary iterations after the item is found.

37. Skipping Values with continue

Suppose we want to print only odd numbers.

for number in range(1, 11):

    if number % 2 == 0:
        continue

    print(number)

Output:

1
3
5
7
9

38. Looping Through Nested Lists

Consider:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

We can use nested loops:

for row in matrix:

    for value in row:
        print(value)

Output:

1
2
3
4
5
6
7
8
9

39. Printing a Matrix

We can print each row:

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:
    print(row)

Output:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

40. Printing a Pattern

Loops are useful for creating patterns.

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

Output:

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

Here, the string multiplication operator repeats "*".

41. Reverse Pattern

for i in range(5, 0, -1):
    print("*" * i)

Output:

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

42. for Loop with else

Python allows an else block after a loop.

Example:

for number in range(5):
    print(number)
else:
    print("Loop completed")

Output:

0
1
2
3
4
Loop completed

The else executes when the loop finishes normally.

43. Loop else with break

This is an important behavior.

for number in range(1, 6):

    if number == 3:
        break

    print(number)

else:
    print("Loop completed")

Output:

1
2

The else does not execute because the loop was terminated by break.

44. Searching with Loop else

This is a useful pattern.

numbers = [10, 20, 30, 40]

target = 25

for number in numbers:

    if number == target:
        print("Number found")
        break

else:
    print("Number not found")

Output:

Number not found

The else means:

The loop completed without finding the target.

45. enumerate() in Real Programs

Suppose we have student names:

students = ["Raj", "John", "Sita", "Michael"]

for index, student in enumerate(students, start=1):
    print(index, student)

Output:

1 Raj
2 John
3 Sita
4 Michael

This is useful for menus, rankings, lists, and numbered output.

46. zip() with Loops

zip() allows us to iterate through multiple sequences together.

names = ["Raj", "John", "Sita"]
marks = [85, 75, 90]

for name, mark in zip(names, marks):
    print(name, mark)

Output:

Raj 85
John 75
Sita 90

This is very useful when two lists contain related data.

47. Looping Through Two Lists

Without zip():

names = ["Raj", "John", "Sita"]
marks = [85, 75, 90]

for i in range(len(names)):
    print(names[i], marks[i])

With zip():

for name, mark in zip(names, marks):
    print(name, mark)

The second version is generally cleaner.

48. List Comprehension

Python provides a shorter way to create lists using loops.

Normal loop:

numbers = []

for number in range(1, 6):
    numbers.append(number * 2)

print(numbers)

Output:

[2, 4, 6, 8, 10]

Using list comprehension:

numbers = [number * 2 for number in range(1, 6)]

print(numbers)

Output:

[2, 4, 6, 8, 10]

49. List Comprehension with Condition

Normal approach:

numbers = []

for number in range(1, 11):

    if number % 2 == 0:
        numbers.append(number)

print(numbers)

List comprehension:

numbers = [
    number
    for number in range(1, 11)
    if number % 2 == 0
]

print(numbers)

Output:

[2, 4, 6, 8, 10]

List comprehensions are powerful, but beginners should first become comfortable with normal loops.

50. for vs while

for Loopwhile Loop
Iterates over a sequenceRuns while a condition is true
Good when number of iterations is knownGood when iterations depend on a condition
Common with lists and range()Common with user input and state-based logic
Automatically moves to next itemYou usually need to update the condition variable
Less likely to create infinite loopsEasier to accidentally create infinite loops

Use for when:

You know what you want to iterate over.

Example:

for student in students:
    print(student)

Use while when:

You want to continue until something happens.

Example:

while password != "python123":
    password = input("Enter password: ")

51. Practical Example : Student Marks

 

students = {
    "Raj": 85,
    "John": 72,
    "Sita": 91,
    "Michael": 64
}

for name, marks in students.items():

    if marks >= 80:
        grade = "A+"
    elif marks >= 70:
        grade = "A"
    elif marks >= 60:
        grade = "B"
    else:
        grade = "C"

    print(name, marks, grade)

This combines:

  • Dictionary
  • Loop
  • if
  • elif
  • else

52. Practical Example : Shopping Cart

cart = [
    {"name": "Keyboard", "price": 1500},
    {"name": "Mouse", "price": 800},
    {"name": "Headphone", "price": 2500}
]

total = 0

for item in cart:
    print(item["name"], item["price"])
    total += item["price"]

print("Total:", total)

Output:

Keyboard 1500
Mouse 800
Headphone 2500
Total: 4800

53. Practical Example : Password Attempts

correct_password = "python123"

attempts = 3

while attempts > 0:

    password = input("Enter password: ")

    if password == correct_password:
        print("Login successful")
        break

    attempts -= 1

    print("Incorrect password")
    print("Attempts remaining:", attempts)

if attempts == 0:
    print("Account temporarily locked")

This demonstrates:

  • while
  • if
  • break
  • Assignment operators
  • User input

54. Practical Example : Menu System

while True:

    print("\n1. Add Student")
    print("2. View Students")
    print("3. Exit")

    choice = input("Choose an option: ")

    if choice == "1":
        print("Add student selected")

    elif choice == "2":
        print("View students selected")

    elif choice == "3":
        print("Goodbye!")
        break

    else:
        print("Invalid choice")

This pattern is commonly used in command-line applications.

55. Copy Code

The following is the complete copy-ready code for the Python Loops lesson.

 

# ========================================== # Python Loops # ==========================================


# ------------------------------------------ # 1. Basic for loop # ------------------------------------------

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


# ------------------------------------------ # 2. range(start, stop) # ------------------------------------------

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


# ------------------------------------------ # 3. range(start, stop, step) # ------------------------------------------

for number in range(1, 11, 2):
    print(number)


# ------------------------------------------ # 4. Counting backwards # ------------------------------------------

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


# ------------------------------------------ # 5. Even numbers # ------------------------------------------

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


# ------------------------------------------ # 6. Odd numbers # ------------------------------------------

for number in range(1, 20, 2):
    print(number)


# ------------------------------------------ # 7. Loop through a list # ------------------------------------------

fruits = ["apple", "mango", "banana"]

for fruit in fruits:
    print(fruit)


# ------------------------------------------ # 8. Loop through a string # ------------------------------------------

name = "Python"

for character in name:
    print(character)


# ------------------------------------------ # 9. Loop through a tuple # ------------------------------------------

courses = ("Python", "Django", "MERN")

for course in courses:
    print(course)


# ------------------------------------------ # 10. Loop through a set # ------------------------------------------

skills = {"Python", "Django", "SQL"}

for skill in skills:
    print(skill)


# ------------------------------------------ # 11. Loop through dictionary keys # ------------------------------------------

student = {
    "name": "Raj",
    "age": 25,
    "course": "Python"
}

for key in student:
    print(key)


# ------------------------------------------ # 12. Dictionary keys # ------------------------------------------

for key in student.keys():
    print(key)


# ------------------------------------------ # 13. Dictionary values # ------------------------------------------

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


# ------------------------------------------ # 14. Dictionary items # ------------------------------------------

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


# ------------------------------------------ # 15. enumerate() # ------------------------------------------

fruits = ["apple", "mango", "banana"]

for index, fruit in enumerate(fruits):
    print(index, fruit)


# Start index from 1

for index, fruit in enumerate(fruits, start=1):
    print(index, fruit)


# ------------------------------------------ # 16. while loop # ------------------------------------------

count = 1

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


# ------------------------------------------ # 17. while loop with user input # ------------------------------------------

password = ""

while password != "python123":
    password = input("Enter password: ")

print("Login successful")


# ------------------------------------------ # 18. break # ------------------------------------------

for number in range(1, 11):

    if number == 6:
        break

    print(number)


# ------------------------------------------ # 19. continue # ------------------------------------------

for number in range(1, 6):

    if number == 3:
        continue

    print(number)


# ------------------------------------------ # 20. pass # ------------------------------------------

for number in range(5):
    pass


# ------------------------------------------ # 21. Nested loop # ------------------------------------------

for i in range(3):

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


# ------------------------------------------ # 22. Multiplication table # ------------------------------------------

number = 5

for i in range(1, 11):
    print(number, "x", i, "=", number * i)


# ------------------------------------------ # 23. Multiple multiplication tables # ------------------------------------------

for number in range(2, 5):

    print("Table of", number)

    for i in range(1, 11):
        print(number, "x", i, "=", number * i)

    print()


# ------------------------------------------ # 24. Loop with condition # ------------------------------------------

numbers = [10, 15, 20, 25, 30]

for number in numbers:

    if number % 2 == 0:
        print(number, "is even")
    else:
        print(number, "is odd")


# ------------------------------------------ # 25. Find numbers greater than 50 # ------------------------------------------

numbers = [10, 75, 30, 90, 45, 60]

for number in numbers:

    if number > 50:
        print(number)


# ------------------------------------------ # 26. Search with break # ------------------------------------------

courses = ["Python", "Django", "MERN", "Data Science"]

for course in courses:

    if course == "Django":
        print("Course found")
        break


# ------------------------------------------ # 27. Skip even numbers # ------------------------------------------

for number in range(1, 11):

    if number % 2 == 0:
        continue

    print(number)


# ------------------------------------------ # 28. Nested list # ------------------------------------------

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]

for row in matrix:

    for value in row:
        print(value)


# ------------------------------------------ # 29. Loop pattern # ------------------------------------------

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


# ------------------------------------------ # 30. Reverse pattern # ------------------------------------------

for i in range(5, 0, -1):
    print("*" * i)


# ------------------------------------------ # 31. Loop else # ------------------------------------------

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

else:
    print("Loop completed")


# ------------------------------------------ # 32. Loop else with break # ------------------------------------------

for number in range(1, 6):

    if number == 3:
        break

    print(number)

else:
    print("Loop completed")


# ------------------------------------------ # 33. Searching with loop else # ------------------------------------------

numbers = [10, 20, 30, 40]

target = 25

for number in numbers:

    if number == target:
        print("Number found")
        break

else:
    print("Number not found")


# ------------------------------------------ # 34. zip() # ------------------------------------------

names = ["Raj", "John", "Sita"]
marks = [85, 75, 90]

for name, mark in zip(names, marks):
    print(name, mark)


# ------------------------------------------ # 35. List comprehension # ------------------------------------------

numbers = [
    number * 2
    for number in range(1, 6)
]

print(numbers)


# ------------------------------------------ # 36. List comprehension with condition # ------------------------------------------

even_numbers = [
    number
    for number in range(1, 11)
    if number % 2 == 0
]

print(even_numbers)


# ------------------------------------------ # 37. Student marks system # ------------------------------------------

students = {
    "Raj": 85,
    "John": 72,
    "Sita": 91,
    "Michael": 64
}

for name, marks in students.items():

    if marks >= 80:
        grade = "A+"
    elif marks >= 70:
        grade = "A"
    elif marks >= 60:
        grade = "B"
    else:
        grade = "C"

    print(name, marks, grade)


# ------------------------------------------ # 38. Shopping cart # ------------------------------------------

cart = [
    {"name": "Keyboard", "price": 1500},
    {"name": "Mouse", "price": 800},
    {"name": "Headphone", "price": 2500}
]

total = 0

for item in cart:

    print(item["name"], item["price"])

    total += item["price"]

print("Total:", total)


# ------------------------------------------ # 39. Password attempts # ------------------------------------------

correct_password = "python123"

attempts = 3

while attempts > 0:

    password = input("Enter password: ")

    if password == correct_password:
        print("Login successful")
        break

    attempts -= 1

    print("Incorrect password")
    print("Attempts remaining:", attempts)

if attempts == 0:
    print("Account temporarily locked")


# ------------------------------------------ # 40. Menu system # ------------------------------------------

while True:

    print("\n1. Add Student")
    print("2. View Students")
    print("3. Exit")

    choice = input("Choose an option: ")

    if choice == "1":
        print("Add student selected")

    elif choice == "2":
        print("View students selected")

    elif choice == "3":
        print("Goodbye!")
        break

    else:
        print("Invalid choice")

56. Practice Exercises

Exercise 1 : Numbers

Print numbers from:

1 to 100

Then print only:

Even numbers

and:

Odd numbers

Exercise 2 : Sum of Numbers

Calculate the sum of numbers from 1 to 100.

Expected result:

5050

Exercise 3 : Multiplication Table

Ask the user for a number and print its multiplication table from 1 to 10.

Example:

Enter number: 7

7 x 1 = 7
7 x 2 = 14
...
7 x 10 = 70

Exercise 4 : Factorial

Ask the user for a number and calculate its factorial.

Example:

Enter number: 5

Factorial: 120

Exercise 5 : Count Vowels

Ask the user to enter a string and count how many vowels it contains.

Example:

Enter text: Python Programming

Vowels: 4

Exercise 6 : Find Maximum

Given:

numbers = [15, 72, 34, 91, 25, 60]

Find the largest number without using max().

Exercise 7 : Find Minimum

Given:

numbers = [15, 72, 34, 91, 25, 60]

Find the smallest number without using min().

Exercise 8 : Reverse a String

Ask the user for a string and reverse it using a loop.

Example:

Input: Python

Output: nohtyP

Exercise 9 : Login Attempts

Allow a user only three attempts to enter the correct password.

After three incorrect attempts:

Account locked

Exercise 10 : Student Result System

Create a dictionary containing student names and marks.

Use a loop to:

  • Display every student
  • Calculate grade
  • Find highest marks
  • Find lowest marks
  • Calculate class average
  • Count passed students
  • Count failed students

57. Challenge Project : SkillMantra Course Enrollment

Create a small console-based enrollment system.

Available courses:

courses = [
    "Python",
    "Django",
    "MERN",
    "Data Science",
    "Machine Learning"
]

Display a menu repeatedly:

===== SkillMantra Courses =====

1. View Courses
2. Search Course
3. Exit

The program should continue running until the user chooses 3.

Use:

  • while
  • for
  • if
  • elif
  • else
  • break
  • in

This combines almost everything learned in the lesson.

Interactive Sandbox
Python