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

时间:2018-12-24 11:27:06

标签: python python-3.x calculator

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

我正在构建一个基本的计算器。对于我在其中描述的三个功能,它工作正常。但是,如果有人输错了他或她想使用的功能(例如,键入“ multifly”即输入“ multiply”),则会返回一个句子,告诉用户输入了错字。我想代表这一行,但也要让它从头开始重新运行。也就是说,如果您输入错误,请回到第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.")

2 个答案:

答案 0 :(得分:1)

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":
    ...

您需要在循环中执行输入和验证部分,然后通过计算来执行代码。 (假设计算器只计算一次,然后退出。否则,您可以将整个事情放到另一个循环中,以进行更多计算,甚至可以使用退出命令。)

在我的示例中,验证是通过包含您可能的命令的一组(选择)进行的,并检查输入的成员资格。

答案 1 :(得分:1)

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]:
#...