Is there a way to return literally nothing in python?

Question:

I’m learning python and I was just wondering if I there was a way to write a code that does something like:

def f(x):
    if x>1:
       return(x)
    else:
        # don't return anything

I’m asking about the else part of the code. I need to not return anything if x<=1, returning None isn’t acceptable.

Asked By: Kirca

||

Answers:

To literally return ‘nothing’ use pass, which basically returns the value None if put in a function(Functions must return a value, so why not ‘nothing’). You can do this explicitly and return None yourself though.

So either:

if x>1:
    return(x)
else:
    pass

or

if x>1:
    return(x)
else:
    return None

will do the trick.

Answered By: Sinkingpoint

There is no such thing as “returning nothing” in Python. Every function returns some value (unless it raises an exception). If no explicit return statement is used, Python treats it as returning None.

So, you need to think about what is most appropriate for your function. Either you should return None (or some other sentinel value) and add appropriate logic to your calling code to detect this, or you should raise an exception (which the calling code can catch, if it wants to).

Answered By: Blckknght

You can do something like this:

>>> def f(x):
...    return x if x>1 else None
... 
>>> f(1),f(2)
(None, 2)

It will appear to ‘return nothing’:

>>> f(1)
>>> 

But even the alternative returns None:

>>> def f2(x): 
...    if x>1: return x
... 
>>> f2(1),f2(2)
(None, 2)

Or:

>>> def f2(x):
...    if x>1: 
...        return x
...    else:
...        pass
... 
>>> f2(1),f2(2)
(None, 2)

So they are functionally the same no matter how you write it.

Answered By: dawg

How about this?

def function(x):
     try:
         x = x+1
         return (x)
     except:
         return ('')
Answered By: Josef

You can use lambda function with filter to return a list of values that pass if condition.

Example:

    myList = [1,20,5,50,6,7,2,100]
    result = list(filter(lambda a: a if a<10 else None, (item for item in myList)))
    print(result)

Output:

    [1,5,6,7,2]
Answered By: Swetha Varikuti

There’s nothing like returning nothing but what you are trying to do can be done by using an empty return statement. It returns a None.

You can see an example below:

if 'account' in command:
    account()

def account():
    talkToMe('We need to verify your identity for this. Please cooperate.')
    talkToMe('May I know your account number please?')
    acc_number = myCommand()
    talkToMe('you said your account number is '+acc_number+'. Is it right?')
    confirmation = myCommand()
    if confirmation!='yes' or 'correct' or 'yeah':
        talkToMe('Let's try again!')
        account()
    else:
        talkToMe('please wait!')
    return

This will return nothing to calling function but will stop the execution and reach to the calling function.

Answered By: Hrishikesh Shukla

As mentioned above by others, it will always return None in your case. However you can replace it with white space if you don’t want to return None type

def test(x):
    if x >1:
        return(x)
    else:
        return print('')
Answered By: Sumit Singh

I may have a tip for you !
Writing print(f(x)) will output None if there is no return value, but if you just call your function without the ‘print’, and instead write in the function some ‘print(s)’ you won’t have a None value

Answered By: The L

you can use
return chr(0)
cause 0 in ASCII doesn’t have a character hence it leaves it blank

Answered By: Omar Ayman

Just to add to all the answers, the only actual way to not return a function is to raise an exception. At least, as long as the program needs to run even after not returning anything.

So your code can be:

def f(x):
    if x>1:
        return x
    raise Exception

(Note that I didn’t use an else block to raise the Exception since it would have already returned the value if the condition was satisfied. You could, however, do this in an else block, too)

On test running:

num1 = f(2)    # 2
num2 = f(0)    # Unbound; and error raised

Now this can be useful if you want to also keep returning None an option for some conditions, and not returning anything for some other conditions:

def f(x):
    if x > 0:
        return x
    elif x == 0:
        return None  # pass
    raise Exception

>>> num1 = f(1)  # 1
>>> num2 = f(0)  # None
>>> num3 = f(-1) # Unbound; and error raised

If you don’t want the program to exit and show an error, you can make it catch the exception outside of the function:

try:
    num = f(0)
except:
    pass

This way, if at all f(0) raises an exception (which it would) it will be caught be the except block and you can happily continue the program, being rest assured that num is not None, but simply unbound.


An interesting fact:

The only other way to not return anything is probably to simply exit the program, which is what exit() and quit() do. When I check the return type for exit() and quit() in my code editor, it shows me NoReturn, which is different from when it shows None for a regular function 🙂

Answered By: a_n

In Simple Terms

for i in range(0,10):
    if i<5:
        None
    else:
       print("greater")

Output:-

greater
greater
greater
greater
greater

The code outputs nothing for all values less than 5.

Answered By: Shahad

To get a blank result from return statement just type return "" . You will just a get a blank line in the end without anything printed on it

def f(x):
    if x>1:
       return(x)
    else:
        return ""
Answered By: Avinash Singh

There are two methods and the former method returns None as explicitly stated in the latter:

def fn1():
    pass

def fn2():
    return None

fn1() == fn2()
True

My personal preference is always for explicit methods, as it reduces mental overhead.

Answered By: Adam Erickson
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.