Python-while循环取决于我在菜单上的起始位置
我是python的超级初学者。 下面是一个简单的数学测验。问题是,选择选项2减法,然后选择1加法会关闭程序,而不是询问加法问题。 它在1到2之间工作,但在2到1之间不工作。你们知道我错过了什么吗?提前谢谢Python-while循环取决于我在菜单上的起始位置,python,while-loop,Python,While Loop,我是python的超级初学者。 下面是一个简单的数学测验。问题是,选择选项2减法,然后选择1加法会关闭程序,而不是询问加法问题。 它在1到2之间工作,但在2到1之间不工作。你们知道我错过了什么吗?提前谢谢 while user_input == 1: num1 = (random.randrange(0,100)) num2 = (random.randrange(0,100)) answer = num1 + num2 problem = str(num1) +
while user_input == 1:
num1 = (random.randrange(0,100))
num2 = (random.randrange(0,100))
answer = num1 + num2
problem = str(num1) + " + " + str(num2)
print("Enter your answer")
print(problem, end="")
result = int(input(" = "))
if result == answer:
print('Correct')
else:
print('Incorrect')
user_input = int(input('Enter your choice: '))
选择2的减法
选择3退出-用户完成测验
你的代码错了。你必须这样做:
choice = input()
while choice == "1" or choice == "2":
if choice == "1":
#do add
else:
#do subtraction
choice = input()
print("bye")
为了获得良好的实践和可读性,我将实现以下内容:
choice = input()
while choice != -1:
choice = input()
if choice == 1:
#do something
else if choice == 2:
#do something else
else if choice == -1:
print("bye")
选择3中最后一个选项的目的是什么。它没有if语句。我通常不会这么说,但是这个问题可能最适合用一个大的代码块来发布,而不是分开发布,因为这似乎是一个控制流问题。在循环之后可以有一个else。在循环结束后执行的。您的else仍然没有附加if语句。此外,需要接受所有可能形式的输入作为条件以保持循环继续,而不是有另一个“退出”值,这是一种不好的做法,我道歉。似乎附加到while循环的else:attached有一些有趣的循环行为失败。它不需要一个if附件,实际上可以按照您编写的方式工作。然而,如果这是你想要的,我仍然不同意OP的做法,因为他处于更初级的水平。哇,谢谢你的帮助。我现在就消化一下,也许过几天再给你们回复。
choice = input()
while choice == "1" or choice == "2":
if choice == "1":
#do add
else:
#do subtraction
choice = input()
print("bye")
choice = input()
while choice != -1:
choice = input()
if choice == 1:
#do something
else if choice == 2:
#do something else
else if choice == -1:
print("bye")