Function passed as an argument returns none

Rustom Mody rustompmody at gmail.com
Wed Oct 1 22:29:33 EDT 2014


On Thursday, October 2, 2014 4:07:44 AM UTC+5:30, Shiva wrote:
> Hi,
> I am learning Python (version 3.4) strings.I have a function that takes in a
> parameter and prints it out as given below.

> def donuts(count):
>   if count <= 5:
>     print('Number of donuts: ',count)
>   else:
>     print('Number of donuts: many')
>     return

> It works fine if I call 
> donuts(5)

> It returns:
> we have 5 DN  (as expected)

> However if I do :

> test(donuts(4), 'Number of donuts: 4')

> where test is defined as below:

> def test(got, expected):
>   print('got: ', got, 'Expected:' ,expected)
>   if got == expected:
>     prefix = ' OK '
>   else:
>     prefix = '  X '
>   print (('%s got: %s expected: %s') % (prefix, repr(got), repr(expected)))

> Only 'None' gets passed on to parameter 'got' instead of the expected value
> of 4.
> Any idea why 'None' is getting passed even though calling the donuts(4)
> alone returns the expected value?

Others have given you the correct python-technicalities answer: 

print ≠ return

However given your starting point – I am learning Python – let me try 
a less technical one.

You start from the assumption that your donuts returns 5, which it
seems to in some contexts and not in others.

So by now you know there are 2 kinds of return:

>>> def foo(x): return x+5
... 
>>> def bar(x): print(x+5)
... 
>>> foo(4)
9
>>> bar(4)
9


So they seem identical here, right?

But as you further discover bar is useless to do anything other than
being called at the command line, whereas foo can be used in all sorts of 
ways: in particular you can use foo to write bar:

def bar(x): print(foo(x))

But not conversely.

So the morals in short: 

1. Stick to the return that works -- python's return statement --
and avoid the return that seems to work -- the print statement
2. print is good for debugging code. When your code is bugfree it should have
few/no prints
3. The official tutorial/docs unfortunately foster bad habits in children by showing prints early --
Know better!



More information about the Python-list mailing list