猿问

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

我对编程很陌生,作为一名数学学生,我将学习 Python 编程。为了做好充分准备,我认为我已经深入了解该计划,使用一些 YouTube 视频和在线材料。现在的问题。


我正在构建一个基本的计算器。它适用于我在其中描述的三个功能。但是如果有人打错了他或她想要使用的函数(例如输入“multifly”iso“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.")


慕运维8079593
浏览 275回答 3
3回答

桃花长相依

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: breakif choice == "add":    ...你在循环中完成输入和验证部分,然后你的代码进行计算。(假设计算器只计算一次然后退出。如果没有,你可以把整个事情放在另一个循环中进行更多计算,也许有一个退出命令。)在我的示例中,验证是通过包含您可能的命令的集合(选择)完成的,并检查输入的成员资格。

萧十郎

OP = ("add", "subtract", "multiply")while True:    choice = input("Pick an operation {}: ".format(OP))    if choice not in OP:        print("Invalid input")    else:        breakif choice == OP[0]:#...
随时随地看视频慕课网APP

相关分类

Python
我要回答