Python While Loop with Examples

The Python While Loop is a construct that allows for the repeated execution of a specific block of code as long as a specified condition evaluates to True. This feature is particularly beneficial when the exact number of iterations required is not known in advance. To implement a While loop, one can use the keyword while followed by a colon (:).

In Python, a while loop can consist of either a single statement or several statements, provided they are correctly indented. The while construct allows the program to execute repeatedly as long as the specified condition remains True; it halts immediately when the condition evaluates to False. Should the condition persistently remain True, the program will enter an infinite loop, continuing to run indefinitely unless interrupted forcefully.

Syntax of the while Loop

Let’s explore the fundamental syntax of the While loop in Python:

Example

while condition:

  # The Code to be executed as long as the condition remains true

Syntax Explanation:

In Python, the While loop assesses a defined conditional expression. The execution of the program occurs as long as the specified condition evaluates to True. After the completion of the entire block of code, the condition is re-evaluated, and this cycle continues until the conditional expression yields False.

Simple Python while Loop Example:

Let's examine a straightforward illustration of a Python while loop.

Example

# initializing a counter variable

counter = 0

# using the while loop to iterate the counter up to 5

while counter < 5:

  # printing the counter value and some statement

  print(counter, "Hello")

  # incrementing the counter value

  counter += 1

Output:

Output

0 Hello

1 Hello

2 Hello

3 Hello

4 Hello

Explanation:

In the preceding illustration, we have set up a variable named counter with an initial value of 0. We subsequently enter a while loop that continues to run the code block as long as the counter is less than 5. Inside this loop, we print the present value of the counter, followed by the word "Hello." After each cycle, the counter is increased by 1. When the counter hits 5, the condition counter < 5 evaluates to False, resulting in the termination of the loop.

Flowchart of the While Loop in Python

The flowchart below illustrates the operation of a 'while' loop:

Step 1: The program starts.

Step 2: The while loop evaluates the given conditional expression to determine if it is True or False.

  • If the result is True, the execution continues into the loop's body.
  • Conversely, if the result is False, the loop terminates and the program advances to the subsequent section.

Step 3: When the condition evaluates to True, proceed to execute the statements contained within the loop.

Step 4: Adjust the variable that governs the loop (for instance, increasing a counter).

Step 5: Return to Step 2 and reassess the condition.

Step 6: When the condition evaluates to False, the loop terminates, and the program proceeds with the subsequent operations.

Note: Indentation is required to define the code block inside a while loop. Improper or Incorrect indentation can cause syntax errors or logical errors (like infinite loops). Any non-zero number in Python is interpreted as Boolean True. False is interpreted as None and 0.

Examples of Python while Loop

Let us now examine a few fundamental illustrations of the while loop in Python.

Finding Numbers Divisible by 5 or 7 Using a while Loop

In this section, we present an example that illustrates the method for identifying numbers ranging from 1 to 50 that are divisible by either 5 or 7 by utilizing a while loop in Python.

Example:

Example

# initializing a iterable as 1

i = 1

# using the while loop to find numbers between 1 to 50 that are divisible by 5 or 7

while i < 50:

  if i % 5 == 0 or i % 7 == 0:

    print(i, end=' ')

  i += 1

Output:

Output

5 7 10 14 15 20 21 25 28 30 35 40 42 45 49

Explanation:

In the preceding illustration, we are identifying numbers that can be evenly divided by both 5 and 7, continuing this process until the numbers within the loop are less than 50. We initiate our count from the starting number 1 and proceed to increase it incrementally. The loop will cease its execution immediately upon reaching the number 50.

Finding the Sum of Squares Using a While Loop

In the subsequent illustration, we will demonstrate the process of computing the sum of the squares of the initial 15 natural numbers by utilizing a while loop in Python.

Example

Example

# initializing variables

sum = 0   # storing the sum of squares

counter = 1     # iterable

# using the while loop

while counter <= 15:

  sum = counter**2 + sum  # calculating the sum of the squares

  counter += 1    # incrementing the counter value

# printing the result

print("The sum of squares is", sum)

Output:

Output

The sum of squares is 1240

Explanation:

The preceding code computes the total of squares for the integers ranging from 1 to 15 by utilizing a while loop. Initially, we set the variable Sum to 0 and the counter to 1. The while loop persists as long as the counter is less than or equal to 15. The execution of the program concludes when the counter increments to 16, at which point the condition is no longer satisfied.

Checking Prime Number using While Loop

In the example below, we will demonstrate how to determine if a specified number is Prime by utilizing a while loop in Python.

Example

Example

# creating a list of numbers

num = [34, 12, 54, 23, 75, 34, 11]

# defining a function to check prime number

def prime-number(number):

    c = 0

    i = 2

    while i <= number / 2:

        if number % i == 0:

            c = 1

            break

        i = i + 1

    if c == 0:

        print(f"{number} is a PRIME number")

    else:

        print(f"{number} is not a PRIME number")

for i in num:

    prime-number(i)

Output:

Output

34 is not a PRIME number

12 is not a PRIME number

54 is not a PRIME number

23 is a PRIME number

75 is not a PRIME number

34 is not a PRIME number

11 is a PRIME number

Explanation:

In the preceding illustration, we are determining if the integers within the list are Prime numbers. We set the variable c to 0 and initialized I to 2. By utilizing the conditions specified within the while loop along with the break statement, we aim to identify the prime numbers.

Checking Armstrong Number Using while Loop

In the subsequent example, we will demonstrate the process of verifying whether a specified integer qualifies as an Armstrong number by utilizing a while loop in Python.

An Armstrong number is defined as a number that equals the sum of its digits each raised to the power corresponding to the total count of digits in that number. For instance, consider the number 153: it can be expressed as 1^3 + 5^3 + 3^3, which simplifies to 1 + 125 + 27, ultimately resulting in 153.

Example

Example

n = int(input())

n1=str(n)

l=len(n1)

temp=n

s=0

while n!=0:

    r=n%10

    s=s+(r**1)

    n=n//10

if s==temp:

    print("It is an Armstrong number")

Else:

    print("It is not an Armstrong number ")

Output:

Output

It is an Armstrong number

Explanation:

The code provided evaluates whether a specified number qualifies as an Armstrong number. To begin, we prompt the user for input and assign this value to the variable n. Subsequently, we convert the number into a string format to determine its length. The variable temp is utilized to retain the original value inputted by the user. We also initialize a variable s to 0, which will accumulate the sum of the digits raised to their respective powers.

The final digit of the number is determined by employing the modulus operator, and this value is saved in r through the use of a while loop. Once the loop concludes, the program evaluates whether the computed sum s matches the initial number temp. If they are the same, it outputs "It is an Armstrong number"; if not, it displays "It is not an Armstrong number."

Creating Table of Multiplication Using the While Loop

In this demonstration, we will illustrate the process of generating a multiplication table for a specified number by utilizing the while loop in Python.

Example

Example

num = 21

counter = 1

# We will use a while loop to iterate 10 times for the multiplication table

print("The Multiplication Table of: ", num)

while counter <= 10: # specifying the condition

    ans = num * counter

    print (num, 'x', counter, '=', ans)

    counter += 1 # expression to increment the counter

Output:

Output

The Multiplication Table of: 21

21 x 1 = 21

21 x 2 = 42

21 x 3 = 63

21 x 4 = 84

21 x 5 = 105

21 x 6 = 126

21 x 7 = 147

21 x 8 = 168

21 x 9 = 189

21 x 10 = 210

Explanation:

In the previous illustration, we are generating a multiplication table for a specified number, which is 21. We set the initial value of the counter to 1 and increased it as the while loop executes. This while loop will continue to operate as long as the counter remains less than or equal to 10. The numbers that are incremented up to 10 are then multiplied by 21, resulting in the multiplication table.

Infinite while Loop in Python

In Python, an infinite while loop occurs when the condition perpetually evaluates to true. This situation leads to the loop executing indefinitely until the system's memory is exhausted.

Consider the following illustration in which the while loop executes indefinitely:

Example

age = 28

# the test condition is always True

while age > 19:

    print('Infinite Loop')

Output:

Output

Infinite Loop

Infinite Loop

Infinite Loop

Infinite Loop

Infinite Loop

Infinite Loop

Infinite Loop

...... and it continues

Explanation:

In the preceding example, we established a condition within the while loop that maintains the program in a continuous loop as long as the age is greater than 19, with the age set to 28. Since 28 is consistently greater than 19, this condition will always evaluate to True, resulting in an infinite loop. We can terminate this infinite loop either by forcibly halting the program or when the system's memory reaches capacity.

Loop Control Statements with Python while Loop

Control statements for loops modify the flow of execution from its standard sequence. Upon exiting a scope, all automatic objects that were instantiated within that scope are eliminated. Python provides support for the following control statements.

We will now explore different loop control statements utilized within Python's while loop.

1. Break Statement

The break statement instantly exits the while loop, irrespective of the loop's condition.

Example

Example

i = 0

while i < 8:

    if i == 4:

        print("Breaking the loop at", i)

        break  # Exits the loop when i is 4

    print("Counter is:", i)

    i += 1

Output:

Output

Counter is: 0

Counter is: 1

Counter is: 2

Counter is: 3

Breaking the loop at 4

Explanation:

In the example provided, the loop terminates immediately when the counter hits 4, despite the initial condition being set to counter < 8.

2. continue Statement

The continue statement allows the loop to bypass the current iteration and proceed directly to the next one, omitting the execution of any subsequent code within the loop.

Example

Example

i = 0

while i < 8:

    i += 1

    if i == 4:

        continue  # Skip iteration when i is 4

    print("Counter is:", i)

Output:

Output

Counter is: 1

Counter is: 2

Counter is: 3

Counter is: 5

Counter is: 6

Counter is: 7

Counter is: 8

Explanation:

In the aforementioned illustration, the loop omits the print statement when the counter reaches the value of 4; nevertheless, it proceeds to execute the remaining instructions afterward.

3. Pass Statement

The pass Statement functions as a no-operation command or a placeholder. It is utilized in scenarios where a statement is syntactically necessary, indicating that while the statement will appear in the code, it will be disregarded during execution, resulting in no output.

Example

Example

i = 0

while i < 8:

    if i == 4:

        pass  # Placeholder for future logic

    print("Counter is:", i)

    i += 1

Output:

Output

Counter is: 0

Counter is: 1

Counter is: 2

Counter is: 3

Counter is: 4

Counter is: 5

Counter is: 6

Counter is: 7

Explanation:

In this illustration, the pass statement acts as a placeholder, preventing Python from generating an error during the coding process. Given that this function lacks any content and yields no output as a result of the pass statement, invoking this function will not produce any results.

4. Else with a while Loop

The else clause runs once the loop concludes successfully (meaning it exits without encountering a break statement).

Example

Example

#initializing value of counter to 0

counter = 0

#using the while loop to iterate the counter up to 7

while counter <= 7:

    print("Counter is:", counter)

    counter += 1

#using the else

else:

    print("Loop completed successfully!")

Output:

Output

Counter is: 0

Counter is: 1

Counter is: 2

Counter is: 3

Counter is: 4

Counter is: 5

Counter is: 6

Counter is: 7

Loop completed successfully!

5. Break statement with Else-while Loop

The Break statement used in conjunction with the else-while loop causes the program to end at the precise moment it is invoked. In this scenario, the loop ceases immediately, and the code within the else block is bypassed.

Example

Example

i = 0

while i < 8:

    print("Counter is:", i)

    if i == 4:

        break  # Loop exits early

    i += 1

else:

    print("Loop completed successfully!")  # This won't execute

Output:

Output

Counter is: 0

Counter is: 1

Counter is: 2

Counter is: 3

Counter is: 4

Explanation:

In this instance, the else block is not activated because the break statement terminates the loop prematurely.

Advantages of the while Loop in Python

Python's while loop offers numerous benefits. Here are some of the key advantages:

1. Easily Executable

A while loop is an excellent choice for scenarios where the total number of iterations cannot be predetermined, as it continues to execute as long as the specified condition evaluates to True.

2. An effective loop for User Input Programs

It can be beneficial when the duration of the loop is determined by user input.

3. Prevents Code Duplication

A while loop efficiently processes multiple iterations in rapid succession, eliminating the necessity for redundant code and enhancing both the clarity and maintainability of the code.

4. Allow Infinite Loops

Endless loops utilizing True can be advantageous in scenarios such as servers, real-time observation, and background operations when appropriately controlled.

5. Conditional Logic

The loop can be easily integrated with logical conditions to manage the flow of the program, as it functions based on a condition that changes dynamically.

Disadvantages of While Loop in Python

Python's while loop comes with a number of drawbacks. Among them are the following:

1. Risk of Infinite Loops

The application may enter an infinite loop, which could lead to a system freeze or excessive CPU usage, if the condition for exiting the loop never evaluates to False.

2. Condition Handling Must Be Done by Hand

A while loop requires the programmer to handle conditions manually, which introduces the potential for errors to occur.

3. Less Readable

Loops may sometimes present challenges in terms of readability and debugging compared to other loops, especially when they incorporate intricate conditions.

4. Overhead in Performance

In contrast to more organized loops, improperly optimized loops can lead to performance degradation by introducing unnecessary iterations that could hinder efficiency.

If not executed with caution, the implementation of break and continue statements within while loops may render the code harder to interpret and troubleshoot.

Conclusion

To summarize, the While Loop in Python is designed to execute a specific block of code repeatedly, provided that a specified condition evaluates to True. This construct is particularly advantageous when the total number of iterations cannot be determined in advance. The implementation of the While loop is achieved by employing the keyword while followed by a colon (:).

Python While Loop FAQs

1. What is a while loop in Python?

The Python While Loop is designed to continually run a segment of code as long as a specified condition evaluates to True. This feature proves beneficial when the total number of iterations cannot be predetermined. To implement a While loop, one can utilize the while keyword followed by a colon (:).

2. What is the syntax of a while loop?

The basic syntax of the While loop in Python:

Syntax:

Example

while condition:

# The Code to be executed as long as the condition remains true

3. How does a while loop work?

The while loop evaluates the given conditional expression to determine if it is True or False.

  • If the condition is True, the execution continues into the loop's body.
  • Conversely, if the condition is False, the loop is terminated, and the program advances to the subsequent section.
  • 4. Give a simple example of a while loop in Python.

Let’s examine a straightforward illustration of a while loop in Python:

Example:

Example

#initializing the counter to 1

count = 1

#using while loop

while count <= 5:

    print(count)

    count += 1

Output:

Output

1

2

3

4

5

5. What happens if the condition never becomes False?

When the condition in a while loop continuously evaluates to True, it results in an infinite loop.

Let's see a small example of an Infinite loop:

Example

age = 28

# the test condition is always True

while age > 19:

    print('Infinite Loop')

Output:

Output

Infinite Loop

Infinite Loop

Infinite Loop

Infinite Loop

Infinite Loop

……..and it continues

Input Required

This code uses input(). Please provide values below: