Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.
Python While Loop Statements (Indefinite Iteration)
Table of Contents
Loops are an indispensable part of learning Python or for that matter, any programming language. They are used when there is a requirement for repeating a specific block of code or set of statements more than once.
There are three types of loops supported by the Python programming language for meeting a different set of requirements, namely for loop, nested loop, and while loop. Typically, the while loop is used in situations when the total number of iterations required is unknown beforehand.
What is Python While Loop?
A while loop clause repetitively executes a set of statements until the given condition turns out to be false. The general syntax for a Python while loop statement is:
The statement body can either be a single statement or a set or block of statements, while the condition may or may not be an expression.
In the Python while loop, the test expression is evaluated at the start. The program execution enters the body of the while loop if and only if the test_expression or condition evaluates to be true. The body of the while loop is evaluated at every iteration.
Evaluating the body of the while loop is continued until the test_expression/condition evaluates to false. Now, the program control is passed to the line immediately succeeding the while loop. In Python, indentation is used for determining the body of the while loop.
The Python programming language uses indentation as a method of grouping statements. As such, all the statements indented by an equal number of character spaces after a programming construct are considered as a single block of code.
The while loop body starts with an indentation in the Python programming language and the very first un-indented line marks the end of the while loop. While any non-zero value is treated as true, None and 0 are interpreted as false by Python.
An important point to note is that it is possible that the while loop might not run even for a single time. This will happen if the condition evaluates to be false during the loop’s very first iteration.
A Simple Python While Loop Example
loop_value = 0 while (loop_value < 9): print ('The loop value is:', loop_value) loop_value = loop_value + 1 print ('Demonstration of a simple Python while loop program is complete!')
The loop value is: 0 The loop value is: 1 The loop value is: 2 The loop value is: 3 The loop value is: 4 The loop value is: 5 The loop value is: 6 The loop value is: 7 The loop value is: 8
Demonstration of a simple Python while loop program is complete!
In the above code example, the while loop body has the condition that the loop_value variable must be less than 9. The body of the while loop contains a print statement that prints the present value of the loop_value variable and then increments it by 1 using the next statement.
The while loop will continue execution until the loop_value reaches 9, upon which the last print statement will be executed.
Recommend Python Course
Complete Python Bootcamp From Zero to Hero in Python
The Infinite Loop
Any loop becomes infinite if the condition stated never turns out to be false. Such a loop is therefore called an infinite loop. Hence, it is advised to pay special attention while using loops to prevent the occurrence of an infinite loop.
An area of application of an infinite loop is in client/server programming. Here, the server is required to run continuously to allow a wide array of client programs to communicate with it, whenever required. Following is a basic code example of an infinite loop:
var = 1 while var == 1 : num = input("Enter some number: ") print ("You entered: ", num) print ("Goodbye!") # the program execution never reaches this point
Enter some number: 22 You entered: 22 Enter some number: 24 You entered: 24 Enter some number: 46 You entered: 46 Enter a number:Traceback (most recent call last): File “main.py”, line 3, in num = input(“Enter some number: ”) KeyboardInterrupt
The aforementioned code example demonstrates an infinite loop that will never exit automatically. You need to hit the Ctrl + C to manually exit the program. The last 4 lines of the output will be displayed when you manually quit the program.
Using the Else Statement With the While Loop
Python provides support for using a loop statement with an else statement. When the else statement is used along with a while loop, then the else statement is executed when the while loop condition becomes false.
Following code demonstrates a simple example of using the while loop along with an else statement:
value = 0 while (value < 8): print (value, " is smaller than 8") value = value + 1 else: # executes once the condition in the while loop turns false print (value, " is not smaller than 8")
0 is smaller than 8 1 is smaller than 8 2 is smaller than 8 3 is smaller than 8 4 is smaller than 8 5 is smaller than 8 6 is smaller than 8 7 is smaller than 8 8 is not smaller than 8
The abovementioned code example demonstrates combining an else statement with a while loop that keeps on printing a number until it becomes equal to 8.
The One-Liner While Clause
Yes, it is possible to write a while loop with a single statement in Python. Such a while loop is also known as a one-liner while clause. Instead of adding the sole statement to the body of the while loop, the same can be placed adjacent to the ‘while’ header.
while test_expression/condition: statement
Following is a code example to demonstrate using the one-liner while clause in the Python programming language:
a = 0 while (a==0): print ("It is 0!")
It is 0! It is 0! It is 0! It is 0! It is 0! It is 0! It is 0! It is 0! It is 0! It is 0! It is 0! Traceback (most recent call last): File “main.py”, line 2, in While (a==0): print (It is 0!”) KeyboardInterrupt
The aforementioned example will produce an infinite loop. Hence, you need to press Ctrl + C to exit the program manually!
That completes everything that you must know about the Python while loop. It is an efficient way of executing a statement(s) that requires more than a single-time execution. You are always free to experiment with the while loop clause to better understand the working.
If you have any important information regarding the Python while loop that you would like to share with us, then you can do so via the dedicated comments section below! Also, you can ask your queries related to the Python while loop there. We would get back to you ASAP!
Recently started out with Python? Then check out this gentle introduction to Python to better know the high-level, interpreted, general-purpose programming language!
People are also reading:
Leave a comment
How do you end a Python program in the middle?
Does Break stop all loops?
What does != Mean in Python?
How do you do a while loop in Python 3?
How do you end a while loop?
Where do we use while loop?
What is for loop and while loop in Python?
How do I write a while loop?
your indentation is way off on Simple Python While Loop Example