[Tutor] Requesting help

Alan Gauld alan.gauld at yahoo.co.uk
Sun Apr 3 19:37:16 EDT 2022


On 03/04/2022 17:20, Eleejay 1O1 wrote:

> I'm trying to understand returning values and returning values using
> functions. 

They are the same. You can only return values from functions.

> I do understand the role of functions

Functions have many roles but the two most important are
1) To improve readability(and thus maintenace) of your code
2) to make common algorithms reusable thius saving typing and
duplication of code(and therefore of errors)

> return using functions throws me off. Can you help me with this?

return terminates a function. If a value is added then that value is
returned to the caller of the function. Otherwise None is returned to
the caller.

The other role of 'return' is to return control to the calling code. A
function can be thought of a small independane program that runs inside
another one. While the function is executing the outer calling code
stops and waits for the function to complete. The return statement
signals that control returns to the external code.

This dual role of 'return'' can confuse beginners but really the two
things are the same thing. The function terminates and hands back
control and its terminal value to the caller.

def aFunction(some, parameters, here):
    code_that_uses_the_parameters_here()
    return aValue  # to the caller

#call the function
myValue = aFunction(1,2,3)  # some=1,parameters=2,here=3
print(myValue)  # prints whatever value myFunction returned.

We use builtin functions and their return values all the time

total = sum([1,2,3,4])
print(total)  # total = 10

sum() is a builtin unction that takes a sequence of values,
adds them together and returns the result.

myname = input("Enter your name")
size = len(myname)
print(myname,"is ", size, "chars long")

input() is a builtin function that takes a prompt string
    parameter, reads a string from the keyboard and returns
    that string to the caller
len() is a builtin function that takes an object and works
    out its length (for some definition of length) and returns
    it to the caller.
print() is a builtin function that takes a variable number
    of parameters and converts them to strings before
    sending them to the stdout stream. It doesn't return
    a value to the caller so its result is the default, None.

Your user defined functions are just like the builtin
functions. There is no real differnce to Python.

HTH
-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list