Python while Loop with range() Function – A Beginner Guide

Introduction

💡 Think About It
What if we want Python to repeat a task while a condition remains true?

A while loop is another way to repeat a block of code in Python. It keeps running the code as long as a specified condition is true.

In this tutorial, we’ll learn the basics of the while loop and use it to perform simple counting tasks similar to those we previously performed using for loops with range().

🔎 A useful connection
With a for loop, Python can automatically move through the values produced by range(). With a while loop, we control the condition and update the loop variable ourselves.

Let’s start by understanding what a while loop is and how it works.

1. What is a while Loop?

A while loop is used to repeat a block of code as long as a specified condition is true.

Before each repetition, Python checks the condition. If the condition is True, the code inside the loop runs. When the condition becomes False, the loop stops.

▶ Simple Example
i = 1

while i <= 5:
    print(i)
    i += 1
▶ Output
1
2
3
4
5
🔎 How does it work?
1. Start with i = 1.
2. Python checks whether i <= 5 is true.
3. If true, the loop prints i.
4. i is increased by 1.
5. The process continues until the condition becomes false.
⭐ Important A while loop needs a condition that can eventually become false. The loop variable must usually be updated inside the loop; otherwise, the loop may continue indefinitely.
🔗 Connection with the for loop
The same counting task that we performed with for + range() can also be performed using a while loop. The main difference is that with a while loop, we manage the condition and update ourselves.

Next, let’s look at the basic syntax of a while loop.

2. Explain the Basic Syntax of a while Loop

The basic syntax of a while loop is simple. It consists of a condition followed by the statements that should be repeated.

📝 Basic Syntax
while condition:
    statement
🔎 Understanding the syntax:
  • while – the keyword used to start the loop.
  • condition – an expression that is checked before each repetition.
  • : – the colon indicates the beginning of the loop body.
  • statement – the code that is executed while the condition is True.
💻 Example
i = 1

while i <= 5:
    print(i)
    i += 1
📤 Output
1
2
3
4
5
⭐ Important: The condition is checked before every repetition. Therefore, the loop body executes only when the condition is True. The loop variable should normally be updated inside the loop so that the condition eventually becomes False.

In this example, i starts at 1 and increases by 1 after each repetition. When i becomes 6, the condition i <= 5 becomes false, so the loop stops.

🔗 Connection with for + range(): A for loop with range() handles the sequence automatically. With a while loop, you usually need to initialize, check, and update the loop variable yourself.

3. Understanding Counting with a while Loop

In the previous for loop article, we used the range() function to generate a sequence of numbers automatically.

A while loop does not use range() directly. Instead, we control the counting ourselves using a starting value, a condition, and an update.

🔎 The main difference:
  • for + range() → Python manages the sequence of numbers.
  • while → We manage the starting value, condition, and update.
🔵 Using for + range()
for i in range(1, 6):
    print(i)
🟢 Using while
i = 1

while i <= 5:
    print(i)
    i += 1
📤 Output from Both Programs
1
2
3
4
5
🧠 Remember the three parts:
  1. Initialize – choose the starting value.
  2. Condition – decide when the loop should continue.
  3. Update – change the value after each repetition.
Key Point: range() is a feature commonly used with for loops. With a while loop, you can achieve similar counting by controlling the loop variable yourself.

4. Counting from a Start Value to a Stop Value

In a for loop, range(start, stop) allows us to start counting from a particular value and continue up to, but not including, the stop value.

With a while loop, we can achieve the same result by setting the starting value, checking the condition, and increasing the value after each repetition.

🔵 Equivalent for Loop
for i in range(2, 6):
    print(i)
🟢 Equivalent while Loop
i = 2

while i < 6:
    print(i)
    i += 1
📤 Output
2
3
4
5
🔎 How does it work?
  1. Initialize: i = 2 sets the starting value.
  2. Check: i < 6 determines whether the loop should continue.
  3. Print: The current value of i is displayed.
  4. Update: i += 1 increases the value by 1.
  5. When i becomes 6, the condition becomes false and the loop stops.
⭐ Important: Just like range(start, stop), the stop value is not included. In this example, the loop prints 2, 3, 4, 5, but not 6.
💡 Remember: With while, there is no start and stop parameter. We create the same counting behavior using an initial value, a condition, and an update.

5. Counting with a Step Value Using a while Loop

In a for loop, range(start, stop, step) allows us to control how much the value changes after each repetition.

A while loop does not have a step parameter. Instead, we control the step ourselves by changing the loop variable inside the loop.

🔵 Using for + range(start, stop, step)
for i in range(2, 11, 2):
    print(i)
🟢 Equivalent while Loop
i = 2

while i < 11:
    print(i)
    i += 2
📤 Output
2
4
6
8
10
🔎 How does it work?
  1. Initialize: i = 2 sets the starting value.
  2. Check: i < 11 checks whether the loop should continue.
  3. Print: The current value of i is displayed.
  4. Update: i += 2 increases the value by 2.
  5. When i becomes 12, the condition becomes false and the loop stops.
🧠 Understanding the Step:

The statement i += 2 means that 2 is added to i after every repetition.

Therefore, the values are: 2 → 4 → 6 → 8 → 10

Important: In a while loop, the step is controlled by the update statement. For example, i += 1 increases the value by 1, while i += 2 increases it by 2.
💡 Remember: range(start, stop, step) is specific to range(). With a while loop, we create similar counting behavior by controlling the initial value, condition, and update ourselves.

6. Three Common Ways to Count Using a while Loop

With range(), the for loop provides different ways to control a sequence of numbers. With a while loop, we can create similar counting patterns by controlling the starting value, condition, and update.

Here are three common ways to count using a while loop.

① Start from a Value
i = 5

while i <= 8:
    print(i)
    i += 1
② Count with a Step
i = 2

while i <= 10:
    print(i)
    i += 2
③ Count Backward
i = 5

while i >= 1:
    print(i)
    i -= 1
🔎 What do these examples show?
  • Start from a value: Begin counting from any suitable number.
  • Count with a step: Use an update such as i += 2 to skip numbers.
  • Count backward: Use i -= 1 to decrease the value after each repetition.
🧠 Key Difference from range():

The range() function provides start, stop, and step values directly. In a while loop, we control these ideas ourselves using the variable initialization, condition, and update statement.

Quick Summary: while gives us more direct control over how the loop variable changes. We decide where to start, when to stop, and how much to change after each repetition.

7. Simple Programs Using a while Loop

Now that we understand the basic syntax and counting logic of a while loop, let’s look at some simple programs.

These examples are suitable for beginners and help you understand how a while loop can be used for different counting tasks.

🟦 Program 1: Print Numbers from 1 to 5
i = 1

while i <= 5:
    print(i)
    i += 1
🟩 Program 2: Print Even Numbers
i = 2

while i <= 10:
    print(i)
    i += 2
🟨 Program 3: Print Numbers from 5 to 1
i = 5

while i >= 1:
    print(i)
    i -= 1
🟥 Program 4: Print Odd Numbers
i = 1

while i <= 9:
    print(i)
    i += 2
🟪 Program 5: Print Multiples of 5
i = 5

while i <= 25:
    print(i)
    i += 5
🟧 Program 6: Calculate Sum from 1 to 5
i = 1
total = 0

while i <= 5:
    total += i
    i += 1

print(“Sum =”, total)
📤 Outputs
Program 1:
1 2 3 4 5

Program 2:
2 4 6 8 10

Program 3:
5 4 3 2 1

Program 4:
1 3 5 7 9

Program 5:
5 10 15 20 25

Program 6:
Sum = 15
🧠 What should you notice?
  • The loop starts with an initial value.
  • The condition decides whether the loop continues.
  • The update changes the loop variable after each repetition.
  • Changing the update allows us to count by 1, 2, 5, or another value.
  • For counting backward, we use an update such as i -= 1.
⭐ Beginner Tip: Before writing a while loop, identify three things: Where should the counting start? When should it stop? and How should the value change?

8. Remember This

🧠 ⭐ Remember This
🔹 A while loop repeats a block of code as long as its condition is True.
🔹 The condition is checked before each repetition.
🔹 Usually, a while loop needs three important parts: initialization, condition, and update.
🔹 The update statement changes the loop variable and helps the loop eventually stop.
🔹 Use i += 1 to increase a value and i -= 1 to decrease it.
🔹 Unlike for + range(), a while loop gives you direct control over the condition and update.
💡 Simple rule: Start → Check → Execute → Update → Repeat
🚀 Quick Tip: Before running a while loop, always ask: “Will the condition eventually become False?” If yes, the loop can stop normally.

9. Practice Questions

Try to solve the following programs using a while loop. These questions will help you practise initialization, conditions, updates, step values, and counting in different directions.

💡 Practice Tip: Before writing each loop, identify the starting value, condition, and update.
1. Write a Python program using a while loop to print the numbers from 1 to 10.
2. Write a program using a while loop to print the numbers from 10 to 1.
3. Write a program to print all even numbers from 2 to 20 using a while loop.
4. Write a program to print all odd numbers from 1 to 19 using a while loop.
5. Write a program to print the numbers 5, 10, 15, 20, 25 using a while loop.
6. Write a program to print the numbers 20, 18, 16, 14, 12, 10 using a while loop.
7. Write a program using a while loop to calculate the sum of numbers from 1 to 10.
8. Write a program using a while loop to print the multiples of 3 from 3 to 30.
🚀 Challenge Yourself

Try writing the programs without looking at the previous examples. Pay special attention to the update statement because it controls how the loop variable changes.

10. Practice Questions – Solutions

Here are the solutions to the practice questions. Compare your programs with these solutions and try to understand how the while loop variable is initialized, checked, and updated.

🟦 Solution 1: Numbers from 1 to 10
i = 1

while i <= 10:
    print(i)
    i += 1
🟩 Solution 2: Numbers from 10 to 1
i = 10

while i >= 1:
    print(i)
    i -= 1
🟨 Solution 3: Even Numbers
i = 2

while i <= 20:
    print(i)
    i += 2
🟥 Solution 4: Odd Numbers
i = 1

while i <= 19:
    print(i)
    i += 2
🟪 Solution 5: Multiples of 5
i = 5

while i <= 25:
    print(i)
    i += 5
🟧 Solution 6: Numbers 20 to 10
i = 20

while i >= 10:
    print(i)
    i -= 2
🟦 Solution 7: Sum from 1 to 10
i = 1
total = 0

while i <= 10:
    total += i
    i += 1

print(“Sum =”, total)
🟩 Solution 8: Multiples of 3
i = 3

while i <= 30:
    print(i)
    i += 3
📤 Expected Outputs
1: 1 2 3 4 5 6 7 8 9 10
2: 10 9 8 7 6 5 4 3 2 1
3: 2 4 6 8 10 12 14 16 18 20
4: 1 3 5 7 9 11 13 15 17 19
5: 5 10 15 20 25
6: 20 18 16 14 12 10
7: Sum = 55
8: 3 6 9 12 15 18 21 24 27 30
🧠 What did we practise?
  • Increasing a variable using i += 1.
  • Decreasing a variable using i -= 1 or i -= 2.
  • Counting with different step values.
  • Using a while loop to calculate a sum.
  • Controlling exactly when a loop starts and stops.
⭐ Remember: In a while loop, always check the initial value, condition, and update. These three parts control how the loop works.

11. Conclusion

The while loop is an important Python looping statement used to repeat a block of code as long as a condition remains True.

Unlike for + range(), where Python manages the sequence of values, a while loop gives the programmer direct control over the starting value, condition, and update.

🧠 Key Takeaways
🔹 A while loop repeats while its condition is True.
🔹 The condition is checked before every repetition.
🔹 The loop variable is usually initialized before the loop.
🔹 The update statement controls how the variable changes.
🔹 A while loop can be used for increasing, decreasing, and step-based counting.
Final Tip: When writing a while loop, remember: Start → Check → Execute → Update → Repeat.
🚀 Keep Practising!
The best way to understand loops is to write and run small programs. Try changing the starting value, condition, and update in the examples and observe how the output changes.
Happy Coding! 💻🐍

Gopal Krishna

Hey Engineers, welcome to the award-winning blog,Engineers Tutor. I'm Gopal Krishna. a professional engineer & blogger from Andhra Pradesh, India. Notes and Video Materials for Engineering in Electronics, Communications and Computer Science subjects are added. "A blog to support Electronics, Electrical communication and computer students".

Leave a Reply

Your email address will not be published. Required fields are marked *

Translate »