Learn Python programming with this Python tutorial for beginners!
Learn how to use while loops and the break statement in Python.
In Python, While Loops is used to execute a block of statements repeatedly until a given condition is satisfied. And when the condition becomes false, the line immediately after the loop in the program is executed. While loop falls under the category of indefinite iteration. Indefinite iteration means that the number of times the loop is executed isn’t specified explicitly in advance.
Syntax:
while expression:
statement(s)
Statements represent all the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. Python uses indentation as its method of grouping statements. When a while loop is executed, expr
is first evaluated in a Boolean context
and if it is true, the loop body is executed. Then the expr
is checked again, if it is still true then the body is executed again and this continues until the expression becomes false.
Example:
# Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
print()
# checks if list still
# contains any element
a = [1, 2, 3, 4]
while a:
print(a.pop())
Output:
Hello Geek
Hello Geek
Hello Geek
4
3
2
1
Just like the if
block, if the while
block consists of a single statement the we can declare the entire loop in a single line. If there are multiple statements in the block that makes up the loop body, they can be separated by semicolons (;)
.
# Python program to illustrate
# Single statement while block
count = 0
while (count < 5): count += 1; print("Hello Geek")
Output:
Hello Geek
Hello Geek
Hello Geek
Hello Geek
Hello Geek
Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
# Prints all letters except 'e' and 's'
i = 0
a = 'geeksforgeeks'
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 the loop as soon it sees 'e'
# or 's'
i = 0
a = 'geeksforgeeks'
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
# An empty loop
a = 'geeksforgeeks'
i = 0
while i < len(a):
i += 1
pass
print('Value of i :', i)
Output:
Value of i : 13
As discussed above, while loop executes the block until a condition is satisfied. When the condition becomes false, the statement immediately after the loop is executed.
The else clause is only executed when your while condition becomes false. If you break out of the loop, or if an exception is raised, it won’t be executed.
Note: The else block just after for/while is executed only when the loop is NOT terminated by a break statement.
# 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 Break\n")
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
Using loops in Python automates and repeats the tasks in an efficient manner. But sometimes, there may arise a condition where you want to exit the loop completely, skip an iteration or ignore that condition. These can be done by loop control statements. Loop control statements change execution from its normal sequence. When execution leaves a scope, all automatic objects that were created in that scope are destroyed. Python supports the following control statements.
In this article, the main focus will be on break
statement.
Break statement in Python is used to bring the control out of the loop when some external condition is triggered. Break statement is put inside the loop body (generally after if condition).
Syntax:
break
Example:
# Python program to
# demonstrate break statement
s = 'geeksforgeeks'
# Using for loop
for letter in s:
print(letter)
# break the loop as soon it sees 'e'
# or 's'
if letter == 'e' or letter == 's':
break
print("Out of for loop")
print()
i = 0
# Using while loop
while True:
print(s[i])
# break the loop as soon it sees 'e'
# or 's'
if s[i] == 'e' or s[i] == 's':
break
i += 1
print("Out of while loop")
Output:
g
e
Out of for loop
g
e
Out of while loop
In the above example, both the loops are iterating the string ‘geeksforgeeks’ and as soon as they encounter the character ‘e’ or ‘s’, the if condition becomes true and the flow of execution is brought out of the loop.
#python #machine-learning #web-development