2014-01-26 20 views
0

我是一名Python初學者,我已經開始編寫一個基本區域計算器(代碼如下所示)。我的想法是將每個形狀的計算代碼分離到它自己的函數中,然後讓if和elif語句根據用戶的輸入決定調用哪個函數。目前,我的程序只計算平方的面積(這個代碼位於平方函數中,都是正確的)。當我輸入「square」時,程序仍然運行else代碼!有人能幫助我理解我做錯了什麼嗎? (這是Python版本3.3.3,如果這有所作爲)。在Python中,當我有一個變量設置爲輸入,並且輸入匹配if語句時,爲什麼它仍然運行我的其他代碼?

def square(): 
    length = input("Please enter the length: ") 
    width = input("Please enter the width: ") 


def whole(): 

    area_product = int(length) * int(width) 

    print("The area of your rectangle is " + str(area_product) + " :)") 

def decimal(): 

    area_product = float(length) * float(width) 

    print("The area of your rectangle is " + str(area_product) + " :)") 


if float(length) % 1 == 0 and float(width) % 1 == 0: 
    whole() 

else: 
    decimal() 

choice = input("Please the select the shape that has the area you would like to calculate: ").lower() 


if choice == square: 
    square() 
else: 
    print("Sorry, the shape " + choice + " is not recognized. :(") 
+1

它運行'if' *或* else''。如果它運行'else',那麼'if'條件*失敗*,儘管相信 - 回去並檢查假設。 (PS的'width'和'length'變量集是'square'函數中的局部變量* - 在其他地方使用它們會產生問題。另外,'square'是一個函數,所以它永遠不會等於輸入..) – user2864740

+0

無論誰將其標記爲不可重現/印刷:這是可重複的,並且不是印刷錯誤。這是OP對Python語法理解的一個錯誤,但它不是一個錯字。 – Marcin

回答

4

choice永遠等於square,因爲square是函數(或更確切地說是square其值的變量是一個函數),的choice值是由input返回的類型,它是一個字符串的。因此,if下的部件永遠不會運行,而是運行else

你想要什麼,可能是if choice == 'square'。這是一個字符串,看看?

實際上,您可能想要做更復雜的事情,但這是解決此問題的方法。

+0

謝謝!這正是我需要的! :) – TimeWillTell

+0

@ user3236485不客氣。 – Marcin

相關問題