Let’s look at how the while statement in Python is used to create loops. We’ll start with the basics and add to it as we go. The following is the format of a basic while loop: and here you will know 10 best ways to use while loops in python
Contents
10 Best Ways To Use While Loop In Python
while
contains the content of the loop, which is the block that will be run continuously. Indentation is used to indicate this, just like in an if expression.
The else Clause
A while loop in Python can have an optional else clause at the end. This is a feature that Python has that most other programming languages lack. The following is the syntax:
while:
else:
When the while loop comes to an end, the else clause will be executed. “How is that useful?” you might be thinking right now. You might achieve the same result without the else clause by placing those statements immediately after the while loop:
while:
Infinite Loops
Assume you’ve written a while loop that, in theory, will never finish. Sounds weird, right?
Consider this example:
while True: print('foo')
Output
KeyboardInterrupt
Traceback (most recent call last):
File “”, line 2, in
print(‘foo’)
This code was halted by pressing Ctrl+C, which causes a keyboard interrupt. It would have gone on indefinitely if it hadn’t been stopped. In the output shown, many foo output lines have been eliminated and replaced by a vertical ellipsis.
Nested while loops
Python control structures can be layered within one other in general. If/elif/else conditional statements, for example, can be nested:
if age == 18: if gender == 'M': print('son') else: print('daughter') if gender == 'M': print('father') else: print('mother') if gender == 'M': print('grandfather') else: print('grandmother')
A while loop can also be placed within every while loop, see above:
a = ['foo', 'bar'] while len(a): print(a.pop(0)) b = ['baz', 'qux'] while len(b): print('', b.pop(0))
Within nested loops, a break or continue statement applies to the nearest enclosing loop:
One-Line while Loops
A while loop, like an if statement, can be specified on a single line. Semicolons (;) can be used to separate multiple statements in the block that makes up the loop body:
n = 5 4 3 2 1 0
However, this only works with simple statements. Two compound statements cannot be combined into a single line. As a result, you can declare a while loop on one line and write an if statement on the same line:
if True: print('foo')
For Loop
Iterators are what Python calls “for loops.”
“For Loop,” like the while loop, is used to repeat the program.
However, unlike the while loop, which is conditional on true or false, the for loop is not conditional. The iteration of elements in a “For Loop” is determined by the components to be iterated.
Example:
#Example file for working with loops
x=0 #define a while loop while(x): <h3>Break Statements in For Loop</h3> A breakpoint is a one-of-a-kind function in the For Loop that allows you to pause or stop the execution of the loop. Example: <strong>#use a for loop over a collection</strong> Months = ["Jan","Feb","Mar","April","May","June"] for m in Months: print(m) # use the break and continue statements for x in range (10,20): if (x == 15): break # if (x % 2 == 0) : continue print(x)
Continue Statement Loop
The continue function, as its name implies, will end the current iteration of the for loop but continue the remaining iterations.
Example
#use a for loop over a collection
Months = ["Jan","Feb","Mar","April","May","June"] for m in Months: print (m)
# use the break and continue statements
for x in range (10,20): if (x == 15): break if (x % 5 == 0) : continue print(x)
Enumerate Loop
Enumerate() is a Python built-in system that offers every element of an iterable collection an index. It constructs an iterable object loop and returns the object in enumerable form while keeping track of the current item. The list() method can be used in a for loop to transform this object into a list.
Example:
If we want to number our months (Jan, Feb, Marc,….June), we declare the variable I to enumerate the numbers, and the variable m to print the month number in a list.
#use a for loop over a collection
Months = ["Jan","Feb","Mar","April","May","June"] for I, m in enumerate (Months): print(i,m)
# use the break and continue statements
for x in range (10,20): if (x == 15): break if (x % 5 == 0) : continue print (x)
Read More: 10 Ways to Use Python For Loop, What is For Loop in Python?