Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3中,如何在另一条消息之前显示消息_Python_Python 3.x_Calculator - Fatal编程技术网

在Python3中,如何在另一条消息之前显示消息

在Python3中,如何在另一条消息之前显示消息,python,python-3.x,calculator,Python,Python 3.x,Calculator,如您所见,我正在用Python3创建一个非常简单的计算器,我希望在用户选择非1、2、3或4的内容时显示一条错误消息。我该怎么做?当前代码仅在用户输入了他们想要加、减、乘或除的数字后显示错误消息,这似乎有点违反直觉。您必须请求输入,并按照您希望的顺序验证输入。要求用户在循环中进行选择。如果他们输入了无效的内容,请他们再试一次。在他们输入有效内容之前,不要中断循环。一旦他们这样做了,就转到下一个输入 name = input("What's your name?\n") print("Hello,

如您所见,我正在用Python3创建一个非常简单的计算器,我希望在用户选择非1、2、3或4的内容时显示一条错误消息。我该怎么做?当前代码仅在用户输入了他们想要加、减、乘或除的数字后显示错误消息,这似乎有点违反直觉。

您必须请求输入,并按照您希望的顺序验证输入。要求用户在循环中进行选择。如果他们输入了无效的内容,请他们再试一次。在他们输入有效内容之前,不要中断循环。一旦他们这样做了,就转到下一个输入

name = input("What's your name?\n")
print("Hello, %s.\nWelcome to the best calculator program in the world.\nSelect an operation to get started.\n------------------------------------------------------------------" % name)
def add(x, y):
   return x + y
def subtract(x, y):
   return x - y
def multiply(x, y):
   return x * y
def divide(x, y):
   return x / y
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")
choice = input("What operation would you like to use?: ")
num1 = float(input("Enter your first number, please: "))
num2 = float(input("Enter your second number, please: "))
if choice == '1':
   print(num1,"+",num2,"=", add(num1,num2))
elif choice == '2':
   print(num1,"-",num2,"=", subtract(num1,num2))
elif choice == '3':
   print(num1,"*",num2,"=", multiply(num1,num2))
elif choice == '4':
   print(num1,"/",num2,"=", divide(num1,num2))
else:
   print("Looks like you tried to use something other than 1, 2, 3, or 4. Try again")
输出:

options = [
    ("1", "Add"),
    ("2", "Subtract"),
    ("3", "Multiply"),
    ("4", "Divide")
]

for option in options:
    print("{}. {}".format(*option))

message = "Enter your selection: "
while True:
    user_selection = input(message)
    if user_selection in map(lambda tpl: tpl[0], options):
        break
    message = "Try again: "

我尝试使用
if=但这也不起作用。我真的不知道还能做些什么。整个代码只是为了说明我在python方面是多么缺乏经验,谢谢,我会尝试一下,然后回到这里。我们都是从某个地方开始的!
1. Add
2. Subtract
3. Multiply
4. Divide
Enter your selection: asdasd
Try again: 678
Try again: 5
Try again: 3
>>>