Back to community
Computer ScienceClass 11 (CBSE) Resolved

How is return different from print inside a Python function?

When I write a function I sometimes use print and sometimes return and both seem to show the answer. But my teacher says they are not the same. Why does it matter?

Asked by Priya Nair 37 45d ago
Need a Computer Science tutor? Browse verified Computer Science tutors near you.

1 answer

Accepted answer
5

print only displays a value on screen for a human to read, it does not give the value back to the program. return sends a value back to whoever called the function so it can be stored or reused. Example: a function with 'return a + b' lets you write 'total = add(2, 3)' and total becomes 5, which you can use later. If the function used 'print(a + b)' instead, it shows 5 but 'total = add(2, 3)' makes total equal to None, because nothing was returned. Rule of thumb: use return when the result will be used further in the program, and print only when you simply want to show something. Functions that calculate should almost always return.

R
Rahul Deshmukh
375 pts· 45d ago

Sign in as a tutor to answer this doubt.