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
behar
10,800 Pointsreturning something to a function?
So say i have the following function:
def add():
print("test")
I can call that function by doing add() and it will just print the test
Now say that i want to return something to that function:
def add2():
print("test")
return 2 + 2
While still being able to just call the function and get the test, how would i find what i returned to the function, that is the 2+2??
1 Answer
Jennifer Nordell
Treehouse TeacherHi there! You don't return to a function. You return from a function.
And you understand how to run a function, so that's good. So let's take a look at your example, but let's remove the print of the "test":
def add2():
return 2 + 2
This example function will only ever return the number 4. That number is returned to the call site where you tell the function to execute. So if you had this:
def add2():
return 2 + 2
print(add2())
The add2() would return a 4 and that is what would be printed.
Or you could assign it to a variable for use later like this:
result = add2()
In this case, the 4 is returned to where the add2() is and it is assigned to the variable result.
Hope this helps!
behar
10,800 Pointsbehar
10,800 PointsYes, im with you on that, i dont think i explained it well enough. My problem is i have the following code:
Now outside of this function i want to make an if statement that contains the first_or_second variable. But python dosent see the variable outside the function. So how would i go about getting that variable outside of that function and use it in a loop?
My idea here was to try to use the return first_or_second and then somehow use whatever was returned by the function.
Remember that i still need to be able to just run the function normally.
Jennifer Nordell
Treehouse TeacherJennifer Nordell
Treehouse TeacherThe answer is to return the value of
first_or_second. I think this is what you're shooting for:It's important to understand that the value returned is going to be substituted in place where the call to the function is:
HwoBegins()runs the function. A value is returned to that spot. It is then compared to 1.Hope this helps!
behar
10,800 Pointsbehar
10,800 PointsYea i dont know why that confused me so much! But got it now, ty so much again!