当我运行计算器时,它会给出以下结果
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")
您使用的是python2,其中
input()
计算输入的内容;因此,当您输入2
时,例如,choice
包含int
2
。尝试在当前代码中输入'2'
(包括引号)。它将按您所期望的那样进入2
来执行。你知道吗您应该在python2上使用
raw_input()
,在python3上使用input()
。如果您希望您的代码与这两者兼容,可以使用以下代码,之后您可以始终使用input()
:您还可以使用^{} 包,它可以实现这一点和许多其他python2/3兼容性方面的功能。你知道吗
在python3中
input()
做了python2中raw_input()
做的事情,python2的input()
就不见了。你知道吗相关问题 更多 >
编程相关推荐