简体   繁体   中英

If i have a function “def func(*args):” how can i return 0

I want to create a function that can receive some arguments, any number of them and return either the difference between the biggest number and the smallest number, but if there is nothing passed it returns 0.

This is what I have.

def x(*args):
    return max(*args) - min(*args)

I know that this doesnt include the returning 0 bit but I have tried a few different things that havent worked thus far.

Attempt 1:

def x(*args):
    if args == None:
         return 0
    else:
        return max(*args) - min(*args)

this doesn't work as I assume that not passing anything to *args doesnt pass None .

I also tried

def x(*args):
    if *args:
        return max(*args) - min(*args)
    else:
        return 0

that didnt work either.

I am super confused and am not sure what to do.

The function needs to be able to take any number of arguments in the form of integers and floats. The practice examples I have received are:

x(1,2,3,4,6) == 5
x(2,2,6,4,9,8,7,5,9) == 7
x() == 0

args will be an empty tuple if no arguments were passed. That can be used to return 0 in that case.

def x(*args):
    return max(args) - min(args) if args else 0

If no arguments are passed, then args will be empty

Just define a function as such:

def arg_range(*args):
    if args: return max(args) - min(args)
    else: return 0
def x(*args):
    return len(args) and max(args) - min(args)

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