2016-10-04 105 views
-2

在下面的代碼中,我如何在'結束'函數中爲我提供變量'guesses'。每當我嘗試這個,我只是收到一個猜測未定義。在play函數中,我返回一個數字,如果我理解正確的數字應該等於「猜測」,並且由於某種原因我不明白'猜測'在'結束'中不起作用。如何在另一個函數中使用main變量?

def main(): 
    guesses = play() 
    play_again = again() 
    while (play_again == True): 
     guesses = play() 
     play_again = again() 
     total_games = 1 
     total_games += 1 
    end() 


def end(): 
    print("Results: ") 
    print("Total: " + print(str(guesses + 1))) 
+1

我覺得你的縮進拼寫錯誤 –

+0

把它作爲一個參數。 –

回答

0

只需通過guesses作爲參數傳遞給end()

def main(): 
    guesses = play() 
    play_again = again() 
    while (play_again == True): 
     guesses = play() 
     play_again = again() 
     total_games = 1 
     total_games += 1 
    end(guesses) 

def end(guesses): 
    print("Results: ") 
print("Total: " + str(guesses + 1)) 

或者另一種選擇(雖然我不建議這樣做,除非你知道你在做什麼),是主要猜測全球。

guesses = None 

def main(): 
    global guesses 
    guesses = play() 
    play_again = again() 
    while (play_again == True): 
     guesses = play() 
     play_again = again() 
     total_games = 1 
     total_games += 1 
    end() 

def end(): 
    print("Results: ") 
print("Total: " + str(guesses + 1)) 

並注意,我修復了您的打印報表。您不需要使用打印兩次來打印傳入print()參數的數據。

5

把它作爲一個參數

def main(): 
    guesses = play() 
    play_again = again() 
    while (play_again == True): 
     guesses = play() 
     play_again = again() 
     total_games = 1 
     total_games += 1 
    end(guesses) 

def end(guesses): 
    print("Results: ") 
    print("Total: " + str(guesses + 1)) 

傳遞作爲參數的輸入,並使用return傳遞變量出爲輸出,可以控制數據流的程序,而不是使用global變量一個柺杖。

+1

唉拍!你打了幾秒鐘。儘管如此... + 1 –

+1

print(print())會有一些奇怪的行爲。因爲它不會按要求工作。 –

+0

@MikeMcMahon好的,我沒有仔細查看代碼的其餘部分 – CoryKramer

2

事情是這樣的:

def main(): 
    guesses = play() 
    play_again = again() 
    while (play_again == True): 
     guesses = play() 
     play_again = again() 
     total_games = 1 
     total_games += 1 
    end(guesses) 

def end(guesses): 
    print("Results: ") 
    print("Total: {}".format(guesses + 1)) 
2

main()end()是兩個單獨的功能與獨立的範圍。您在函數main()內定義了變量guesses。它不可用於end(),因爲end()的定義範圍無法訪問guesses。儘管在main()內調用了end()這一事實。在創建/定義end()時,函數的內部並不知道guesses存在。

當您試圖做的事情時,需要在兩個函數之間傳遞信息突出了對數據流的一個非常常見的編程範例的需求。您可以通過使用「參數」或「參數」將信息傳遞到函數中。這些是調用函數時定義或設置的變量。

在Python中,他們是這樣的:

def function(argument): 
    #do something with argument 
    print (argument) 
+0

好的解釋! [教導OP釣魚]可能是一個好主意(https://en.wiktionary.org/wiki/give_a_man_a_fish_and_you_feed_him_for_a_day ;_teach_a_man_to_fish_and_you_feed_him_for_a_lifetime)。 +1 –

相關問題