2017-04-18 27 views
0

當我試圖向op輸入任何值時,總是執行else語句。爲什麼我的編程沒有正確執行? if語句沒有被評估,它直接跳轉到Python中的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" 
+0

它適用於我:) –

+0

除了類型轉換,我沒有看到任何問題。提供您給出的輸入和相應的輸出 – sbk

+0

您如何證明**不評估相等操作?我的意思是,通常情況下需要添加一個函數,比如。 '比較(val,target):print「比較%r和%r」%(val,target);返回val == target',然後將這個函數放在你的'if'語句中並尋找副作用(print語句)。 –

回答

1

這是工作的罰款,如果你輸入你想先那麼這兩個數字操作,也需要投typped爲整數的數字:

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" 

Try it here

相關問題