0

Output for:

def test(c):
    if c == 4:
       return None
    return 'test'

returns 'test' given anything I put in such as test(500) but when I try test(4) the function simply skips and pretends I never ran it, but I want it to show None. So,

>> test(500)
'test'
>> test(4)
>>

is what happens. My goal is for a None to return without having to use print in the function:

>> test(4)
None

Help!

Sundrah
  • 785
  • 1
  • 8
  • 16
  • 5
    But it does return `None`. It just happens to not show that to you, but the return value is indeed `None`. – univerio May 09 '15 at 02:47
  • @univerio How can I get it to show in the output? – Sundrah May 09 '15 at 02:48
  • You can confirm it's returning None by doing `print test(4)` then you'll see the `None` return value that is there as others have indicated – Eric Renouf May 09 '15 at 02:48
  • The title of my canonical doesn't mention this specific case, but the Q&A covers it. (The title is already quite long, so I couldn't figure out a way to work it in.) The general question is about *how the REPL handles the result of expressions*; it doesn't print `None` results, but it does print others. – Karl Knechtel Jan 28 '23 at 21:31

3 Answers3

3

It is returning None. Nothing is printed, because the output shows the result, which is None, which is nothing, so it is not shown.

holtc
  • 1,780
  • 3
  • 16
  • 35
2

It is returning None. If you want to see that this is true without putting print in the method definition, you can do this:

print test(4)
> None
leekaiinthesky
  • 5,413
  • 4
  • 28
  • 39
1

None is the result returned by things that "don't return anything", like list.sort or the Python 3 print function. If an expression you type at the interactive prompt evaluates to None, Python won't automatically print it, since it thinks you probably called a "doesn't return anything" function, and it would be confusing to have sessions like

>>> l = [3, 2, 1]
>>> l.sort()
None
>>> print(l)
[1, 2, 3]
None

If you want to print it anyway, you need to explicitly print it.

user2357112
  • 260,549
  • 28
  • 431
  • 505