[Tutor] Function question

Alan Gauld alan.gauld at yahoo.co.uk
Sat Mar 25 07:17:29 EDT 2017


On 25/03/17 10:01, Peter O'Doherty wrote:

> def myFunc(num):
>      for i in range(num):
>          print(i)
> 
> print(myFunc(4))
> 0
> 1
> 2
> 3
> None #why None here?

Because your function does not have an explicit return
value so Python returns its default value - None.
So the print() inside the function body prints the 0-3
values then the function terminates and returns the (default)
None to your top level print.

> def myFunc(num):
>      for i in range(num):
>          return i
> 
> print(myFunc(4))
> 0 #why just 0?

Because return always returns from the function immediately.
So you call the function, it enters the loop, sees the return for the
first element and exits. The print() then prints that returned value.

The preferred method to do what I think you were expecting is to build a
list:

def anotherFunction(num):
    result = []
    for i in range(num):
       result.append(i)
    return result

Which is more concisely written using a list comprehension but
that would hide the general point - that you should accumulate results
in a collection if you want to return more than a single value.

To print the result you would typically use the string.join()
method:

print(' '.join(anotherFunction(4))


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