Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

Is there a way to create a set variable from within a function?

Is there a workaround to keep a variable that I have set within a function? eg.

def poke(cactus):
    if cactus == "prickly":
        pain = True
    elif cactus == "smooth"
        pain = False
    if cactus == "wet"
        thirst = False

Is there any way to have the 'pain' variable stay True outside of the function, without explicitly writing it outside the function?

cactus = "prickly"
poke(cactus)
if pain == True:
    print("ow")

obviously this doesn't work if it isn't within the function. And return() doesn't seem like it will do the job without a mess. But with a longer list of elifs and multiple potential variables, it would be great to have a way to do this within the function to keep the process organized.

[MOD: aded ```python markdown formatting -cf]

Variables which exist outside of a function are called global variables. They exist across everything no matter where you are. Take a look at this link about How to set a global variable within a function:

Here's a snippet:

def f():

      global x # this is the explicit global declaration
      print x # try to print the global
      ...
      for j in range(100):
           if q > 3:
              x=4

Notice you have to insert a explicit global declaration at the start of the function. From there forth in the function, anything you right will be considered global so be conscious of encapsulation.

As always, if this helped, please vote best answer. Happy coding :)

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

Outside the function, pain is a global variable. To change this value from within the function, the local pain variable must be declared global.

def poke(cactus):
    global pain, thirst
    # ...

A better approach would be to use a return statement to pass the value back.

def poke(cactus):
    if cactus == "prickly":
        pain = True
    elif cactus == "smooth"
        pain = False
    if cactus == "wet"
        thirst = False
    return pain

cactus = "prickly"
pain = poke(cactus)  # <-- assign global pain output of poke()
if pain == True:
    print("ow")

if you also need to return thirst, you can return multiple items:

def poke(cactus):
    # ...
    return pain, thirst

pain, thirst = poke(cactus)

Thanks! But assuming there were a few more elifs, and each pointed to a different variable (thirst, pain, joy, mescaline_high, etc.) and you didn't know which variable would be used, how would you return one but not all, and how would you select that variable?

? = poke(cactus)
Chris Freeman
Chris Freeman
Treehouse Moderator 68,468 Points

Your question goes both ways, if the function doesn't know which variable to return how would the code following the call to poke know what adjective to test for?

After the call to poke will there be many if statements to test all of the possible return values to choice which print to issue?

You haven't reached object oriented programming yet, so I'll hold off on suggesting you define a class object.

One option is to move the prints into the poke function:

def poke(cactus):
    if cactus == "prickly":
        print("ow")
    # ...

The logic of your code needs to defined more clearly. What is the main objective of poke? Articulating the objective in a sentence can reveal what the code should look like.

How is the value of cactus chosen for the call to poke?

This is just example code -- I am trying to make a dialogue simulator within a text-game, where different keywords in phrases would trigger different responses in dialogue as well as trigger events. But I think maybe I should learn some more basics first.