Optional function parameter

2

I tried to create a square root function:

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

I want ind not to be mandatory.

I thought that if I did not put it, the value would become None (so I put if ind == none, ind = 2 , so I can turn ind into 2).

Is there any way, or is it impossible? Not even in a different way without being def .

    
asked by anonymous 13.03.2018 / 21:52

1 answer

5

Tem. All you have to do is assign the value that the parameter will receive by default.

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

So, if you call root(10, 5) , n will be worth 10 and ind will count 5; if you call only root(10) , the value of ind will be 2, because it is the default value. It is worth mentioning that the optional parameters should always be after the required parameters. That is, as above is possible, but do something like:

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

It will give syntax error.

  

SyntaxError: non-default argument follows default argument

    
13.03.2018 / 21:55