【发布时间】:2018-10-17 02:02:12
【问题描述】:
我对 Python 很陌生。
我制作了一个数学程序,每次你做对最后一道题时,它都会不断生成一个新的数学题。但是我不知道如何退出/中断 while 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: 循环。我查看了针对类似问题发布的其他答案,但是当我尝试它们时,它们都会阻止我的代码产生超过一定数量的问题。
有没有办法做到这一点。还是我需要找到一种方法来运行这个数学游戏而无需 while True 循环?
【问题讨论】:
标签: python-3.x while-loop infinite-loop