How to End the while Loop in Python
-
End a
whileLoop in Python Using thebreakStatement -
End a
whileLoop in Python Within a Function Using thereturnStatement
This article will explain how we can end a while loop in Python. A while loop is a control flow statement used to repeat a specific code again and again until the specified condition is not reached. It can be considered as a repeating if statement.
We can end a while loop with a True condition within a function body and outside a function body in the following two ways in Python.
End a while Loop in Python Using the break Statement
We can end a while loop outside a function body by simply using a break statement. Suppose we have a list of numbers, and we want to end the while loop if we lose the number is greater than a certain value.
The example below demonstrates how to end a while loop using the break statement in Python.
mylist = [1, 4, 2, 7, 16, 3, 2, 8]
while True:
if mylist[-1] < 5:
print("less than 5")
if mylist[-1] > 10:
print("greater than 10")
break
if mylist[-1] > 5:
print("greater than 5")
mylist.pop()
Output:
greater than 5
less than 5
less than 5
greater than 10
We can also end a while loop within a function body using the break statement in Python, as demonstrated in the below example code.
mylist = [1, 4, 2, 7, 16, 3, 2, 8]
def myfunc():
while True:
if mylist[-1] < 5:
print("less than 5")
if mylist[-1] > 10:
print("greater than 10")
break
if mylist[-1] > 5:
print("greater than 5")
mylist.pop()
return
if __name__ == "__main__":
myfunc()
Output:
greater than 5
less than 5
less than 5
greater than 10
End a while Loop in Python Within a Function Using the return Statement
We can end a while loop in Python within a function using the return statement. In a function, we can also use the return statement instead of the break statement to end a while loop, which will stop the while loop and end the function’s execution.
The example below demonstrates how to use a return statement within a function body to end the while loop in Python.
mylist = [1, 4, 2, 7, 16, 3, 2, 8]
def myfunc():
while True:
if mylist[-1] < 5:
print("less than 5")
if mylist[-1] > 10:
print("greater than 10")
return
if mylist[-1] > 5:
print("greater than 5")
mylist.pop()
if __name__ == "__main__":
myfunc()
Output:
greater than 5
less than 5
less than 5
greater than 10