3 回答

TA贡献2065条经验 获得超14个赞
我认为最好先进入一个while循环,然后从用户那里获取输入或确定答案是否正确以及其他问题......
# coding: utf-8
# Start of the 1st Question
redo="y"
A1=-1 # can be any integer but not the correct answer
n1, n2 = 2, 3
while (A1 != n1 + n2) or redo.lower()=="y":
# ask the question
A1 = int(input("What is the sum of %i and %i : " % (n1, n2)))
# if answer is correct
if A1 == n1 + n2:
redo = input("Correct ! Would you like to try again? (Y/[N]) : ")
if redo.lower() == "y":
continue
else:
break
else:
print("Your Answer : %d is Incorrect!" % A1)

TA贡献1898条经验 获得超8个赞
这种程序结构没有意义。
你可以做:
while True:
num1 = int(input("num1 "))
num2 = int(input("num2 "))
op = '+'
calc = -1
if op == "+":
while calc != num1 + num2:
calc = int( input(f"Whats {num1} {op} {num2}?"))
elif op == "-":
pass # code the others
elif op == "*":
pass # code the others
elif op == "/":
pass # code the others - use float where needed instead of int
# comparing floats is difficult due to float math rounding imperfection
print("Correct!" , num1, op, num2,"=",calc)
again = input("Again? Y to do it again: ").lower()
if again != "y":
break # leaves the while True

TA贡献1860条经验 获得超8个赞
为此,您可以定义一个函数。也许它比你在课堂上做的要复杂一点,但它仍然很基础,所以你可以轻松学习它:) 使用函数时,请记住在第一次调用它以便它可以工作。这是一个例子:
def function_name():
while True:
'''your code'''
repeat =(input("Correct! would you like to try again? Y/N "))
if repeat == "y":
function_name() # wach time the user say "y" the code calls the function again.
break # the break will finish the while loop and will close the program.
function_name() # that's where I call the function the first time.
顺便说一句,如果您正在使用该函数,则实际上不必使用 while 循环。但我认为这是你在课堂上的工作,所以我就这样吧:)
添加回答
举报