Python Tutorial

Python while loop: Syntax, Examples, Programs, How to Use?

Table of Contents

  • Introduction
  • What is While Loop in Python?
  • While Loop Syntax in Python
  • How While Loops Work in Python?
  • Python while loop Examples
  • While Loop Programs in Python
  • While Loop with else
  • Single Statement While Loop in Python
  • Infinite While Loop in Python
  • While Loop Control Statements in Python
  • do while loop in Python
  • Nested while in Python
  • while true in Python
  • Difference Between while and for loop in Python

Introduction

Python consists of various control flow statements. These loops are used to repeat a block of code multiple times. One such control flow statement is the while loop that is used to execute a set of statements repeatedly until a specific condition is met. Once the condition is evaluated to be false, the while loop is terminated immediately.

What is While Loop in Python?

The Python while loop is used to execute a specific block of statements repeatedly until a certain condition provided in the while loop statement is fulfilled. When the condition becomes false, the line following the loop in the program is executed. 

The number of times the while loop is repeated or executed is unknown in advance. Hence, it is also known as an indefinite iteration statement. It is continuously repeated until the condition is true and ends only when the condition becomes false.

While Loop Syntax in Python

The syntax of Python while loop is:

while expression:
    statement(s)

Explanation of the syntax

  • statement(s) can either be a single statement or a block of uniformly indented statements, which is treated as a block in Python.

  • expression refers to the conditional statement that is evaluated initially in the Python while loop. If the conditional expression returns the boolean value True, the while loop is executed again. Again, the statement is verified once the code block is executed. The process keeps on repeating until the conditional expression gives the boolean value False. 

  • Python interprets any non-zero number as a boolean True and none and 0 as a boolean False. 

  • We use the while keyword to write the while loop statement.

  • The while expression is the starting of the while loop statement. 

How While Loops Work in Python?

A while loop in Python repeatedly executes a block of code as long as a specified condition remains true. 

Below is a breakdown of the key elements involved:

Syntax:

  • The loop begins with the while keyword followed by a condition.

  • The indented block of code beneath it is what gets executed repeatedly as long as the condition remains true.

Condition:

  • The condition is a Boolean expression that determines whether the loop should continue or terminate.

  • If the condition is initially false, the code block is skipped entirely, and the program moves on.

Execution Process:

  • The condition is evaluated before entering the loop. If it's false from the start, the loop is skipped.

  • If the condition is true, the code block inside the loop is executed.

  • After the execution of the code block, the condition is re-evaluated.

  • If the condition is still true, the loop executes the code block again.

  • This process repeats until the condition becomes false, at which point the program exits the loop and continues with the subsequent code.

Updating the Condition:

  • It's crucial to ensure that the condition in the while loop has the potential to become false.

  • Typically, within the code block, there should be some logic that alters the variables or conditions being checked, eventually leading to the condition becoming false.

  • If the condition always evaluates to true, the loop will continue indefinitely, resulting in an infinite loop.

Python while loop Examples

Let's go through a few examples of Python while loops:

Example 1: Counting Up

count = 1
while count <= 5:
    print(f"Count is {count}")
    count += 1

Explanation:

  • The loop starts with count equal to 1.

  • The condition count <= 5 is true, so the code block is executed.

  • It prints the current value of count and increments it by 1.

  • The loop continues until count is no longer less than or equal to 5.

Output:

Count is 1
Count is 2
Count is 3
Count is 4
Count is 5

Example 2: Sum of Numbers

total = 0
num = 1
while num <= 5:
    total += num
    num += 1
print(f"Sum of numbers 1 to 5 is: {total}")

Explanation:

  • The loop initializes total to 0 and num to 1.

  • While num is less than or equal to 5, it adds num to total and increments num.

  • The loop continues until num is no longer less than or equal to 5.

  • It then prints the sum of numbers from 1 to 5.

Output:

Sum of numbers 1 to 5 is: 15

Example 3: User Input Validation

user_input = input("Enter a positive number: ")
number = int(user_input)
while number <= 0:
    print("Invalid input. Please enter a positive number.")
    user_input = input("Enter a positive number: ")
    number = int(user_input)
print(f"Thank you! You entered: {number}")

Explanation:

  • This example ensures that the user enters a positive number.

  • It prompts the user until a positive number is provided.

  • The while loop runs as long as the entered number is less than or equal to 0.

  • It repeatedly asks for input until a valid positive number is given.

Output:

Enter a positive number: -3
Invalid input. Please enter a positive number.
Enter a positive number: 0
Invalid input. Please enter a positive number.
Enter a positive number: 7
Thank you! You entered: 7

While Loop Programs in Python

Here are a few while loop programs in Python, along with their outputs and short explanations:

1. Factorial Calculation

# Calculate the factorial of a number using a while loop
num = int(input("Enter a number: "))
factorial = 1
i = 1
while i <= num:
    factorial *= i
    i += 1
print(f"The factorial of {num} is: {factorial}")

Explanation:

  • This program calculates the factorial of a given number using a while loop.

  • It initializes factorial to 1 and i to 1.

  • The loop multiplies factorial by i and increments i until i is no longer less than or equal to the input number.

Output:

Enter a number: 5
The factorial of 5 is: 120

 

2. Guess the Number Game

# Simple guess the number game using a while loop
import random
secret_number = random.randint(1, 10)
guess = 0
while guess != secret_number:
    guess = int(input("Guess the secret number (between 1 and 10): "))
    if guess != secret_number:
        print("Try again!")
print("Congratulations! You guessed the secret number.")

Explanation:

  • This program generates a random secret number between 1 and 10.

  • It prompts the user to guess the number and continues the loop until the correct number is guessed.

  • It provides feedback for each incorrect guess and congratulates the user upon guessing correctly.

Output:

Guess the secret number (between 1 and 10): 4
Try again!
Guess the secret number (between 1 and 10): 7
Congratulations! You guessed the secret number.

 

3. Fibonacci Sequence

# Generate the Fibonacci sequence up to a given number using a while loop
limit = int(input("Enter the limit for the Fibonacci sequence: "))
a, b = 0, 1
while a <= limit:
    print(a, end=" ")
    a, b = b, a + b

Explanation:

  • This program generates the Fibonacci sequence up to a given limit using a while loop.

  • It initializes variables a and b to 0 and 1, respectively.

  • The loop prints the current value of a and updates a and b for the next Fibonacci numbers until a exceeds the input limit.

Output:

Enter the limit for the Fibonacci sequence: 20
0 1 1 2 3 5 8 13

While Loop with else

Boolean values in the while loop are used to create an infinite loop that ends or can be exited only based on a certain condition mentioned with the loop. The while loop supports the else statement in Python, which is optional. 

Here’s an explanation of how while else works:

  • We write the else statement after the while statement, and it is executed when the expression becomes False. 

  • Once the while statement is executed normally, the else statement is executed.

  • If a break statement is executed within the while loop and execution terminates, the else block is skipped, and control goes directly to the statement immediately after the while-else. 

  • The statement within the else block is skilled when the while loop stops abruptly. In a normal scenario, when the expression returns False, the else statement is executed.

  • The statement after the while-else block is executed, regardless of whether the expression returning False or the while loop breaks abruptly. 

Example:

count = 0
while count < 5:
    print(f"Count is {count}")
    count += 1
else:
    print("Loop finished!")
print("After the loop.")

In this example:

  • The while loop runs while count is less than 5.

  • The code block inside the loop prints the current value of count and increments it.

  • When the loop condition becomes false (count >= 5), the code inside the else block is executed.

  • Finally, the program continues with the code outside the loop.

The output will be:

Count is 0
Count is 1
Count is 2
Count is 3
Count is 4
Loop finished!
After the loop.

Single Statement While Loop in Python

A while loop in Python generally spans multiple lines, with an indented block of code under it. However, if the block inside the loop is a single statement, you can write the entire while loop in a single line. This is known as a "single-line while loop" or "single statement while loop." 

The syntax for a single-line while loop is as follows:

while condition: statement
Here's an example:
count = 0
while count < 5: print(f"Count is {count}"); count += 1

In this example:

  • The while loop condition is count < 5.

  • The single statement inside the loop is print(f"Count is {count}"); count += 1.

However, keep in mind that while single-line while loops can be convenient for very short and simple statements, they might reduce code readability if overused or for more complex logic. It's generally recommended to use the multi-line form of while loops for better code clarity and maintainability.

Infinite While Loop in Python

An infinite while loop is a loop that continues to execute indefinitely because the loop condition always evaluates to true. 

In other words, there is no condition that would cause the loop to exit naturally. Infinite loops can be problematic because they can lead to programs that never finish executing, causing the application to become unresponsive.

Example of infinite while loop:

while True:
    print("This is an infinite loop!")

In this example, True is a constant boolean value, so the loop condition is always true, and the loop will never exit.

Cautionary Notes:

1. Avoiding Infinite Loops:

  • Infinite loops are usually unintentional and are considered bugs.

  • It's crucial to design loop conditions carefully to ensure that they will eventually become false, allowing the loop to exit.

2. Program Unresponsiveness:

  • Infinite loops can lead to a program becoming unresponsive because it never progresses beyond the loop.

  • Users may experience freezing or crashing of the application.

How to Break Out of an Infinite Loop?

If you find yourself stuck in an infinite loop during development or execution, you can take the following actions to break out of it:

  • Keyboard Interrupt (Ctrl+C):

If you're running the script from the command line, you can often break out of an infinite loop by pressing Ctrl+C. This sends a keyboard interrupt signal to the program, causing it to terminate.

  • Kill the Program:

If you're running the script in an integrated development environment (IDE) or another environment, you might need to manually stop or kill the program's execution.

  • Fix the Loop Condition:

Go back to the code and analyze the loop condition.

Ensure that there's a mechanism within the loop that will eventually make the condition false.

While Loop Control Statements in Python

while loops in Python can be controlled using several statements that help manage the flow of the loop:

1. break Statement:

The break statement in Python is used to exit a loop prematurely, regardless of whether the loop condition is still true. It is often used with an if statement to check a certain condition and exit the loop accordingly.

count = 0
while True:
    print(f"Count is {count}")
    count += 1
    if count == 5:
        break

In this example, the break statement is used to exit the loop when count reaches 5.

2. continue Statement:

The continue statement in Python is used to skip the rest of the code inside the loop for the current iteration and move to the next iteration.

count = 0
while count < 5:
    count += 1
    if count == 3:
        continue
    print(f"Count is {count}")

In this example, the continue statement skips the printing step when count is equal to 3, and the loop proceeds to the next iteration.

3. else Clause with While Loop:

You can use the else clause with a while loop. The code in the else block is executed when the loop condition becomes false.

count = 0
while count < 5:
    print(f"Count is {count}")
    count += 1
else:
    print("Loop finished!")

Here, the else block is executed after the loop finishes naturally (when count is no longer less than 5).

4. pass Statement:

The pass statement is a null operation. It is used as a placeholder where syntactically some code is required but no action is desired.

count = 0
while count < 5:
    if count == 2:
        pass  # Placeholder for future code
    else:
        print(f"Count is {count}")
    count += 1

In this example, the pass statement is a placeholder for future code when count is equal to 2.

5. while-else Construction:

Similar to the else clause with an if statement, a while loop can also have an else clause. The code in the else block is executed when the loop condition becomes false.

count = 0
while count < 5:
    print(f"Count is {count}")
    count += 1
else:
    print("Loop finished!")

Here, the else block is executed after the loop finishes naturally (when count is no longer less than 5).

do while loop in Python

Python does not have a built-in do-while loop like some other programming languages. However, you can achieve similar functionality using a while loop with an initial condition that is guaranteed to be true for the first iteration. Then, you use a condition check within the loop to decide whether to continue or break out.

Here's an example of a "do-while" loop in Python:

while True:
    # Code to be executed at least once
    user_input = input("Do you want to continue? (yes/no): ")
    if user_input.lower() != 'yes':
        break

In this example:

  • The loop condition is True, ensuring that the loop will execute at least once.

  • Inside the loop, there is code that you want to execute.

  • After the code execution, it prompts the user to decide whether to continue.

  • If the user enters anything other than 'yes', the loop will break, and the program will continue after the loop.

This structure mimics the behavior of a do-while loop, where the loop body is guaranteed to run at least once.

It's important to note that Python's design philosophy typically favors simplicity and readability, and using a while loop with a break condition is considered more idiomatic than introducing a separate do-while construct.

Nested while in Python

Nested while loops in Python refer to the situation where one while loop is placed inside another. This is useful when you need to repeatedly execute a block of code, and within that block, there is another task that needs to be repeated. The inner loop will execute multiple times for each iteration of the outer loop.

Here's a simple example of nested while loops:

outer_count = 1
while outer_count <= 3:
    inner_count = 1
    while inner_count <= 3:
        print(f"Outer Count: {outer_count}, Inner Count: {inner_count}")
        inner_count += 1
    outer_count += 1

In this example:

  • The outer loop (while outer_count <= 3) runs three times.

  • For each iteration of the outer loop, the inner loop (while inner_count <= 3) runs three times.

  • Inside the inner loop, a statement is printed, showing both the outer and inner counts.

The output will be:

Outer Count: 1, Inner Count: 1
Outer Count: 1, Inner Count: 2
Outer Count: 1, Inner Count: 3
Outer Count: 2, Inner Count: 1
Outer Count: 2, Inner Count: 2
Outer Count: 2, Inner Count: 3
Outer Count: 3, Inner Count: 1
Outer Count: 3, Inner Count: 2
Outer Count: 3, Inner Count: 3

Each iteration of the outer loop triggers three iterations of the inner loop.

You can nest as many while loops as needed, but keep in mind that excessive nesting can make the code harder to read and understand. In such cases, it might be worth considering other control structures or refactoring your code for better clarity.

while true in Python

The expression while True in Python creates an infinite loop. The while True construct is commonly used when you want a loop to continue running indefinitely until a certain condition is met or until the loop is explicitly broken with a break statement.

Here's a simple example:

while True:
    user_input = input("Enter 'exit' to end the loop: ")
    if user_input.lower() == 'exit':
        break
print("Loop ended.")

In this example:

  • The while True creates an infinite loop.

  • Inside the loop, it prompts the user for input.

  • If the user enters 'exit', the loop is broken using the break statement.

Remember that using an infinite loop should be done carefully, and there should be a way to exit the loop. In this case, the user has the option to exit the loop by entering 'exit'.

If you're using an infinite loop without a clear exit strategy, it can lead to your program becoming unresponsive, and you might need to forcibly terminate it. Always ensure there's a condition or mechanism within the loop to break out of it when needed.

Difference Between while and for loop in Python

Here's a tabular comparison showing the difference between while and for loops in Python:

 

Feature

while Loop

for Loop

Syntax:

while condition:

for variable in iterable:

Initialization:

Requires initialization of loop control variable

Automatically initializes loop control variable

Loop Control:

Explicitly managed within the loop

Implicitly managed by iterating over an iterable

Use Case:

Used when the number of iterations is not known

Used when iterating over a sequence or iterable

Example:

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

python for item in iterable: print(item)

Infinite Loop:

More prone to unintentional infinite loops

Rarely causes unintentional infinite loops

Exiting the Loop:

Requires a condition to be false or break statement

Automatically exits when all items in the iterable have been processed or break statement is used

Range Iteration:

Not naturally suited for iterating over ranges

Suited for iterating over ranges using range()

Common Use Cases:

- When a specific condition needs to be met

- Iterating over elements in a list, tuple, string, etc.
- Enumerating elements with their indices using enumerate()
- Iterating over a range of numbers with range()

Learn Next:

More Tutorials:-

Compilers to practice online:-

Did you find this article helpful?