簡體   English   中英

如何使函數從Python中的函數外部獲取變量?

[英]How to make a function take variables from outside the function in Python?

因此,我剛剛開始編寫代碼,該代碼將詢問用戶他們想要在哪個主題上進行測試以及他們想要進行多困難,然后,顯然可以給他們進行測試。 我為if語句創建了一個函數,用於檢查它的測試內容以及測試的難度,並且我剛剛制作了一個隨機的,一次性的函數來測試代碼。 我將向您展示代碼(顯然是早期alpha版本,並且還沒有完成),然后我將解釋問題。

def which_test(real_dif, real_test, give_test):
    if difficulty == real_dif and test == real_test:
        give_test

def easy_CS():
    print("HEY")

while True:
    test = str(input("What test do you want to take? Computer Science, History or Music? ").strip().lower())
    difficulty = str(input("Do you want to take the test in easy, medium or hard? ").strip().lower())
    which_test("easy", "computer science", easy_CS())

問題是,無論輸入變量是什么, easy_CS()函數都會被激活。 我可以為test變量輸入“ JFAWN”,為difficulty變量輸入“ JDWNA”,它仍然會顯示“ HEY”。 如何使它真正地接受變量,或者如何使它按預期方式工作?

這是因為您自己調用了此函數。 在這里看到括號了嗎? 他們調用該函數:

which_test("easy", "computer science", easy_CS())
                                       ^^^^^^^^^^

您的意思是:

def which_test(real_dif, real_test, give_test):
    if difficulty == real_dif and test == real_test:
        give_test()  # call the function

# more code...
which_test("easy", "computer science", easy_CS))
             # pass the function itself ^^^^^^

因此,沒有括號-沒有函數調用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM