Lefteris Kyprianou
Lefteris Kyprianou

Reputation: 327

How to get none if my function is called with no arguements in python?

Hey everyone i would like to ask how can I get null if my function is called with no arguments (sum_func())?

def sum_func(*args):
       k = 0
       for i in args:
           k += i
       return k

Thank you!

Upvotes: 1

Views: 840

Answers (3)

Jakub Szlaur
Jakub Szlaur

Reputation: 2132

I think you want to return None (not Null) if you don't pass any argument to the function, which can be done by checking the args as shown in the code below:

def sum_func(*args):
    if args:
        k = 0
        for i in args:
            k += i
        return k
    else:
        return None

print("With arguments:", sum_func(1, 2))
print("Without arguments:", sum_func())

Output:

With arguments: 3
Without arguments: None

Upvotes: 1

Krishna Chaurasia
Krishna Chaurasia

Reputation: 9572

You can check for nullity of argument args and return None as:

def sum_func(*args):
    if not args:
        return None

    k = 0
    for i in args:
        k += i
    return k

print(sum_func())
print(sum_func(2, 3))

Output:

None
5

You could also consider using ‘len(args)‘ and check if it is zero in case the input is of type boolean.

Upvotes: 3

Rambarun Komaljeet
Rambarun Komaljeet

Reputation: 646

if k!=0:
    return k

This is assuming you do not want to use count 0.

The function will return None if no return value given.

Upvotes: 0

Related Questions