Python 2.7 为什么不是';我的程序运行不正常吗?if语句不是';t被求值,它直接跳转到Python中的else语句

Python 2.7 为什么不是';我的程序运行不正常吗?if语句不是';t被求值,它直接跳转到Python中的else语句,python-2.7,if-statement,Python 2.7,If Statement,当我试图将任何值输入op时,总是执行else语句 这里有什么问题?我是编程新手 print "Basic Calculator" print "Options:" print "For addition, type add" print "For subtraction, type sub" print "For multiplication, type mul" print "For division, type div" op = raw_input() num1 = raw_input(

当我试图将任何值输入op时,总是执行else语句

这里有什么问题?我是编程新手

print "Basic Calculator"
print "Options:"
print "For addition, type add"
print "For subtraction, type sub"
print "For multiplication, type mul"
print "For division, type div"

op = raw_input()
num1 = raw_input("Enter first number: ")
num2 = raw_input("Enter second number: ")

if op == 'sum':
    print "The sum is: ", num1 + num2
elif op == 'sub':
    if num1 > num2:
        print "The subtraction is: ", num1 - num2
    else:
        print "The subtraction is: ", num1 - num2
elif op == 'mul':
    print "The product is: ", num1 * num2
elif op == 'div':
    print "The division is: ", num1 / num2
else:
    print "You entered an incorrect operation"

如果先键入所需的操作,然后键入两个数字,则可以正常工作,还需要将数字转换为整数:

print "Basic Calculator"
print "Options:"
print "For addition, type add"
print "For subtraction, type sub"
print "For multiplication, type mul"
print "For division, type div"

op = raw_input("Enter the operation wanted (add, sub, mul, div): ")
num1 = raw_input("Enter first number: ")
num2 = raw_input("Enter second number: ")

intNum1 = int(num1)
intNum2 = int(num2)
if op == 'sum':
    print "The sum is: ", intNum1 + intNum2
elif op == 'sub':
    if intNum1 > intNum2:
        print "The subtraction is: ", intNum1 - intNum2
    else:
        print "The subtraction is: ", intNum1 - intNum2
elif op == 'mul':
    print "The product is: ", intNum1 * intNum2
elif op == 'div':
    print "The division is: ", intNum1 / intNum2
else:
    print "You entered an incorrect operation"

它非常适合我:)除了类型转换之外,我在这里没有看到任何问题。提供您提供的输入和相应的输出。您如何证明等式运算未被计算?我的意思是,通常这需要添加一个函数,即
def compare(val,target):打印“比较%r和%r”%(val,target);return val==target
然后将该函数放入
if
语句中并查找副作用(print语句)。顺便说一句,
print“您输入的操作不正确:%r”%(op,)
将更容易诊断早期比较失败的原因。