0
當我運行我的計算器時,它會給出以下結果;爲什麼我的代碼返回我的else語句?
Select operation.
1.Add
2.Subtract
3.Multiply
4.Divide
Enter choice(1/2/3/4):3
Enter first number: 1
Enter second number: 5
Invalid! Input
爲什麼與我else if語句可應對任何人都可以向我解釋,我心中已經檢查了代碼多次,再加上我已經複製的代碼直接粘貼,原樣,太多的無奈之後,但它產生相同的結果?
# A simple calculator that can add, subtract, multiply and divide.
# define functions
def add(x, y):
"""This function adds two numbers"""
return x + y
def subtract(x, y):
"""This function subtracts two numbers"""
return x - y
def multiply(x, y):
"""This function multiplies two numbers"""
return x * y
def divide(x, y):
"""This function divides two numbers"""
return x/y
# Take input from the user
print ("Select operation.")
print ("1.Add")
print ("2.Subtract")
print ("3.Multiply")
print ("4.Divide")
choice = input("Enter choice(1/2/3/4):")
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
if choice == '1':
print(num,"+",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("Invalid! Input")
您正在使用Python 2,我敢打賭。在Python 2中,'input()'*將輸入評估爲Python表達式,所以'choice'是一個整數。用Python 3運行你的代碼,或者發現你自己需要複製一個Python 2版本(例如使用'raw_input()'代替)。 –
可能相關:[如何在Python中以整數形式讀取輸入?](http://stackoverflow.com/a/20449433/1903116) – thefourtheye