2017-09-25 107 views
2

所以我刚刚开始编写代码,询问用户他们想要进行测试的主题以及他们希望实现的难度,然后显然给他们做测试。我为if语句创建了一个函数,用来检查它是什么样的测试以及它应该是多么困难,并且我只是做了一个随机的一次性函数来测试代码。我会告诉你代码(显然非常早 - 阿尔法并且没有完成)然后我会解释这个问题。如何使一个函数从Python的函数外部获取变量?

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”。我该如何做到这一点,才能真正接受变量,或者我怎样才能做到这一点,以便它按照预期的方式工作?

+0

使用全局变量应该会有帮助! –

+3

你在错误的地方调用函数。你需要移动引起它在'which_test'内调用的圆括号,所以你传递*函数*,而不是它的*结果*。 @ChetanVasudevan这是很少,如果真的。 – jonrsharpe

+0

@chetanvasudevan你为什么会建议使用'global'?这里没有必要。 – roganjosh

回答

6

这是因为你你自己调用这个函数。在这里看到括号?他们调用函数:

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

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

相关问题