Optional parameter in function

Asked

Viewed 2,858 times

3

I was trying to create a square root function:

def root(n, ind):
    if ind == None:
        ind = 2
    ind2 = 1 / ind
    print(n ** ind2)

I want the ind not be mandatory.

I thought if I didn’t, the value would turn None (so I put if ind == none, ind = 2, in order to transform the ind in 2).

Is there any way, or is it impossible? Even with another way than def.

1 answer

6


Has. You just need to assign, next to the function setting, the value the parameter will receive by default.

def root(n, ind = 2):
    ind2 = 1 / ind
    print(n ** ind2)

So, call yourself root(10, 5), n will be worth 10 and ind will be worth 5; call only root(10), the value of ind will be 2, because it is the default value. It is worth noting that the optional parameters at all times should be after the required parameters. That is, the above is possible, but do something like:

def root(ind = 2, n):
    ...

Will give syntax error.

Syntaxerror: non-default argument Follows default argument

Browser other questions tagged

You are not signed in. Login or sign up in order to post.