Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Python Basics Functions and Looping Returning Values

when to use result and return in def function?

Can someone help me to explain the purpose of result and return in the def function?

When do we use them?

1 Answer

Shahid khan
Shahid khan
790 Points

Hello Gia, Function is block of code that do certain task in your program. Let's see a simple example

def cal_age(birth_year){ my_age = 2019 - birth_year print(my_age) } In above function we are calcaluting my age. we passed an argument birth_year(ex:1996 my birth_year) now in my_age varivable your calcaluting my age by subtracting it from current year.Now if you want to print the result of the function just print it inside fuction body.When you call the function you will see the my_age gets printed to the console. cal_age(1996) it will print 23 to the console.

now if you want return the value form a function we need to use the return keyword.

def cal_age(birth_year){ my_age = 2019 - birth_year return my_age }

now this function will return the calcaluted value of my_age. It will not print anything on the console when you call the function. To print the value of my_age you need to enclose the function with print statement like this print(cal_age(1996)) or you can use a varivable to store the function return value like this

age = cal_age(1996) print(age) // 23 prints to console