[英]Why is my code returning my else: statement?
When i run through my calculator, it gives the following results; 当我运行计算器时,它将得到以下结果;
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
Can anyone explain to me why it is responding with my else if statement, i'v checked the code many times, plus i have copied paste the code directly, as is, after much frustration, yet it yields the same result? 任何人都可以向我解释为什么我用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")
You're using Python 2, where input()
evaluates what is entered; 您正在使用Python 2,其中input()
评估输入的内容; so when you enter 2
, for instance, choice
contains the int
2
. 因此,例如,当您输入2
时, choice
包含int
2
。 Try entering '2'
into your current code (including the quotes). 尝试在当前代码(包括引号)中输入'2'
。 It'll act as you expect entering 2
to act. 就像您期望输入2
起作用。
You should use raw_input()
on Python 2 and input()
on Python 3. If you want your code to be compatible with both, you can use the following code, after which you can always just use input()
: 您应该在Python 2上使用raw_input()
在Python 3上使用input()
。如果您希望代码与两者兼容,则可以使用以下代码,之后始终可以只使用input()
:
try:
input = raw_input # Python 2
except NameError: # We're on Python 3
pass # Do nothing
You can also use the six
package, which does this and many other Python 2/3 compatibility things. 您还可以使用six
软件包,它可以执行此操作以及其他许多与Python 2/3兼容的事情。
In Python 3 input()
does what raw_input()
does in Python 2, and Python 2's input()
is gone. 在Python 3中, input()
作用与Python 2中raw_input()
作用相同,而Python 2的input()
消失了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.