2017-08-14 44 views
0

我是新來編碼,並決定做一個基本的計算器。在我完成它的工作之後,我決定在輸入錯誤的變量時創建文本。我使用這個代碼,但它運行,不管我輸入什麼。任何修復將不勝感激!輸入錯誤時的基本計算器錯誤消息應該出現,但不管輸入如何顯示

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 

回答

0

所以你想一個值與一個列表,你真正想要的是檢查是否USER_INPUT不是預期值的列表中。嘗試這樣做(注意不在),

while user_input not in ("1","2","3","4"): 
    print("Please enter 1, 2, 3 or 4!") 
    user_input = input("Choice:") 
相關問題