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

Alternate Function

Why do I need to use return function when I can just use print function to print the value.

Why do I need to write , return (cost_per_person)

and again write a print function . Is it not letting us create smelly code, because I feel we are repeating ourselves . Is there any specific reason to do so or can we just use print in def body so that we don't have to write another line of code.

1 Answer

Jeff Muday
MOD
Jeff Muday
Treehouse Moderator 28,716 Points

*The practice of a functional programming style is a good thing to learn in the early phases of your Python journey. * Functional programming focuses on making functional units that are encapsulated, stateless, and without side effects. One value goes in, a new one comes out-- the original value should not be affected. Printing is sometimes considered a side effect of a function, I'll explain...

A print statement shows a user a computation, but (for the most part) the computer itself can't read what you printed. The "return" shares a value that can be used to print or log at a more appropriate point, and make further computations.

When you embark on a development career, your programs will become very compex and will be broken down into many modules, you will also be required to write unit tests (that the computer tests your code) much like the automated grader does at Treehouse. The computer won't be able to read these screen-print statements, but wants to examine values and data structures.

Also, you will write functions that will be reused by others. A good library will not chatter to the screen or console rather it will produce logging messages-- the user then can decide how they want to use or supress the messages.

Another consideration is "internationalization" of your code. By keeping printing centralized, you can have the ability to have a configuration set in one location and then pull your standardized print messages from the appropriate language "hive".

I hope this helps you understand why your teachers might be insisting on functions returing values. I've learned many important things from Kenneth and Craig (and others at Treehouse) on how to teach the material and dedication to best practices that will serve well in your future career!