How can I exit a loop in Python when a certain condition is met?
I have a loop, and I want it to stop when x + y = z. Here’s my code:
from random import randint
import os
x = randint(1, 11)
y = randint(1, 11)
print("", x, "+", y, "=\n")
z = int(input("Resposta="))
if z == x + y:
input("\n\nCorreto\nPrima enter para continuar...")
else:
for z in range(0, 10):
os.system('CLS')
input("Incorreto.\n\n Tente de novo...")
x = randint(1, 11)
y = randint(1, 11)
os.system('CLS')
print("", x, "+", y, "=\n")
z = int(input("Resposta="))
if z == x + y: # I want the loop to exit here
input("\n\nCorreto\nPrima enter para continuar...")
exit
In this scenario, I want the loop to stop when the condition z == x + y is true. How can I properly use Python exit for loop to break out of the loop?
You can use the break statement to exit the loop when the condition is met:
from random import randint
import os
x = randint(1, 11)
y = randint(1, 11)
print("", x, "+", y, "=\n")
z = int(input("Resposta="))
if z == x + y:
input("\n\nCorreto\nPrima enter para continuar...")
else:
for z in range(0, 10):
os.system('CLS')
input("Incorreto.\n\n Tente de novo...")
x = randint(1, 11)
y = randint(1, 11)
os.system('CLS')
print("", x, "+", y, "=\n")
z = int(input("Resposta="))
if z == x + y: # I want the loop to exit here
input("\n\nCorreto\nPrima enter para continuar...")
break # Exits the loop
You can use exit() to stop the program entirely (which will exit the loop and the program), but this is not always recommended as it terminates the entire script:
from random import randint
import os
x = randint(1, 11)
y = randint(1, 11)
print("", x, "+", y, "=\n")
z = int(input("Resposta="))
if z == x + y:
input("\n\nCorreto\nPrima enter para continuar...")
else:
for z in range(0, 10):
os.system('CLS')
input("Incorreto.\n\n Tente de novo...")
x = randint(1, 11)
y = randint(1, 11)
os.system('CLS')
print("", x, "+", y, "=\n")
z = int(input("Resposta="))
if z == x + y: # I want the loop to exit here
input("\n\nCorreto\nPrima enter para continuar...")
exit() # Exits the program entirely
If your loop is inside a function, you can use return to exit the function and stop the loop:
from random import randint
import os
def run_game():
x = randint(1, 11)
y = randint(1, 11)
print("", x, "+", y, "=\n")
z = int(input("Resposta="))
if z == x + y:
input("\n\nCorreto\nPrima enter para continuar...")
else:
for z in range(0, 10):
os.system('CLS')
input("Incorreto.\n\n Tente de novo...")
x = randint(1, 11)
y = randint(1, 11)
os.system('CLS')
print("", x, "+", y, "=\n")
z = int(input("Resposta="))
if z == x + y: # I want the loop to exit here
input("\n\nCorreto\nPrima enter para continuar...")
return # Exits the loop and the function
run_game()
The above solution ensures the loop exits when the condition z == x + y is true, with the keyword python exit for loop properly addressed in each context.