Python While Loop

Tutorial Playlist

In this tutorial, we are going to learn about one of the most important control flow statements in Python i.e. while loop. First, we will start this while loop tutorial by introducing its basics, key features, and syntax, and then we will proceed to its overall working with practical examples, and advanced concepts like state machines, exception handling, and file handling using while loops in Python.

By the end of this Python while loops module, you will gain sufficient knowledge to use the while loops effectively in your Python Programming.

Table of Contents:

What is a While Loop in Python?

A while loop in Python is a control flow statement that allows you to execute a block of code repeatedly as long as a specified condition remains true. This type of loop is particularly useful when the number of iterations is not known beforehand but depends on a condition being met during execution.

Why Use While Loops?

  • To automate repetitive tasks without manually writing multiple lines of code.
  • Ideal for scenarios where the number of iterations isn’t fixed.
  • Helpful for reading user input until a valid response is received or processing dynamic data.

Syntax for While Loop in Python:

while test_expression:
body of while

Working of While Loop

The following flowchart explains the working of the while loop in Python:

python while loop

  • The program first evaluates the while loop condition.
  • If the condition of the loop is true, then the program enters the loop and executes the body of the while loop. It continues to execute the body of the while loop as long as the condition is true.
  • When it is false, the program comes out of the loop and stops repeating the body of the while loop.

Let’s see the following example of Python ‘while loop’ to understand it better.

Python

Output:

example of Python

The flowchart below shows each step:

  1. The condition counter < 10 is first checked before entering the loop. This verifies if the counter variable is less than 10.
  2. If true, the code inside the loop runs – it prints the value of the counter
  3. After printing, the counter is incremented by 1 with counter = counter + 1.
  4. Python returns to the top to re-check the condition.
  5. It continues looping and printing until the condition becomes false when the counter reaches 10.
  6. Once counter >= 10, the program exits the while loop and continues with any code after it.

Get 100% Hike!

Master Most in Demand Skills Now!

Infinite While Loop in Python

An infinite while loop refers to a while loop where the while condition never becomes false. When a condition never becomes false, the program enters the loop and keeps repeating that same block of code over and over again, and the loop never ends.

The following example shows an infinite loop:

Python

If we run the above code block, it will execute an infinite loop that will ask for our names again and again. The loop won’t break until we press ‘Ctrl+C’.

Python Do While Loop

Python doesn’t have a do-while loop. But we can create a program to implement do-while. It is used to check conditions after executing the statement. It is like a while loop but it is executed at least once.

Example:

Python

Output:

Python Do While Loop

Python While True Loop

There is a concept of declaring a condition to be true, without evaluating any expression. This is done to indicate that the loop has to run until it breaks. We then write the break statements inside the code block.

The while true in Python is simple to implement. Instead of declaring any Python variable, applying conditions, and then incrementing them, write true inside the conditional brackets.

Example: Using while True to Simulate Weekly Salary Calculation

Python

Output:

Weekly Salary Calculation

Python While Loop with Else

In Python, we can also use the else statement with loops. When the else statement is used with the while loop, it is executed only if the condition becomes false.

Example:

Python

Output:

Python While Loop with Else

In the above example, the program keeps executing the body of the while loop till the condition is true, meaning that the value of a is less than 5. Since the initial value of a is 1 and every time the program enters the loop the value of a is increased by 1, the condition becomes false after the program enters the loop for the fourth time when the value of a is increased from 4 to 5.

When the program checks the condition for the fifth time, it executes it as false goes to the else block, and executes the body of else, displaying, ‘condition is false now.’

Python While Loop Interruptions

Python offers the following two keywords which we can use to prematurely terminate a loop iteration.

1. Break statements in the While loop

The break keyword terminates the loop and transfers the control to the end of the loop.

Python

Output:

Break statements in the While loop

2. Continue statements in the While loop

The continue keyword terminates the ongoing iteration and transfers the control to the top of the loop and the loop condition is evaluated again. If the condition is true, then the next iteration takes place.

Example:

Python

Output:

Continue statements in the While loop

Handling Infinite Loops and Debugging

An infinite loop runs indefinitely unless a condition explicitly stops it. Detecting and interrupting such loops is crucial during development.

Python

Output:

Handling Infinite Loops and Debugging

Tips for Debugging:

  • Use print() statements to trace variables.
  • Press Ctrl + C to interrupt the program in the terminal/IDE.

Nested while Loops

Nested loops allow you to iterate over multiple dimensions, such as in grid structures.

Python

Output:

Nested while Loops

Examples of Python While Loop Programs

The examples given below demonstrate various use cases of the While loops in Python. Remember to choose the appropriate loop structure based on your specific needs and ensure proper indentation for clear and efficient code. Here are some common examples:

1. Summing Values

We keep summing numbers entered by the user until they enter 0.

Python

Output:

Summing Values

2. Number Pattern Program in Python using While Loop

This program will print a right-angled triangle pattern using *.

Python

Output:

Python using While Loop

3. Factorial Program in Python using While Loop

This is going to calculate the factorial of a given number using a while loop.

Python

Output:

Factorial Program in Python using While Loop

4. Combining while Loops with Functions

Encapsulating loops in functions allows better code organization and reusability.

Python

Output:

Combining while Loops with Functions

5. Tracking Loop Iterations Efficiently

Tracking iterations can be optimized by using enumerators or logging techniques.

Python

Output:

Tracking Loop Iterations Efficiently

Performance Comparison: while loop vs for-loop

In terms of performance efficiency between the for loop and while loop in Python, for loops are generally faster and more memory efficient than while loops because they majorly iterate over the predefined range of values with additional checks. However, if we talk about the while loops, they generally provide more flexibility for the scenarios where you need to iterate over the specific conditions dynamically until that condition is satisfied.

Example to measure performance benchmarks:

Python

Output:

while loop vs for-loop

Basically both while loops and for loops have their different advantages based on the conditions:

  • Use a while loop when the total number of iterations is unknown and the loop depends on the specific condition that needs to be satisfied.
  • Use for loop when you know the number of iterations of the program you want to write.

While Loops for Data Stream Processing

Ideal for reading from sockets, files, or continuously receiving data until a specific condition is met.

Note: In order to run this, you need to create the text file in your system in the same directory as this code.

Python

Output:

While Loops for Data Stream Processing

Break, Continue, and Else with while Loops

Control Statements like break, continue, and else generally change or alter the natural flow of the loops.

Python

Output:

Else with while Loops

Handling Exceptions Within While Loops

In Python, whenever you want to run any programs using a while loop, there may be a chance you will encounter any unexpected error or exceptions that can arise due to many reasons such as invalid inputs, file access errors, or any other runtime issues. To handle these exceptions you can simply use the try-except blocks in the while loop code that will simply ensure that your program handles all these errors smoothly instead of crashing the whole program.

Example: Handling User Input Errors

Python

Output: When you enter an integer

enter an integer

Output: When you enter a non-integer

enter a non-integer

Explanation:

  • The try block simply proceeds to convert the input into an integer. If the user enters any non-integer they will encounter a ValueError.
  • The except block simply catches all these errors and asks the user to input again which just prevents the whole program from crashing.

Implementing State Machines with while Loops

A state machine is generally a programming concept in which an application transitions between different states based on different conditions. While loops are majorly used in these implementations of state machines like in gaming, text parsers, and automation scripts.

Example: Simple ATM Transaction System

Python

Output:

Simple ATM Transaction System

Explanation:

  • The program starts in the “START” state and moves to “MENU”.
  • Based on user input, it transitions between different states like “WITHDRAW”, “DEPOSIT”, or “EXIT”.
  • The loop will continue to run until the user chooses to exit.

Resource Management and Cleanup in while Loops

Whenever a while loop of Python is used for tasks that include file handling, database connections, or any network operations, it is very important to release system resources properly to avoid any memory leaks and performance issues.

Example 1: Reading a File with Proper Cleanup

Python

Output:

Output

Explanation:

  • The file is opened before the loop starts.
  • The loop reads each line until there is no more data.
  • If the file is missing, a FileNotFoundError is handled.
  • The finally block ensures the file is closed even if an error occurs.

Example 2: Using with Statement for Automatic Cleanup

Python

Output:

Output

Note: In order to run these codes, you need to create the text file in your system in the same directory as this code.

Conclusion

In this Python While loops tutorial, you have learned everything about the while loops starting from its implementation to various topics like infinite loops, nested loops, and working with user input exception handling, and data processing state machines using while loops.

Remember, while loops in Python are a very powerful and flexible tool. By learning these concepts and best practices in this While Loops tutorial, you will become proficient in solving any complex problem of Python with so much ease.

FAQs on Python While Loops
1. What is a Python while loop, and when can I use it?

A while loop in Python is a concept or tool in which you write the particular condition that you want to execute repeatedly and it will get executed until the condition remains true. You can use the while loops when you do not know the exact number of repetitions of a particular problem

2. Can a while loop run infinitely in Python? How can I avoid infinite loops?

Yes, a while loop can run infinitely when the condition mentioned in the loop structure will always be true. In order to avoid these infinite loops, you can use break statements.

3. How does a while loop differ from a for loop in Python?

A for loop is generally preferred when you know the number of iterations of any conditions of the problem, whereas while loop is used when you are not sure about the number of iterations of that particular problem.

4. How can I use the break and continue statements in a loop?

You can use the break statement when you want to exit the condition of the program while the continue statement bypasses the present loop and jumps on to the next iteration structure.

5. Can I use else with a while loop in Python?

Yes, you can use else statements with a while loop in Python. Basically, the else statement will work only when the while loop ends naturally and not with a break statement.

Our Python Courses Duration and Fees

Program Name
Start Date
Fees
Cohort starts on 15th Mar 2025
₹20,007

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.