Python Programming for Beginners

Chapter 5: Python Loops – for and while

Chapter 5: Python Loops – for and while

5.1 Introduction

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

For example:

Display numbers from 1 to 10.

Print a message several times.

Process every item in a list.

Calculate the total of several numbers.

Repeat an operation until a condition becomes false.

Writing the same code repeatedly would be inefficient. Loops solve this problem by allowing a block of code to execute multiple times.

Python mainly provides two types of loops:

for loop

while loop

In this chapter, you will learn how to use both loops and how to control their execution.

5.2 What is a Loop?

A loop is a programming structure that repeatedly executes a block of code.

For example, instead of writing:

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

we can use a loop:

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

Output:

1 2 3 4 5

The loop makes the program shorter and easier to maintain.

5.3 Types of Loops in Python

Python provides two primary loop statements:

for loop

A for loop is commonly used when you want to iterate over a sequence or a known range of values.

while loop

A while loop repeats a block as long as a specified condition remains true.

5.4 The for Loop

The basic syntax of a for loop is:

for variable in sequence:    statement

Example:

for number in [1, 2, 3, 4, 5]:    print(number)

Output:

1 2 3 4 5

The variable number receives each value from the sequence one at a time.

5.5 Using range()

The range() function is frequently used with for loops.

Example:

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

Output:

0 1 2 3 4

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

5.6 range(start, stop)

You can specify both the starting and stopping values.

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

Output:

1 2 3 4 5

The stop value 6 is not included.

5.7 range(start, stop, step)

The third argument specifies the step size.

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

Output:

2 4 6 8 10

Here, the loop increases the value by 2 each time.

5.8 Counting Backwards

A negative step can be used to count backwards.

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

Output:

5 4 3 2 1

This technique is useful for countdown programs.

5.9 Printing a Message Multiple Times

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

Output:

Welcome to Python Welcome to Python Welcome to Python Welcome to Python Welcome to Python

The variable i is not used in the output, but it keeps track of the loop iterations.

5.10 Looping Through a String

A for loop can iterate over each character of a string.

word = "Python" for character in word:    print(character)

Output:

P y t h o n

This is useful when processing text character by character.

5.11 Looping Through a List

A for loop can process each item in a list.

fruits = ["apple", "banana", "mango"] for fruit in fruits:    print(fruit)

Output:

apple banana mango

Each iteration assigns the next list item to fruit.

5.12 Looping Through a Tuple

The same technique works with tuples.

numbers = (10, 20, 30, 40) for number in numbers:    print(number)

Output:

10 20 30 40

5.13 Using a for Loop with Conditions

A loop can contain an if statement.

Example:

for number in range(1, 11):    if number % 2 == 0:        print(number)

Output:

2 4 6 8 10

This program prints only the even numbers.

5.14 Calculating a Sum Using a for Loop

total = 0 for number in range(1, 6):    total = total + number print("Total:", total)

Output:

Total: 15

The variable total keeps track of the accumulated value.

5.15 Using the while Loop

A while loop repeatedly executes a block of code while a condition is true.

Syntax:

while condition:    statement

Example:

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

Output:

1 2 3 4 5

5.16 How a while Loop Works

Consider:

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

The process is:

count starts at 1.

Python checks count <= 3.

The condition is true.

count is printed.

count increases to 2.

The condition is checked again.

The process continues.

When count becomes 4, the condition is false.

The loop stops.

5.17 Importance of Updating the Condition

A while loop must normally change something that eventually makes its condition false.

For example:

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

If count += 1 were removed, the condition could remain true indefinitely.

This can create an infinite loop.

5.18 Infinite Loops

An infinite loop continues running because its condition never becomes false.

Example:

while True:    print("This keeps running")

This creates an intentional infinite loop.

Such loops are sometimes useful in programs that continuously wait for events, but they must have a suitable way to stop.

5.19 break Statement

The break statement immediately terminates 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, the loop stops.

5.20 continue Statement

The continue statement 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

The number 3 is skipped.

5.21 pass Statement

The pass statement does nothing.

It can be used when Python requires a statement but you do not want to execute anything yet.

Example:

for number in range(5):    if number == 2:        pass    print(number)

pass does not stop or skip the loop. It simply performs no operation at that point.

5.22 break, continue, and pass

These statements have different purposes:

StatementPurpose
breakStops the loop
continueSkips the current iteration
passDoes nothing

Understanding the difference is important when controlling loops.

5.23 Nested Loops

A loop can be placed inside another loop.

This is called a nested loop.

Example:

for i in range(1, 4):    for j in range(1, 4):        print(i, j)

Output:

1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3

For every iteration of the outer loop, the inner loop completes its iterations.

5.24 Nested Loop Example: Multiplication Table

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

5.25 Printing Multiple Tables

Nested loops can be used to create several multiplication tables.

for number in range(2, 5):    print("Table of", number)    for i in range(1, 6):        print(number, "x", i, "=", number * i)    print()

This produces tables for numbers 2, 3, and 4.

5.26 for Loop vs while Loop

Both loops can repeat code, but they are commonly used in different situations.

for Loopwhile Loop
Commonly used to iterate over sequencesCommonly used while a condition remains true
Useful with range()Useful when the number of repetitions is not known in advance
Often convenient for collectionsOften convenient for condition-controlled repetition
Usually has a clear iteration sequenceRequires careful condition management

Example of for:

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

Example of while:

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

Both produce the numbers 1 through 5.

5.27 User-Controlled while Loop

A while loop can continue until the user chooses to stop.

Example:

choice = "" while choice != "q":    choice = input("Enter q to quit: ") print("Program ended.")

The loop continues until the user enters q.

5.28 Example: Password Attempts

A loop can be used to limit the number of attempts in a learning example.

correct_password = "python123" attempts = 3 while attempts > 0:    password = input("Enter password: ")    if password == correct_password:        print("Access granted")        break    attempts -= 1    print("Incorrect password") if attempts == 0:    print("No attempts remaining")

This is an educational example. Real authentication systems should use secure password storage and proper security practices.

5.29 Example: Sum of User-Entered Numbers

Suppose we want the user to enter numbers until they enter 0.

total = 0 while True:    number = int(input("Enter a number (0 to stop): "))    if number == 0:        break    total += number print("Total:", total)

This demonstrates:

while

break

input

arithmetic

accumulation

5.30 Example: Counting Even Numbers

count = 0 for number in range(1, 21):    if number % 2 == 0:        count += 1 print("Even numbers:", count)

Output:

Even numbers: 10

5.31 Example: Factorial

The factorial of a positive integer n is the product of all positive integers from 1 through n.

For example:

5! = 5 × 4 × 3 × 2 × 1 = 120

Python program:

number = int(input("Enter a positive integer: ")) factorial = 1 for i in range(1, number + 1):    factorial *= i print("Factorial:", factorial)

5.32 Example: Reverse Countdown

number = int(input("Enter starting number: ")) while number >= 1:    print(number)    number -= 1 print("Finished!")

If the user enters 5:

5 4 3 2 1 Finished!

5.33 Looping Through a Dictionary

A for loop can iterate through dictionary keys.

student = {    "name": "Aman",    "age": 20,    "city": "Delhi" } for key in student:    print(key)

You can also access values:

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

Output:

name : Aman age : 20 city : Delhi

Dictionaries will be studied in greater detail later.

5.34 The enumerate() Function

When you need both an index and a value while looping through a sequence, enumerate() is useful.

Example:

fruits = ["apple", "banana", "mango"] for index, fruit in enumerate(fruits):    print(index, fruit)

Output:

0 apple 1 banana 2 mango

You can start the index from another number:

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

Output:

1 apple 2 banana 3 mango

5.35 The else Clause with Loops

Python allows an else clause with both for and while loops.

For a loop, the else block executes when the loop finishes normally, without encountering break.

Example:

for number in range(1, 4):    print(number) else:    print("Loop completed")

Output:

1 2 3 Loop completed

If break is executed, the loop's else block is skipped.

for number in range(1, 6):    if number == 3:        break    print(number) else:    print("Loop completed")

Output:

1 2

5.36 Common Loop Mistakes

Mistake 1: Forgetting to update a while loop

Incorrect:

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

The condition never changes, so the loop can continue indefinitely.

Correct:

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

Mistake 2: Incorrect indentation

Incorrect:

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

Correct:

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

Mistake 3: Incorrect range() expectation

Remember:

range(1, 5)

produces:

1 2 3 4

The ending value 5 is not included.

5.37 Mini Project: Number Guessing Game

Here is a simple educational guessing game.

secret_number = 7 guess = None while guess != secret_number:    guess = int(input("Guess the number: "))    if guess < secret_number:        print("Too low")    elif guess > secret_number:        print("Too high")    else:        print("Correct!")

This project demonstrates:

while

if

elif

else

Comparison operators

User input

Later, you can improve the game by generating a random number instead of using a fixed value.

5.38 Mini Project: Multiplication Table Generator

number = int(input("Enter a number: ")) print("Multiplication Table") for i in range(1, 11):    result = number * i    print(number, "x", i, "=", result)

This is a useful beginner project for practicing loops.

5.39 Mini Project: Simple Menu Program

while True:    print("\n1. Say Hello")    print("2. Show Message")    print("3. Exit")    choice = input("Enter your choice: ")    if choice == "1":        print("Hello! Welcome to Python.")    elif choice == "2":        print("You are learning Python loops.")    elif choice == "3":        print("Goodbye!")        break    else:        print("Invalid choice.")

This example demonstrates how a while loop can create a simple repeating menu.

5.40 Chapter Summary

In this chapter, you learned:

What loops are

Why loops are useful

for loops

while loops

The range() function

Start, stop, and step values

Counting forward and backward

Looping through strings

Looping through lists and tuples

Conditions inside loops

break

continue

pass

Nested loops

Loop else

enumerate()

Common loop mistakes

Practical loop-based programs

Loops are one of the most important programming concepts because they allow programs to perform repetitive tasks efficiently.

Quick Revision Questions

1. What is a loop?
A loop repeatedly executes a block of code.

2. What are the two main loops in Python?
for and while.

3. Which function is commonly used to generate a sequence of numbers for a for loop?
range().

4. Does range(5) include 5?
No. It generates values from 0 through 4.

5. What does break do?
It immediately terminates the loop.

6. What does continue do?
It skips the current iteration and proceeds to the next iteration.

7. What does pass do?
It performs no operation.

8. What is an infinite loop?
A loop that continues because its stopping condition is never reached.

9. What is a nested loop?
A loop placed inside another loop.

10. When is a while loop commonly useful?
When repetition depends on a condition and the number of iterations may not be known beforehand.

Practice Exercises

Exercise 1: Print Numbers

Write a program using a for loop to print numbers from 1 to 20.

Exercise 2: Even Numbers

Print all even numbers from 1 to 50.

Exercise 3: Odd Numbers

Print all odd numbers from 1 to 50.

Exercise 4: Multiplication Table

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

Exercise 5: Sum of Numbers

Calculate the sum of numbers from 1 to 100 using a loop.

Exercise 6: Factorial

Ask the user for a positive integer and calculate its factorial.

Exercise 7: Countdown

Ask the user for a starting number and create a countdown to 1.

Exercise 8: List Processing

Create a list containing five student names and use a for loop to display each name.

Exercise 9: Search

Create a list of numbers and use a loop to find whether a particular number exists.

Exercise 10: Menu

Create a repeating menu using a while loop with an option to exit.

Chapter Activity

Create a Student Marks Analyzer using loops.

The program should:

Ask how many students need to be entered.

Accept the marks of each student.

Calculate the total marks.

Calculate the average marks.

Count how many students passed.

Count how many students failed.

Display the final statistics.

Try to use:

for

while

if

else

Arithmetic operators

Variables

Next Chapter: Python Functions – Creating and Using Functions