Python:获取函数中定义的变量的值,在该函数之外

时间:2016-04-08 00:19:23

标签: python

我需要一种方法来获取在该函数之外的函数中定义的变量的值。这没有必要,但会使我的代码更容易遵循。尚未找到任何可靠的答案。

def pizzais():
  pizza = "yummy"

pizzais()
print(pizza)

这将返回错误,说明没有定义披萨。是否有任何黑客可以解决这个问题。

太了解我的情况这里是我的代码我也在应用它。

def questions():
    user = input("What is your username?") #username
    race = input("What is your race? (orc, human, elf, goblin)") #race

#won't move on if the player fills an answer that is not an option
    if race == "orc" or race == "human" or race == "elf" or race == "goblin":
        pClass = input("What is your class? (archer, warrior, rogue or mage)")


    else:
        while race != "orc" and race != "human" and race != "goblin" and race != "elf":
            race = input("What is your race? (orc, human, elf, goblin)")
            if race == "orc" or race == "human" or race == "elf" or race == "goblin":
                pClass = input("What is your class? (archer, warrior, rogue or mage)")

#won't move on if the player fills an answer that is not an option               
    if pClass == "archer" or pClass == "warrior" or pClass == "rogue" or pClass == "mage":
            correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)")

    else:
        while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage":
            pClass = input("What is your class? (archer, warrior, rogue or mage)")
            if pClass == "archer" or pClass == "warrior" or pClass == "rogue" or pClass == "mage":
                correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)")

    def correct_def():
        correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)")
        if correct == "yes": #if player likes their choices the game will begin
            print("Enjoy the game " + user + "!")

        elif correct == "no": #if player doesn't like their choices all questions are asked again
            reAsk = input("What would you like to change?(username, race, class or all)")

        else:
            while correct != "yes" and correct != "no":
                correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)")
            if correct == "yes":
                print("Enjoy the game " + user + "!")

            elif correct == "no":
                questions()

    if correct == "yes": #if player likes their choices the game will begin
        print("Enjoy the game " + user + "!")

    elif correct == "no": #if player doesn't like their choices all questions are asked again
        reAsk = input("What would you like to change?(username, race, class or all)")

        if reAsk == "username":
            user = input("What is your username?")
            correct_def()

        elif reAsk == "race":
            race = input("What is your race? (orc, human, elf, goblin)")
            while race != "orc" and race != "human" and race != "goblin" and race != "elf":
                race = input("What is your race? (orc, human, elf, goblin)")
            correct_def()

        elif reAsk == "class":
            pClass = input("What is your class? (archer, warrior, rogue or mage)")
            while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage":
                pClass = input("What is your class? (archer, warrior, rogue or mage)")
            correct_def()

        elif reAsk == "all":
            questions()

        else:
            while reAsk != "username" and reAsk != "race" and reAsk != "class" and reAsk != "all":
                reAsk = input("What would you like to change?(username, race, class or all)")
                if reAsk == "username":
                    user = input("What is your username?")
                    print("Enjoy the game " + user + "!")

                elif reAsk == "race":
                    race = input("What is your race? (orc, human, elf, goblin)")
                    while race != "orc" and race != "human" and race != "goblin" and race != "elf":
                        race = input("What is your race? (orc, human, elf, goblin)")
                    print("Enjoy the game " + user + "!")

                elif reAsk == "class":
                    pClass = input("What is your class? (archer, warrior, rogue or mage)")
                    while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage":
                        pClass = input("What is your class? (archer, warrior, rogue or mage)")
                    print("Enjoy the game " + user + "!")

                elif reAsk == "all":
                    questions()

#won't move on if the player fills an answer that is not an option 
    else:
        while correct != "yes" and correct != "no":
            correct = input("So you are " + user + ", the " + race + " " + pClass + "? (yes or no)")
        if correct == "yes":
            print("Enjoy the game " + user + "!")

        elif correct == "no":
            reAsk = input("What would you like to change?(username, race, class or all)")

        if reAsk == "username":
            user = input("What is your username?")
            correct_def()

        elif reAsk == "race":
            race = input("What is your race? (orc, human, elf, goblin)")
            while race != "orc" and race != "human" and race != "goblin" and race != "elf":
                race = input("What is your race? (orc, human, elf, goblin)")
            correct_def()

        elif reAsk == "class":
            pClass = input("What is your class? (archer, warrior, rogue or mage)")
            while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage":
                pClass = input("What is your class? (archer, warrior, rogue or mage)")
            correct_def()

        elif reAsk == "all":
            questions()

        else:
            while reAsk != "username" and reAsk != "race" and reAsk != "class" and reAsk != "all":
                reAsk = input("What would you like to change?(username, race, class or all)")
                if reAsk == "username":
                    user = input("What is your username?")
                    print("Enjoy the game " + user + "!")

                elif reAsk == "race":
                    race = input("What is your race? (orc, human, elf, goblin)")
                    while race != "orc" and race != "human" and race != "goblin" and race != "elf":
                        race = input("What is your race? (orc, human, elf, goblin)")
                    print("Enjoy the game " + user + "!")

                elif reAsk == "class":
                    pClass = input("What is your class? (archer, warrior, rogue or mage)")
                    while pClass != "archer" and pClass != "warrior" and pClass != "rogue" and pClass != "mage":
                        pClass = input("What is your class? (archer, warrior, rogue or mage)")
                    print("Enjoy the game " + user + "!")

                elif reAsk == "all":
                    questions()
questions()

4 个答案:

答案 0 :(得分:2)

有两种方法可以做到这一点,一种是推荐的,另一种是推荐的。除非你知道自己在做什么,否则你不应该搞乱全局变量。你要做的是100%使用回报。但是为了具有包容性,我把它放入,因为它可以理论上完成你想要做的事情。

最佳做法:使用回报

def pizzais():
  return "yummy"

pizza = pizzais()
print(pizza)

错误主意:使用全局变量

pizza = ""

def pizzais():
  global pizza
  pizza = "yummy"


pizzais()

print(pizza)

返回多个变量

def get_three_variables():
    var1 = "text1"
    var2 = "text2"
    var3 = "text3"
    return (var1, var2, var3)


response = get_three_variables()
print(response)
#this prints: ('text1', 'text2', 'text3')

print(response[0])
#this prints text1

print(response[1])
#this prints text2

答案 1 :(得分:2)

你应该阅读Tutorial section on functions - 这只是你使用 函数的最基本的东西。

你的代码示例是一个巨大的混乱,但这里是你似乎想要做的一个简单的例子:

def ask_race():
    race = None
    options = ['orc', 'human', 'elf', 'goblin']
    while race not in options:
        race = input('What is your race? ({})'.format(','.join(options)))
    return race

重复其他选项,然后您可以执行以下操作:

def questions():
    race = ask_race()
    character_class = ask_class()

可以做更多的清理,但这应该让你开始更健全的结构。

答案 2 :(得分:1)

  1. 在元组return x, y, z中返回多个值,并将返回值解压缩为x, y, z = func()
  2. 您可以使用全局变量。在函数内设置值时,首先声明global x然后x = something。但最好避免全局变量。
  3. 如果您发现自己经常改变全局状态,使用class更合适。
  4. 您可以使用闭包来维护状态。但是这需要一个不同的设计,如果你对高阶函数感到满意,你应该这样做。闭包原则上是轻量级的,并且比类( Beazly )快得多。

答案 3 :(得分:0)

您正在尝试打印pizza,但披萨是什么?你没有在任何地方定义它,除了你的功能,你没有返回任何东西。它是本地变量,而尝试在函数范围之外打印披萨正在寻找全局变量。您可以查看此question以了解本地变量和全局变量。如果您在功能结束时设置pizza = pizzais(),则可以设置print(pizza)然后执行return "yummy"。在功能结束时不使用return,默认情况下会返回None