Python Loop Control
In Python, loop controls are used to skip certain
step/steps in a loop.
There're basically three types of loop conrols.
"Pass" Keyword
The pass keyword does nothing. It is used to
replace a situation where an
element is to used to fullfill without assigning any operation.
The below code will throw an error since there's an empty element.
n = 5
#nothing included inside if Statement.
if n > 2:
print("bye")
Press Run to execute.
Learn more about "if" statement Here.
To overcome the above problem we can use the "pass" statement.
n = 5
if n > 2:
pass
print("bye")
Press Run to execute.
"break" Keyword
The break statement is used to break out of a
loop
when a certain condition is fullfilled.
Any line of code within the loop after the it reach the break statement will not get excuted.
When the value assigned to the variable "num" is equal to 5, break out of the loop(for).
for num in range(1,100):
print(num)
if num == 5 :
break
print("hello")
print ("over")
#"over" is out of the loop
Press Run to execute.
When the variiable "num" is assigned with value 5, the code break out of the loop and execute the
rest - print("over"), because of the "break" statement.
Above code can be represented using "while" loop as well.
num = 1
while num < 10:
print(num)
if num == 5:
break
print("hello")
num = num + 1
print("over")
Press Run to execute.
Learn more about "loops" Here.
"continue" Keyword
The continue statement is used to reach the
start of a loop
when a certain condition is fullfilled.
When the value assigned to the variable "i" is equal to 3, restart the loop (for).
for i in range(1,5):
print("Hi")
if i == 3 :
continue
print("bye")
print ("over")
#"over" is out of the loop
Press Run to execute.
When the variiable "i" is asigned with value 3, the code reach back to the start of the loop and
restart
without reaching the bottom lines of code - print("bye") because of the "continue"
statement.
Above code can be represented using "while" loop as well.
i = 0
while i < 4:
i = i + 1
print("Hi")
if i == 3:
continue
print("bye")
print("over")
Press Run to execute.
Learn more about "loops" Here.