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
ronakeogh
30 PointsWhen to pass arguments into a function
Hello, I've been having some problems recently trying to write my own programs. I create functions where i declare a variable. I then attempt to pass this variable into another function and i always put it into the function as a parameter. When i go to run the program i get back an error message saying the variable is not defined.
an example of this is shown below, help would be hugely appreciated. Thanks. P.S im not sure why it is putting things on the same line when i upload the question but hopefully you get the general idea. :)
def name(): name = 'Bob'
def print_name(name): print(name)
name() print_name(name)
1 Answer
Steven Parker
243,656 Points
You're seeing the results of the concept called "scope".
When you define "name" inside the name function, it is only available inside the function. One way to make it available outside would be with return, as shown here:
def name():
name = 'Bob' # "name" is only available inside this function
return name # but we can return its value to the caller
print(name()) # this will print "Bob"
ronakeogh
30 PointsThanks this has helped a lot!
Steven Parker
243,656 PointsSteven Parker
243,656 PointsCode formatting instructions are in the Markdown Cheatsheet pop-up below the text entry area.