Tutorial

While Loop in Python

6 min read

A while loop in Python is a control flow statement that allows a block of code to be executed repeatedly as long as a given condition is true. It is used when the number of iterations is not known in advance.

The loop continues until the condition becomes false. While loops are commonly used in Python for tasks such as reading data from a file, processing data, or waiting for user input.

It’s also important to note that you can use the break and continue statements inside a while loop to control its execution.

Syntax of a While Loop in Python

The syntax of a while loop in Python is as follows:

while condition:
    # code to be executed

Here, the condition is a boolean expression that is evaluated before each iteration of the loop. If the condition is true, the code block inside the loop is executed. Once the code inside the loop has been executed, the condition is evaluated again.

The process repeats until the condition becomes false.

It is important to make sure that the condition will eventually become false to avoid an infinite loop.

Types of While Loop in Python

There are two types of while loops in Python:

  • while loop: This is the standard while loop that continues executing the code block as long as the specified condition is true.

Example of Python while loop-

i = 1
while i <= 10:
    print(i)
    i += 1

Here, the loop continues as long as the value of the variable i is less than or equal to 10. The variable i is incremented by 1 after each iteration of the loop, so the loop will eventually stop when the value of i becomes 11.

  • do-while loop: This is a variation of the while loop in which the block of code will be executed at least once, irrespective of the value of the condition. The syntax for a do-while loop is not natively supported in Python, but it can be emulated using a combination of a while loop and a flag variable.

Example of Python do-while loop-

user_input = ""
while user_input != "exit":
    user_input = input("Enter something (exit to quit): ")
    print("You entered: ", user_input)

Here, the user input is captured in the first line. After that, the loop starts executing. It will continue to execute until the user enters ‘exit‘ as input and the loop will break.

Infinite While Loop in Python

An infinite while loop in Python is a loop that continues to execute indefinitely because the condition for the loop is always true. An infinite loop can be caused by a variety of reasons like a logical error in the condition, a missing increment or update statement, or an intentional design choice.

Example of Pyhton infinite while loop:

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

Here, the condition for the loop is the constant value True, which will always be evaluated as true, so the loop will continue to execute indefinitely.

It’s important to be aware of the possibility of infinite loops when using while loops and take steps to ensure that the loop will eventually exit.

This can be done by including a counter variable that is incremented or decremented with each iteration of the loop and a condition that compares the counter variable to a specific value. We can also do it by adding a break statement inside the loop to exit the loop when a certain condition is met.

Note: Infinite loops can be useful in certain situations, such as in a program that waits for user input or monitors a system for changes. It’s also important to have an exit condition for the loop, for example by adding a keyboard interrupt.

While Loop in Python with Else statement

In Python, a while loop can be used with an else statement. The else block is executed after the loop completes its execution, but only if the loop was not terminated by a break statement.

Example of while loop in Python with an else statement-

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
search_num = 11
i = 0

while i < len(numbers):
    if numbers[i] == search_num:
        print(search_num, " found at index ", i)
        break
    i += 1
else:
    print(search_num, " not found in the list.")

The output for this code will be:
11 not found in the list.

Here, the loop iterates over the list of numbers and searches for the number 11. If the number is found, the loop breaks, and the message “11 found at index x” is printed, where x is the index of the number in the list. If the number is not found, the loop completes its execution and the else block is executed, printing the message “11 not found in the list.

Note: The else block in a while loop can be useful for situations where we want to perform some action or provide feedback to the user if the loop completes its execution without being interrupted by a break statement.

While loop true false Python

In Python, a while loop will continue to execute as long as the specified condition is True. Once the condition becomes False, the loop will exit.

Python example:


x = 0
while x < 5:
    print(x)
    x += 1

This loop will print the numbers 0 through 4, because the condition x < 5 is True for each iteration of the loop. Once x becomes 5, the condition x < 5 is False, so the loop exits.

Breaking a while loop Python or exit while loop Python

In Python to exit a while loop, you can use the break statement. The break statement immediately exits the loop, regardless of the current value of the condition.

For example, the following code will print the numbers 0 through 4, and then exit the loop:


x = 0
while True:
    print(x)
    x += 1
    if x >= 5:
        break

In this example, the loop is infinite, because the condition is always True. But the break statement will cause the loop to exit when x becomes greater than or equal to 5.

Another example is to use a flag variable, which can be set to True or False to control the loop.


flag = True
while flag:
    x = int(input("Enter a number: "))
    if x == 0:
        flag = False
    else:
        print(x)

In this example, the flag variable is set to True at the beginning of the loop, and it will continue to execute as long as the flag variable is True. When the user enters 0, the flag is set to False, and the loop will exit.

It’s important to note that using a break in an infinite loop is a good practice to exit the loop, but it should be used in cases where it makes sense and the code is readable.

Conclusion

In conclusion, while loops are a fundamental control flow statement in Python.

Python while loops are widely used and can be used in different situations. They also have variations like do-while which can be emulated.

In addition, while loop in Python is also very effective and flexible. They can be used in combination with other statements like break, continue, and else to make the code more readable and efficient.

Continue learning and check the tutorial for loops in Python. You may also like online Python tutoring.