如何使函数从Python函数外部获取变量?

Gam*_*r01 2 python variables function while-loop python-3.x

所以我刚开始编写代码,将询问用户,他们希望有一个测试,是多么困难,他们希望它是什么主题,然后,很明显,给他们的考验.我创建了一个检查它是什么测试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())
Run Code Online (Sandbox Code Playgroud)

问题是,easy_CS()无论输入变量是什么,函数都会被激活.我可以为test变量输入"JFAWN",为变量输入"JDWNA" difficulty,它仍然会打印"HEY".我如何使它实际上取得变量,或者我怎样才能使它按照预期的方式工作?

For*_*Bru 6

这是因为您自己调用此函数.请看这里的括号?他们称之为功能:

which_test("easy", "computer science", easy_CS())
                                       ^^^^^^^^^^
Run Code Online (Sandbox Code Playgroud)

你打算做什么:

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 ^^^^^^
Run Code Online (Sandbox Code Playgroud)

所以,没有括号 - 没有函数调用.