2014-05-20 79 views
0

所以我是新來編碼(從Python開始),我試圖做一個超級簡單/基本的計算器。我已經遇到了這個問題,然後在另一組代碼,我不明白爲什麼。即使它是假的,代碼行也會返回true。所以說我把100除以5,對於「*」和「乘法」,它返回的結果是500,而不是正確的答案,它應該是20.如果有人能解釋/顯示爲什麼它返回true而不是false?如果語句一直返回true

def calculator(): 
    Number_input_one = int(raw_input("Enter your first number: ")) 
    Math_symbol = raw_input("What do you want to do? ") 
    Number_input_two = int(raw_input("Enter your second number: ")) 

    if Math_symbol == "*" or "Multiply": 
     print Number_input_one * Number_input_two 
    elif Math_symbol == "/" or "Divide": 
     print Number_input_one/Number_input_two 
    elif Math_symbol == "+" or "Add": 
     print Number_input_one + Number_input_two 
    elif Math_symbol == "-" or "subtract": 
     print Number_input_one - Number_input_two 
    else: 
     print "it doesn't match anything!" 
+0

請注意,「lowercase_names」通常用於Python變量,而「UpperCamelCase」通常用於類。 –

+0

還請記住正確縮進您的代碼。我假設你的代碼沒有縮進錯誤。 –

回答

4

你正在一個典型的錯誤:

if Math_symbol == "*" or "Multiply": 

沒有做什麼,你認爲它。正確的版本是:

if Math_symbol in ("*", "Multiply"): 

你的代碼的版本正在做的是檢查if Math_symbol == "*"或者"Multiply"存在(即它不是一個空字符串)。這將始終評估爲True,因爲字符串"Multiply"確實存在。需要爲其他if陳述

類似更正:

if Math_symbol in ("*", "Multiply"): 
    print Number_input_one * Number_input_two 
elif Math_symbol in ("/", "Divide"): 
    print Number_input_one/Number_input_two 
elif Math_symbol in ("+", "Add"): 
    print Number_input_one + Number_input_two 
elif Math_symbol in ("-", "subtract"): 
    print Number_input_one - Number_input_two 
else: 
    print "it doesn't match anything!" 
+0

工作!謝謝。 – ThatPythonNoob

0

你想math_symbol == "-" or math_symbol == "subtract"

聲明 「弦」 始終判斷爲真

1

你也可以試試這個:

if (Math_symbol == "*") or (Math_symbol=="Multiply"): 

elif (Math_symbol == "/") or (Math_symbol == "Divide"): 

等等!