By Timmy Telebrant via Discussions on Python.org at 06Sep2022 17:44:
I’m really trying to get me an picture in my head how this “Return
Value” in functions work, why and when we use them.
I’ve read on internet and in a book but still just can’t understand it. I mean we print stuff by using print() and we call functions by their name and as i am new to programming i simply cant understand why return value would be needed in a function to run the specific function.
In short, print()
writes text to your terminal. Your larger programme
doesn’t get to use it.
So this example:
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = first_name + ' ' + last_name
return full_name.title()
musician = get_formatted_name('jimi', 'hendrix')
print(musician)
calls get_formatted_name()
to get the titlecased name, and separately
prints it.
Your second example:
def get_formatted_name(first_name, last_name):
"""Return a full name, neatly formatted."""
full_name = first_name + ' ' + last_name
print(full_name.title())
get_formatted_name('jimi', 'hendrix')
calls get_formatted_name()
and that function does the print()
.
But where does print()
get the titlecased string? From
full_name.title()
, which itself is a function which returns a value
(does not print the value).
Generally, we write function to compute values. If your function just
prints that value to the terminal then nothing else can make use of it.
Look at this (untested):
from math import sqrt
G = 9.81 # acceleration due to gravity
def square(x):
''' x ^ 2 = x * x '''
return x * x
def hypotenuse(dx, dy):
''' h = √ (dx^2 + dy^2 ) '''
return sqrt( square(dx) + square(dy) )
def distance(start, start_v, accel, time):
''' d = start + start_v * t a * t^2 / 2 '''
return start + start_v * t + accel * square(time) / 2
def distance_to_projectile_fired_up_from_train(train_speed, fire_speed, time):
ground_distance = train_speed * time
height = distance(0, fire_speed, -G, time)
line_of_sight_distance = hypotenuse(ground_distance, height)
return line_of_sight_distance
print("The projectile is", distance_to_projectile_fired_up_from_train(10, 100, 8), "metres away after 8 seconds")
If each of these functions just wrote things to the terminal, there
would be no way to assemble them to compute
distance_to_projectile_fired_up_from_train
.
We generally separate output (such as print()
) from computation (the
functions), because a function can be reused for more complex tasks.
The IDLE Python prompt make this idstinction less clear:
>>> 3
3
>>> print(3)
3
because it does its own printing to make the results of expressions
(including function calls) visible.
Cheers,
Cameron Simpson cs@cskk.id.au