Python Loops Explained: for Loop, while Loop and Nested Loops

Python loops allow a program to repeat a block of code without writing the same instructions again and again. They are essential for processing lists, generating repeated output, calculating values, reading collections and building practical applications.

This guide explains Python for loops, while loops, nested loops, the range() function, break, continue and pass with practical examples. It also explains how to decide which type of loop to use and how to avoid common infinite-loop and logic errors.

Once variables, operators and conditional statements are comfortable, learning Python programming becomes much more practical when repetition and data processing are introduced through loops.

What Are Loops in Python?

A loop repeatedly executes a block of code according to a defined rule.

For example, suppose you want to print the numbers from 1 to 5. Without a loop, you could write:

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

A loop makes the same task shorter and easier to modify:

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

The advantage becomes much greater when the number of repetitions increases or when the program needs to process changing data.

Why Are Python Loops Important?

Loops are used whenever a program needs to perform a repeated operation.

  • Processing items in a list
  • Reading records
  • Calculating totals
  • Searching through data
  • Generating reports
  • Repeating user interactions
  • Processing files
  • Running calculations
  • Building menu-driven programs
  • Working with databases and APIs

Loops become especially powerful when combined with conditions and functions.

Types of Loops in Python

Loop Best Used When Typical Example
for You are iterating over a sequence or known range Processing items in a list
while Repetition depends on a condition Repeating until valid input is received
Nested loop One repeated operation occurs inside another Processing rows and columns

Python for Loop

The for loop is commonly used to iterate over a sequence such as a list, tuple, string or range of numbers.

for number in [10, 20, 30]:
    print(number)

The loop takes each item from the collection and executes the indented block.

Using for Loop with range()

The range() function is frequently used when a loop needs to run over a sequence of numbers.

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

This produces values from 0 through 4.

To start at 1 and stop after 5:

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

The ending value in range() is not included.

Understanding range()

The basic form of range() can use a start value, stop value and step value.

range(start, stop, step)

For example:

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

This prints even numbers from 2 through 10.

A negative step can be used to count backwards:

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

Looping Through a String

A string is a sequence of characters, so a for loop can process each character individually.

word = "Python"

for character in word:
    print(character)

This technique can be useful when searching, counting or validating individual characters.

Looping Through a List

Lists are one of the most common data structures used with loops.

students = ["Riya", "Aman", "Neha"]

for student in students:
    print(student)

You can also perform calculations while processing each item.

marks = [70, 85, 92, 66]

for mark in marks:
    print(mark + 5)

Using Conditions Inside a Loop

Loops and conditional statements are often used together.

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

for number in numbers:
    if number % 2 == 0:
        print(number)

Here, the loop processes every number while the condition determines which values are displayed.

Python while Loop

A while loop repeatedly executes a block of code as long as its condition remains true.

count = 1

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

The variable controlling the condition must eventually change if the loop is intended to stop.

How a while Loop Works

A while loop generally follows this sequence:

  1. Set an initial value.
  2. Check the condition.
  3. Execute the loop body if the condition is true.
  4. Update the relevant value.
  5. Check the condition again.
  6. Stop when the condition becomes false.

For example:

count = 1

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

The update count += 1 is important because it moves the program toward the stopping condition.

for Loop vs while Loop

Choosing the correct loop is easier when you focus on what controls the repetition.

Situation Recommended Loop Reason
Process every item in a list for The collection already defines what to iterate over
Repeat a fixed number of times for range() clearly represents the repetition
Continue until a condition changes while The condition controls the loop
Repeat until valid input while The number of attempts may not be known beforehand

A simple rule is useful: if you are iterating over known data, start by considering a for loop. If you are waiting for a condition to change, a while loop may be more appropriate.

Infinite Loops

An infinite loop occurs when a loop's condition never becomes false.

count = 1

while count <= 5:
    print(count)

The above loop never changes count, so the condition remains true.

A corrected version is:

count = 1

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

When writing a while loop, always identify what event will eventually make the condition false.

Python break Statement

The break statement immediately exits a loop.

for number in range(1, 11):
    if number == 6:
        break
    print(number)

The loop stops when the value reaches 6.

break is useful when the required result has already been found and there is no reason to continue processing the remaining values.

Python continue Statement

The continue statement skips the current iteration and moves to the next one.

for number in range(1, 6):
    if number == 3:
        continue
    print(number)

The value 3 is skipped, but the loop continues with the remaining values.

Python pass Statement

The pass statement does nothing. It can be used as a placeholder when a block of code is required syntactically but the implementation has not yet been written.

for number in range(5):
    pass

Unlike break and continue, pass does not change the normal flow of the loop.

Nested Loops in Python

A nested loop is a loop inside another loop.

for row in range(3):
    for column in range(3):
        print(row, column)

The outer loop controls the rows while the inner loop runs for each row.

Nested loops are useful for working with grids, tables, matrices and combinations of values.

Nested Loop Example: Multiplication Tables

for number in range(1, 4):
    for multiplier in range(1, 6):
        print(number * multiplier)
    print()

The outer loop selects the number and the inner loop performs the repeated multiplication.

Nested Loop Example: Simple Pattern

for row in range(1, 5):
    for column in range(row):
        print("*", end=" ")
    print()

The inner loop runs a different number of times depending on the current outer-loop value.

Looping Through a Dictionary

Python dictionaries can also be processed using loops.

student = {
    "name": "Riya",
    "age": 20,
    "course": "Python"
}

for key in student:
    print(key, student[key])

The items() method can make key-value iteration clearer:

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

Calculating a Total with a Loop

Loops are frequently used to calculate totals from collections.

prices = [100, 250, 350, 150]

total = 0

for price in prices:
    total += price

print(total)

The variable total acts as an accumulator. Each value is added to the existing total.

Finding a Value with a Loop

A loop can also be used to search through data.

names = ["Riya", "Aman", "Neha", "Karan"]
target = "Neha"

for name in names:
    if name == target:
        print("Student found")
        break

The break statement prevents unnecessary processing once the required value has been found.

Using a while Loop for Input Validation

A while loop is useful when the program should continue asking for input until the user provides an acceptable value.

age = int(input("Enter your age: "))

while age < 0:
    print("Age cannot be negative.")
    age = int(input("Enter your age again: "))

print(f"Age entered: {age}")

The number of attempts is not fixed, so a while loop fits this situation naturally.

Common Python Loop Mistakes

  • Forgetting to update the control variable in a while loop.
  • Using the wrong range boundaries.
  • Adding unnecessary nested loops.
  • Changing a collection unexpectedly while iterating over it.
  • Using break when continue was intended.
  • Using the wrong indentation.
  • Writing a loop without clearly identifying when it should stop.

How to Debug a Python Loop

When a loop produces unexpected output, inspect the values being processed rather than guessing at the problem.

numbers = [10, 20, 30]

for number in numbers:
    print("Current value:", number)

Temporary print statements can help you understand which iteration is running and what values are being used.

For a while loop, inspect both the current value and the condition controlling the loop.

count = 1

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

This makes it easier to identify incorrect updates or unexpected values.

Practical Python Loop Example: Student Marks

Suppose a program needs to calculate the average marks of several students.

marks = [75, 82, 68, 91, 88]

total = 0

for mark in marks:
    total += mark

average = total / len(marks)

print(f"Average marks: {average:.2f}")

This example combines a list, a loop, an accumulator, the len() function and arithmetic.

The important learning point is that the loop is not useful simply because it reduces the number of lines. It provides a systematic way to process every value in the collection.

Python Loop Practice Questions

Practise loops by solving problems that gradually increase in complexity.

  1. Print numbers from 1 to 10.
  2. Print even numbers from 1 to 50.
  3. Print numbers in reverse order.
  4. Calculate the sum of numbers from 1 to 100.
  5. Print a multiplication table.
  6. Count vowels in a string.
  7. Find the largest number in a list.
  8. Calculate the average of a list of marks.
  9. Search for a particular value in a list.
  10. Create a menu-driven program using a while loop.

When Should You Use a Loop?

Before writing a loop, identify what exactly is being repeated.

  • If each item in a collection needs to be processed, consider for.
  • If a fixed number of repetitions is required, consider for with range().
  • If repetition continues until a condition changes, consider while.
  • If a search can stop once a match is found, consider break.
  • If specific iterations should be skipped, consider continue.

This simple decision process can prevent many unnecessary or complicated loop structures.

Why Choose Upskill Now for Learning Python?

Loops are much easier to understand when learners repeatedly apply them to different types of problems. A structured Python program can help connect loops with conditions, collections, functions and projects instead of treating each topic as an isolated chapter.

Upskill Now's Python program progresses from fundamentals and programming logic into data structures, object-oriented programming, file handling, exception management, databases, automation and APIs.

The practical projects provide opportunities to apply programming concepts in larger contexts. Projects such as the Student Management System, Expense Tracker, Library Management System, Employee Database Management and Weather Information Application require learners to combine multiple Python concepts instead of relying on single-line examples.

How Upskill Now Can Connect Loops to Practical Projects

Python Concept What You Practise Possible Application
for loop Processing collections Student or employee records
while loop Condition-based repetition Menu-driven applications
Conditions Decision making Validation and business rules
Collections Managing multiple values Expenses, marks and inventory
Functions Organising repeated logic Reusable application features

Upskill Now also introduces tools such as VS Code, PyCharm, MySQL, Git and GitHub, REST APIs and command-line tools as learners progress toward practical development.

For learners looking to move from Python syntax to project-based programming, Upskill Now's Python training can be evaluated based on its curriculum, projects and learning format.

What Should You Know Before Moving Beyond Loops?

You do not need to memorise every loop example before progressing. Instead, you should be able to reason about repetition.

You should be comfortable answering questions such as:

  • What needs to be repeated?
  • How many times should it repeat?
  • What data is being processed?
  • What condition should stop the repetition?
  • Should some iterations be skipped?
  • Can the loop stop early after finding the required result?

If you can answer these questions before writing the code, your understanding of loops is becoming practical rather than purely syntax-based.

Conclusion

Python loops provide the repetition required to process data and automate repeated tasks. The for loop is particularly useful for iterating over sequences and known ranges, while the while loop is useful when repetition depends on a changing condition.

Nested loops, break, continue and conditions extend the possibilities further. The most effective way to learn these concepts is to solve progressively harder problems instead of memorising isolated examples.

Loops become especially valuable when combined with collections, functions, files, databases and APIs. A structured learning path such as Upskill Now's Python program can help learners make that transition from basic programming exercises to practical projects.

Contact Upskill Now

A-3, Third Floor, Rajouri Garden, New Delhi – 110027

Phone: 9999848160 | 9711448765

Email: connect@upskillnow.in