как мне разорвать бесконечный цикл с пользовательским вводом - PullRequest
0 голосов
/ 07 мая 2018

Я очень плохо знаком с Python.

Я создал математическую программу, которая продолжает генерировать новую математическую задачу каждый раз, когда вы правильно решаете последнюю. однако я не знаю, как выйти / прервать цикл True и перейти от сложения к вычитанию.

import random

while True:

    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 True:
            print(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)
            else:
                print("Have another go")
            #I want to push space to break this while loop
            #and be able to switch to subtraction problems    
    if question == "2":
        print("Try your skill at these problems.")
        number1 = random.randint(0, 9)
        number2 = random.randint(0, 9)

        while True:
            print(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)
            else:
                print("Have another go")
            #I want to push space to break this while loop
            #and be able to switch to addition problems

как мне указать пользовательский ввод (например, пробел) для торможения цикла while True :. Я посмотрел на другие ответы, опубликованные на похожие вопросы, но когда я их попробую, все они мешают моему коду генерировать больше, чем набор проблем.

Есть ли способ сделать это. или мне нужно найти способ запустить эту математическую игру без короткого цикла True?

1 Ответ

0 голосов
/ 07 мая 2018

Хорошо использовать цикл while, когда количество циклов не может быть определено, отлично подходит для вашего подхода с использованием цикла while.

Если вы хотите выйти из цикла while, вы можете попытаться определить переменную (переменную условий) вне цикла while и установить, что переменная становится вашими условиями while. А чтобы выйти из цикла, просто измените значение переменной условий.

Примеры кода:

import random

while True:

    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 changes
            print(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 changes
                if checking == "N": # my changes
                    conditions = False # my changes
            else:
                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 changes
            print(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 changes
                if checking == "N": # my changes
                    conditions = False # my changes
            else:
                print("Have another go")
...