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

Accessing variable in function from another function

Hello All,

I am struggling with accessing the variable in my game function from my play_again function. I played around with using global declaration, however, I don't want to edit it, I would like to call the variable in that specific function from another one. Can anyone give me tips for doing this? Specifically, I'm trying to call the max_score variable in line number 30 to use in 50.

My code: https://w.trhou.se/jskrvgc14m

1 Answer

Steven Parker
Steven Parker
231,007 Points

Variables defined inside a function are intentionally not available outside that function. This is part of what is known as scope rules.

But for what you want to use it for, it makes sense for this to be a global variable. Instead of creating inside the function, do it before the first function is called. Then it will be available to all functions.

Another way you could do this (but it would require more changes) is to pass it back as the return value from any function where it is changed, and pass it into any function that needs it as an argument.