## Parameters of python| function

parameters python function

Welcome to click 「 Beauty of algorithm and programming 」↑ Pay attention to our ！

Welcome to the team ！ Face to face with the author ！ Just click ！

Preface

When defining a function , We just need to determine the name and location of the parameter , The interface definition of the function is finished .

Positional arguments

stay power(x) in ,x This is the position parameter , Calling this parameter has and only one parameter

seek x² Function of , The code is as follows ：

 >>>def  power(x):return x * x

When there are multiple parameters , take power(x) Change it to power(x,n), It includes two parameters x and n, And both parameters are positional parameters , When you call a function , The two values passed in are assigned to the parameter in order of position x and n

seek x Of n Power , The code is as follows ：

 >>>def power(x, n):     s = 1     while n > 0:         n = n - 1         s = s * x     return s

Default parameters

1、 Because we often calculate x², So we can take the second parameter n The default value of is set to 2, namely n=2 Is the default parameter

 >>>def power(x, n=2):     s = 1     while n > 0:         n = n - 1         s = s * x     return s

When n>2 when , You need clear input n Value , Such as ：power(x,100)

2.、 When setting default parameters , There are two points to pay attention to ：

First, the required parameters are in front of , The default parameter is after .

The second is how to set the default parameters ： When a function has more than one parameter , Put the variable parameters ahead , Change small parameters behind . The parameter with small change can be used as the default parameter .

Variable parameters

Variable parameter is that the number of parameters passed in is variable

When we determine the input parameters , The code is as follows ：

 >>>def calc(numbers):     sum = 0     for n in numbers:         sum = sum + n * nreturn sum>>> calc([1,2,3])14

When we change the parameter to a variable parameter , The code is as follows ：

 def calc(*numbers):     sum = 0     for n in numbers:         sum = sum + n * n     return sum>>>calc(1,2)5

END

Lord   Ed    |    Wang Nanlan

responsibility   Ed    |    Li Xiaohuan

The stronger the ability , The greater the responsibility . Seeking truth from facts , Rigorous and meticulous Cause .

——where2go The team

WeChat ID ： Beauty of algorithm and programming

Long press identification QR code to follow us !

reminder ： Click on the bottom right corner of the page “ Write a message ” Comment , Looking forward to your participation ！ Looking forward to your forwarding ！