Table of Contents
ToggleIntroduction
You can automate repetitive activities with Python’s many tools and functionalities. While Loop in Python, Loops are one of those qualities. All contemporary programming languages include loops because they are useful and often used. When you wish to automate a certain repetitious operation or stop yourself from repeatedly pasting the same code into your program, loops come in handy. In computer programming, loops repeatedly run the same block of code or set of instructions until a condition is satisfied or is no longer fulfilled.
What is While Loop in Python?
While Loop in Python is used to repeatedly run a block of statements until a specified condition is met. And the line immediately following the loop in the program is performed when the condition changes to false.
Syntax:
while expression:
statement(s)
Code
# Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1
print(“DataTrained”)
Output
DataTrained
DataTrained
DataTrained
If the counter variable (count) in the above example is fewer than three, the while condition will be True.
Flow Diagram of While Loop in Python
The while loop is an example of an infinite loop. When a loop is iterated indefinitely, the number of times the loop is run isn’t explicitly stated beforehand.
A block of code is considered to consist of all the statements that follow a programming construct and are indented by the same number of character spaces. Python groups statements together with indentation. The experiment is initially assessed in a Boolean context when a while loop is run, and if it returns true, the loop body is then run. When the expression is still true, the body is then executed once more, and so on until the expression is no longer true.
While Loop in Python Using Else
While loop in Python runs the block until a condition is met, as was previously discussed, the statement that follows the loop is executed when the condition changes to false. Only when your while condition is false is the else clause put into action? The loop won’t be run if you leave it or if an exception is thrown.
Note: When the loop isn’t ended by a break statement, the else block immediately following for/while is only ever put into action.
# Python program to demonstrate
# while-else loop
i = 0
while i < 4:
i += 1
print(i)
else: # Executed because no break-in for
print(“No Breakn”)
i = 0
while i < 4:
i += 1
print(i)
break
else: # Not executed as there is a break
print(“No Break”)
Output
1
2
3
4
No Break
1
Click here to know more about data analytics courses in India
Single Statement WhileBlock
The whole block can be declared in a single line if it just contains a single statement, just as the if block. While Loop in Python, The block that forms the loop body can contain many statements; semicolons can be used to divide them(;).
# Python program to illustrate
# Single statement while block
count = 0
while (count < 5): count += 1; print(“DataTrained”)
Output
DataTrained
DataTrained
DataTrained
DataTrained
DataTrained
Sentinel Controlled Statement
Since we don’t know the number of times the loop will run, we don’t need a counter variable in this. While Loop in Python, Here, the user chooses how many times to run the loop. We employ a sentinel value for this. When a user joins a loop, a sentinel value is used to end it. Typically, the sentinel value is -1.
Python while loop with user input
a = int(input(‘Enter a number (-1 to quit): ‘))
while a != -1:
a = int(input(‘Enter a number (-1 to quit):
Also read: data science colleges in Mumbai
While Loop in Python on Boolean Values
Boolean values are frequently used in while loop in Python to generate infinite loops that can only be terminated in response to certain conditions.
For example:
# Initialize a counter
count = 0
# Loop infinitely
while True:
# Increment the counter
count += 1
print(f”Count is {count}”)
# Check if the counter has reached a certain value
if count == 10:
# If so, exit the loop
break
# This will be executed after the loop exits
print(“The loop has ended.”)
Output
Count is 1
Count is 2
Count is 3
Count is 4
Count is 5
Count is 6
Count is 7
Count is 8
Count is 9
Count is 10
The loop has ended.
Loop Control Statements
Statements used to control loops divert execution from the usual path. While Loop in Python, All automatic objects produced within a scope are deleted when execution exits it. The following control statements are supported by Python.
Continue Statement
Python’s continue statement resets the loop’s starting point.
While Loop in Python with a continue statement
# Prints all letters except ‘e’ and ‘s’
i = 0
a = ‘DataTrained’
while i < len(a):
if a[i] == ‘e’ or a[i] == ‘s’:
i += 1
continue
print(‘Current Letter :’, a[i])
i += 1
Output
Current Letter : g
Current Letter : k
Current Letter : f
Current Letter : o
Current Letter : r
Current Letter : g
Current Letter : k
Break Statement
The break statement in Python removes control from the loop.
While loop in Python with a break statement
# break the loop as soon it sees ‘e’
# or ‘s’
i = 0
a = ‘DataTrained’
while i < len(a):
if a[i] == ‘e’ or a[i] == ‘s’:
i += 1
break
print(‘Current Letter :’, a[i])
i += 1
Output
Current Letter : g
Pass Statement
Python’s pass statement can be used to create empty loops. Pass is also used for classes, functions, and empty control statements.
While loop in Python with a pass statement
# An empty loop
a = ‘DataTrained’
i = 0
while i < len(a):
i += 1
pass
print(‘Value of i :’, i)
Output
Value of i : 13
Conclusion
Python’s use of loops makes it possible to execute a section of code continuously without having to repeat the same lines of code. While Loop in Python, By repeatedly running the same piece of code, loops turn complex issues into simple ones. While loop in Python is used to exe
cute a block of code until a specific condition is met. Here, the condition is assessed via a while loop. The while loop’s code is performed if the condition evaluates to True.
Related blogs:-
Python Array | Everything you need to Know
Frequently Asked Questions
What is a while loop example?
When a condition is not satisfied, a “While” loop is employed to repeat a certain piece of code an undetermined number of times. For instance, if we would like to inquire from a user for a number between 1 and 10, but we don’t know how often they might enter a greater number, we keep requesting “while the number is not between 1 and 10.”
Why do while loop is used?
We may repeat the execution of various statements using the do-while loop. When we need to run the loop at least once, the do-while loop is typically utilised. Most menu-driven programs employ the do-while loop, where the termination circumstance depends on the user.
What is tuple in Python?
Multiple items can be stored in a single variable by using tuples. One of the four built-in data types in Python for storing data collections is the tuple; the other three are list, set, and dictionary, each with a unique set of features and applications. A tuple is an unchanging, ordered collection.
What is while True Python?
While True in Python
It is customary to use this phrase to imply that the loop must continue to run till it breaks. The break statements are then added within the code block. Python’s while the true function is easy to use.
How does a while loop start?
The evaluation of condition initiates the while loop. The code in the code block is executed if the condition evaluates to true. The code in the code block is not run and the loop stops if the condition evaluates to false.