Python while Loop
Introduction
Before we begin talking about Python while loop, let's briefly understand – What is Loop?
Loops are an essential element in programming languages. When you need to repeatedly run a particular block of code until a predetermined condition is met, loops come in handy.
A for
loop is a control structure that allows you to iterate over a sequence of elements such as a list, tuple, string, or range of numbers. It executes a block of code repeatedly for each element in the sequence.
The for
and while
loops are the two fundamental loop building blocks in Python.
The fundamentals of Python's while
loops are covered in this tutorial. You will learn how to use the else
clause, break
, and continue
statements as well. We will also address a few FAQs on Python while loop.
Python while
Loop
As long as the given condition evaluates to true
, the while
loop runs its statements an indefinite number of times.
The while
loop in Python looks like this:
while EXPRESSION:
STATEMENT(S)
The while
statement begins with the while
keyword and is followed by the conditional expression.
Before the statements are executed, the EXPRESSION
is evaluated. The STATEMENT(S)
is executed if the condition is true
. Otherwise, if the condition evaluates to false
, the loop is ended and the next statement takes over program control.
The first line of the STATEMENT(S)
block is indented, while the last line is the first unintended line. Most individuals either prefer to indent 4-spaces or 2-spaces. The Python Code Style Guide suggests using 4-spaces per indentation level and avoiding combining the usage of tabs and spaces for indentation.
Consider the following code, which increments and prints the current value of the variable i
if it is less than five:
i=0
while i < 5:
i += 1
print('number:', i)
As long as i
is less than or equal to five, the loop iterates. The output will be as follows:
Output
number: 1
number: 2
number: 3
number: 4
number: 5
Standard comparison operations are supported by Python.
a == b
- True if variablesa
andb
are equal.a != b
- True if variablesa
andb
are not equal.a > b
- True if variablea
is greater than variableb
.a >= b
- True if variablea
is equal to or greater than variableb
.a < b
- True if variablea
is less than variableb
.a <= b
- True if variablea
is equal to or less than variableb
.
Use the logical not
operator to negate the conditional expression:
i=0
while not i >= 5:
i += 1
print('number:', i)
break
and continue
Statements
You can regulate the while
loop's execution using the break
and continue
statements.
The break statement ends the current loop and transfers control to the statement that comes after the loop that was terminated. Using break to end the loop when a predetermined condition is fulfilled is the most common case.
In the example that follows, the loop is terminated when the item being iterated equals 2.
i=0
while i < 5:
i += 1
if i == 2:
break
print('number:', i)
Output
Number: 1
A loop's current iteration is terminated by the continue
statement, which also transfers program control to the next iteration of the loop.
In the example below, the continue
statement will force execution to return to the start of the loop and proceed with the next iteration once the currently iterated item equals 2
.
i=0
while i < 5:
i += 1
if i == 2:
continue
print('number:', i)
Output
number: 1
number: 3
number: 4
number: 5
else
Clause
Python features an optional else
clause for the while
loop, unlike other languages:
while EXPRESSION:
STATEMENT(S)
else:
STATEMENT(S)
When the EXPRESSION
evaluates to false
, the statements inside the else
clause are executed. The loop will not be executed if an exception is encountered or if a break
statement terminates it.
Here's an example:
i=0
while i < 5:
i += 1
print('number:', i)
else:
print('Loop completed.')
Output
number: 1
number: 2
number: 3
number: 4
number: 5
Loop completed.
Let us check out what happens when you break
out of the loop:
i=0
while i < 5:
i += 1
if i == 2:
break
print('number:', i)
else:
print('Loop completed.')
Because the expression did not evaluate to false
, the statement inside the else
clause is not executed:
Output
Number: 1
The else
clause in a while
loop is rarely used. One such situation is when you expect to break from a loop and the loop continues to run until the condition evaluates to false
, you can execute some statement or function.
Infinite while
Loop
An endless loop is a loop that keeps repeating indefinitely and does not end until the program does. If the condition constantly evaluates to true, you get an infinite loop.
Usually, programs are made to wait for an external event to happen by using infinite loops. The most common technique to build an infinite loop in Python is with while True:
You can also use any other expression that always returns true
in place of True
.
Here is an example of an endless while
loop that will keep asking you to type “Yes”:
while True:
i = input('Please enter \'Yes\': ')
if i.strip() == 'Yes':
break
The while
loop will continue to run until you enter “Yes”:
Output
Please enter 'Yes': 3
Please enter 'Yes': l
Please enter 'Yes': lin
Please enter 'Yes': No
Please enter 'Yes': Yes
Pressing CTRL+C
is another way to break an infinite loop.
Use the break
statement to end the loop at some point when creating infinite loops.
FAQs on Python while loop
How does a "while loop" work in Python?
The condition is checked before each iteration. If it evaluates to True, the code block inside the loop is executed. The loop continues until the condition becomes False.
What happens if the condition in a "while loop" is initially False?
If the condition evaluates to False initially, the code block inside the loop will not execute, and the loop will be skipped entirely.
Can the condition in a "while loop" be changed within the loop itself?
Yes, you can modify the condition within the loop, and it will be re-evaluated before each iteration to determine whether to continue looping or exit.
How can I exit a "while loop" prematurely?
You can use the break
statement to exit the loop at any point when a specific condition is met.
Can I use "while True" to create an infinite loop?
Yes, you can use while True
to create an infinite loop. It will continue executing the code block until a break
statement or a system interrupt is encountered.
Can a "while loop" be nested within another loop or control structure?
Yes, you can nest a "while loop" within another loop or control structure to implement more complex iterative behavior.
Are the initial and final values of loop control variables accessible inside the "while loop"?
Yes, loop control variables can be defined before the loop and modified within the loop body, making their values accessible throughout the loop's execution.
Conclusion
As long as the specified condition is true, the while loop repeatedly executes its statements.
If you have any queries, feel free to post a comment below, and we'll be happy to answer them.