如何在另一个函数中使用main中的变量?

时间:2016-10-04 19:15:12

标签: python

在下面的代码中,如何在'end'函数中使用变量'猜测'。每当我尝试这个,我只是收到猜测没有定义。在播放函数中,我返回一个数字,如果我理解正确,那么该数字应该等于'猜猜',并且由于某种原因我不理解'猜测'将不会在'结束'中起作用。

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

4 个答案:

答案 0 :(得分: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 :(得分: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 :(得分:2)

main()end()是两个具有不同范围的独立函数。您在函数guesses中定义了变量main()end()无法使用它,因为end()定义的范围无法访问guesses。尽管在end()内调用main()这是事实。在创建/定义guesses时,函数内部无法识别end()

在尝试执行时,需要在两个函数之间传递信息,这突出了对数据流非常常见的编程范例的需求。您可以通过使用“parameters”或“arguments”将信息传递给函数。这些是在调用函数时定义或设置的变量。

在python中,它们看起来像这样:

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

答案 3 :(得分: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()参数的数据。