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