Python 3.x 当输入错误时,基本计算器错误消息应该出现,但不管输入如何都会出现
我不熟悉编码,决定做一个基本的计算器。在我做了它并开始工作之后,我决定做一个文本,当你输入错误的变量时,它就会出现。我使用了这段代码,但不管输入什么,它都会运行。任何修复都将不胜感激Python 3.x 当输入错误时,基本计算器错误消息应该出现,但不管输入如何都会出现,python-3.x,Python 3.x,我不熟悉编码,决定做一个基本的计算器。在我做了它并开始工作之后,我决定做一个文本,当你输入错误的变量时,它就会出现。我使用了这段代码,但不管输入什么,它都会运行。任何修复都将不胜感激 while user_input != ("1","2","3","4"): print("Please enter 1, 2, 3 or 4!") user_input = input("Choice:") 以下是完整的代码: import time def Add(x, y): re
while user_input != ("1","2","3","4"):
print("Please enter 1, 2, 3 or 4!")
user_input = input("Choice:")
以下是完整的代码:
import time
def Add(x, y):
return x + y # x is added to y
def Sub(x, y):
return x - y # x is subtracted by y
def Multiply(x, y):
return x * y # x is multiplied by y
def Divide(x, y):
return x / y # x is divided by y
print("Select a function:\n")
print("1.Add\n")
print("2.Sub\n")
print("3.Multiply\n")
print("4.Divide\n")
user_input = input("Choice:") # user chooses function
while user_input != ("1","2","3","4"):
print("Please enter 1, 2, 3 or 4!")
user_input = input("Choice:")
num1 = float(input("Enter first number:")) # user unputs number
num2 = float(input("Enter second number:")) # user inputs second number
if user_input == '1':
print(num1, "+", num2, "=", Add(num1,num2))
if user_input == '2':
print(num1, "-", num2, "=", Sub(num1,num2))
if user_input == '3':
print(num1, "*", num2, "=", Multiply(num1,num2))
if user_input == '4':
print(num1, "/", num2, "=", Divide(num1,num2))
time.sleep(5) # sleeps for 5 seconds before ending
因此,您试图将单个值与列表进行比较,您真正想要的是检查用户输入是否不在预期值列表中。试着这样做(注意不在)
while user_input not in ("1","2","3","4"):
print("Please enter 1, 2, 3 or 4!")
user_input = input("Choice:")