1

I need a way to get the value of a variable that was defined in a function outside of that function. It's not necessary but would make my code so much easier to follow. Haven't found any solid answers to this yet.

def pizzais():
  pizza = "yummy"

pizzais()
print(pizza)

this will return an error saying that pizza is not defined. Is there any hack to get around this.

Too better understand my situation here is my code I'm applying it too.

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()
Shniper
  • 854
  • 1
  • 9
  • 31
  • 2
    Why would you "hack"? This is what `return` is for. – tzaman Apr 08 '16 at 00:21
  • 2
    what part in the wall of code are we supposed to be looking at to better understand your question? Where is your issue? – Keatinge Apr 08 '16 at 00:30
  • Basically I want to be able to use race, pClass, username outside of questions() – Shniper Apr 08 '16 at 00:32
  • @Shniper I created a [chat room](https://chat.stackoverflow.com/rooms/108583/chat-with-shniper) if you want to ask more questions. – tzaman Apr 08 '16 at 03:10

4 Answers4

2

Two ways to do this, one recommended and one not so much. You should not mess around with global variables unless you know what you're doing. What you are trying to do should 100% use a return. But to be inclusive I put it in because it could theoretically accomplish what you're trying to do.

Best Practice: Using A Return

def pizzais():
  return "yummy"

pizza = pizzais()
print(pizza)

Bad Idea: Using Global Variables

pizza = ""

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


pizzais()

print(pizza)

Returning Multiple Variables

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
Keatinge
  • 4,330
  • 6
  • 25
  • 44
  • so if i have several variables in a function and return each variable in the function how can I get the value of each of those variables outside of the function? – Shniper Apr 08 '16 at 00:24
  • return a tuple of multiple variables – Keatinge Apr 08 '16 at 00:25
  • 2
    Technically, `global` is the opposite - it's using a variable defined *outside* the function inside it. – tzaman Apr 08 '16 at 00:26
  • Okay I think I understand your problem. What you really should do is create a character class which can hold all this information. Then in your questions function you create a new character and return it in the function. – Keatinge Apr 08 '16 at 00:31
  • @tzaman I'm still running into a problem but don't want to post a new question on the same topic is there a way I can get in touch with you? or even share a pastebin? – Shniper Apr 08 '16 at 03:03
2

You should probably read through the Tutorial section on functions - this is just about the most basic thing you use functions for.

Your code sample is a giant mess, but here's a quick example of what you seem to be trying to do:

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

Repeat for your other options, then you can do something like:

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

There's much more cleanup that could be done, but this should get you started on a somewhat more sane structure.

tzaman
  • 46,925
  • 11
  • 90
  • 115
  • yeah i know it's a mess, I taught myself js and need to create a python game for one of my classes with very limited knowledge gained from the professor. So most of it is me playing around with how to turn js into python. Sorry – Shniper Apr 08 '16 at 00:40
  • 1
    The second snippet is not valid since `class` is not a valid variable name – Francisco Apr 08 '16 at 00:43
1
  1. Return multiple values in a tuple return x, y, z and unpack the return value like x, y, z = func().
  2. You can use global variables. While setting values inside a function first declare global x and then x = something. But global variables are best avoided.
  3. If you find yourself changing global state a lot, using a class is more appropriate.
  4. You can use closures to maintain state. But that needs a different design and you should do it if you are comfortable with higher order functions. Closures are in principle lightweight and much faster than classes(Beazly).
C Panda
  • 3,297
  • 2
  • 11
  • 11
0

You're trying to print pizza but what is pizza? You haven't defined it anywhere except for in your function and you're not returning anything. It's a local variable whereas trying to print pizza outside of the scope of your function is looking for a global variable. You can check out this question for local vs. global variables. You could set pizza = pizzais() and then do print(pizza) if you set return "yummy" at the end of your function. Without using return at the end of your function it will return None by default.

Community
  • 1
  • 1
Pythonista
  • 11,377
  • 2
  • 31
  • 50