简体   繁体   English

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

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

So I've just started to program code that will ask the user what subject they want to have a test on and how difficult they want it to be, and then, obviously, give them that test. 因此,我刚刚开始编写代码,该代码将询问用户他们想要在哪个主题上进行测试以及他们想要进行多困难,然后,显然可以给他们进行测试。 I created a function for the if statement that checks what test it is and how difficult it should be, and I just made a random, throwaway function to test the code. 我为if语句创建了一个函数,用于检查它的测试内容以及测试的难度,并且我刚刚制作了一个随机的,一次性的函数来测试代码。 I'll show you the code (obviously very early-alpha and nowhere near finished) and then I'll explain the problem. 我将向您展示代码(显然是早期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())

The problem is, the easy_CS() function gets activated no matter what the input variables are. 问题是,无论输入变量是什么, easy_CS()函数都会被激活。 I could input "JFAWN" for the test variable and "JDWNA" for the difficulty variable and it would still print "HEY". 我可以为test变量输入“ JFAWN”,为difficulty变量输入“ JDWNA”,它仍然会显示“ HEY”。 How do I make it so that it actually takes the variables, or how could I make it so that it just works the way it's intended to? 如何使它真正地接受变量,或者如何使它按预期方式工作?

This is because you call this function yourself. 这是因为您自己调用了此函数。 See the parentheses here? 在这里看到括号了吗? They call the function: 他们调用该函数:

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

What you meant to do: 您的意思是:

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 ^^^^^^

So, no parentheses - no function call. 因此,没有括号-没有函数调用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM