Function passed as an argument returns none

Chris Kaynor ckaynor at
Thu Oct 2 00:45:56 CEST 2014


On Wed, Oct 1, 2014 at 3:37 PM, Shiva <shivaji_tn at>

> 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

Print actually prints the value, and does not return it.

Based off the rest of your code, you probably want this to look like

def donuts(count):
  if count <= 5:
    return 'Number of donuts: {}'.format(count) # You could also use other
formatting methods here, if you prefer the printf-style "%s" instead.
    return 'Number of donuts: many'

Which will cause donuts to return the actual string, rather than printing
it out to the TTY.

Note that this means that, if run from the interpreter as you have been
trying, the interpreter will now display "Number of donuts: 4" - including
the quotes.

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

If you do as mentioned above, donuts will then return the value, and it
will be passed into test.

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

donuts is, in fact, returning None when called alone. It merely looks like
it is returning it as, when run from the interpreter, Python prints the
"repr" of the return values of any non-None returns. This is known as a
REPL: read, execute, print, loop. It is quite handy for debugging.

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list