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 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