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

Why am I not getting a global variable out of this funciton in Python?

Hello everyone.

I would like to know why this code does not print the variable:

def my_function():
    output = 'Hello'
    return output

my_function()
print (output)

It says output is not defined, so I presume this is not the right method to get a global variable output from that function.

Obviously if I replace the last 2 lines with this:

print(my_function())

I get the string printed, but I need to "generate" global variables that I can reuse

How should I sort this out?

Thanks

Vittorio

PS Kenneth Love as I see you are online ;)

2 Answers

Kenneth Love
STAFF
Kenneth Love
Treehouse Guest Teacher

So, global means the variable is available in all scopes. Returning a variable from a function doesn't make that variable available in all scopes (thank goodness!). If you want the output variable's value to be used outside of the function, you need to assign the function call to a variable.

def my_function():
    output = 'Hello'
    return output

output = my_function()
print(output)
Kenneth Love
Kenneth Love
Treehouse Guest Teacher

Also, notice I didn't actually tell you how to make a global variable. Globals are pretty heavily discouraged in Python :)

Ok Kenneth, thanks.

In fact I had a look at the videos so far when trying to understand this and we haven't used it.

I will try to do it without global variables then.

May I ask why are these discouraged in Python?

ty

Kenneth Love
Kenneth Love
Treehouse Guest Teacher

We haven't used what? We've used return values a lot, and we'll keep using them. Globals? no, we haven't.

They're discouraged because they're harder to track down and keep in-mind. If I only have to deal with the variables that I've defined and passed into a function, I have less to keep in mind.