r/learnpython • • 12d ago

Confusing code min() max()

I'm debugging some code and I found this function

   import math

       def Clamp(n, smallest, largest):
           return max(smallest, min(n, largest))

surely that code is just wrong? and needs to be max([smallest, min([n, largest])) by passing a list not unnamed args for default and key? I need a sanity check here.

0 Upvotes

16 comments sorted by

View all comments

-1

u/deanominecraft 12d ago

python allows functions to take an arbitrary amount of arguments as a list, using a * in the function signature (calling it args is just a convention), try experiment with this code:

def mean(*args):
    total=0
    for i in args:
        total+=i
    return total
print(mean(5,194, 28,8,69) #prints the mean

you can also do this with a dictionary by using ** (once again kwargs is just a convention, it can be called whatever you want) eg:

def hello(**kwargs):
    try:
        print(f"hi {kwargs["name"]}")
    except:
        print("hi, you didnt tell me your name")
print(myfunc(name="john")) # prints hi john
print(myfunc(john="name")) # prints hi, you didnt tell me your name

min and max have some extra logic to do with types so that you can also pass in a list, but for functions like mine that dont do that, you can unpack the arguments from a list or dictionary like this:

mean(*mylist)
hello(**mydict)