Skip to content Skip to sidebar Skip to footer

How Do I Break Infinite While Loop With User Input

I'm very new to Python. I made a math program that keeps generating a new math problem every time you get the last one right. however I don't know how to exit/break the while True

Solution 1:

It is good to use while loop when the number of looping cannot be determined, Well done for your approach using while loop.

If you want to exit the while loop, you can try to define a variable(conditions variable) outside the while loop, and set the variable become your while conditions. And to exit the loop, just change the value of the conditions variable.

Code examples :

import random

whileTrue:

    conditions = True# my changes
    question = input("press 1 for addition, press 2 for subtraction.")
    if question == "1":
        print("Try your skill at these problems.")
        number1 = random.randint(0, 9)
        number2 = random.randint(0, 9)

        while conditions: # my changesprint(number1, "+", number2, "=")
            number3 = number1+number2
            answer = int(input())
            if answer == number3:
                print("Great Job, Try this one.")
                number1 = random.randint(0, 9)
                number2 = random.randint(0, 9)
                checking = input("Another round? (Y/N)") # my changesif checking == "N": # my changes
                    conditions = False# my changeselse:
                print("Have another go")
    if question == "2":
        print("Try your skill at these problems.")
        number1 = random.randint(0, 9)
        number2 = random.randint(0, 9)

        while conditions: # my changesprint(number1, "-", number2, "=")
            number3 = number1-number2
            answer = int(input())
            if answer == number3:
                print("Great Job, Try this one.")
                number1 = random.randint(0, 9)
                number2 = random.randint(0, 9)
                checking = input("Another round? (Y/N)") # my changesif checking == "N": # my changes
                    conditions = False# my changeselse:
                print("Have another go")

Post a Comment for "How Do I Break Infinite While Loop With User Input"