如何使用循环重新运行基本计算器

How to use a loop to rerun a basic calculator

我对编程还很陌生,作为一名学生,我将学习 Python 编程。为了做好充分的准备,我想我已经开始使用一些 youtube 视频和在线 material 来深入了解该程序了。现在是问题。

我正在构建一个基本的计算器。它适用于我在其中描述的三个功能。但是如果有人输错了他或她想要使用的功能(例如输入 "multifly" i.s.o "multiply"),它会 returns 一个句子告诉用户它打错了。我想代表这条线,但也让它从头开始重新运行。也就是说,如果你打错了字,回到第 1 行询问用户他想做什么。

我知道我必须使用 for 或 while 循环,但我不知道如何真正让它工作。请给我一些建议:)

choice = input("Welcome to the basic calculator, please tell me if you want to add, substract or muliply: ")

if choice == "add":

     print("You choose to add")
     input_1 = float(input("Now give me your first number: "))
     input_2 = float(input("And now the second: "))
     result = (input_1 + input_2)
     if (result).is_integer() == True:
          print("Those two added makes " + str(int(result)))
     else:
          print("Those two added makes " + str(result))
elif choice == "substract":
     print("You choose to substract")
     input_1 = float(input("Now give me your first number: "))
     input_2 = float(input("And now the second: "))
     result = (input_1 - input_2)
     if (result).is_integer() == True:
          print("Those two substracted makes " + str(int(result)))
     else:
         print("Those two substracted makes " + str(result))
elif choice == "multiply":
     print("You choose to multiply")
     input_1 = float(input("Now give me your first number: "))
     input_2 = float(input("And now the second: "))
     result = (input_1 * input_2)
     if (result).is_integer() == True:
         print("Those two multiplied makes " + str(int(result)))
     else:
         print("Those two multiplied makes " + str(result))

else:
print("I think you made a typo, you'd have to try again.")
choices={"add","substract","multiply"}
while 1:
    choice = input("Welcome to the basic calculator, please tell me if you want to add, substract or muliply: ")
    if choice not in choices:
        print("I think you made a typo, you'd have to try again.")
    else: break

if choice == "add":
    ...

你在循环中完成输入和验证部分,然后你的代码进行计算。 (假设计算器只计算一次然后退出。如果没有,你可以把整个东西放在另一个循环中进行更多计算,也许有一个退出命令。)

在我的示例中,验证是使用包含您可能的命令的集合(选择)完成的,并检查输入的成员资格。

OP = ("add", "subtract", "multiply")

while True:
    choice = input("Pick an operation {}: ".format(OP))
    if choice not in OP:
        print("Invalid input")
    else:
        break

if choice == OP[0]:
#...