简体   繁体   中英

Python - How to get a function to actually return `None`?

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!

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM