2015-08-22 125 views
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") 
+1

您正在使用Python 2,我敢打赌。在Python 2中,'input()'*将输入评估为Python表达式,所以'choice'是一个整数。用Python 3运行你的代码,或者发现你自己需要复制一个Python 2版本(例如使用'raw_input()'代替)。 –

+0

可能相关:[如何在Python中以整数形式读取输入?](http://stackoverflow.com/a/20449433/1903116) – thefourtheye

回答

2

您正在使用Python 2,其中input()评估输入内容;所以当您输入2时,例如,choice包含int2。尝试将'2'输入您当前的代码(包括引号)。它会按照您的期望进入2采取行动。

你应该如果你想你的代码能够同时与兼容关于Python 3. Python 2和input()使用raw_input(),您可以使用下面的代码,之后就可以永远只是用input()

try: 
    input = raw_input # Python 2 
except NameError: # We're on Python 3 
    pass # Do nothing 

你也可以使用six包,它可以做到这一点,还有很多其他Python 2/3兼容性的东西。

在Python 3中input()是什么raw_input()在Python 2中做的,而Python 2的input()已经不存在了。

相关问题