🚀 author: “Big Data Zen”

🚀 : This column is about python, from the basics to the advanced. You are welcome to subscribe.

🚀 Fan benefit: Join the big data community of Xiaochan

🚀 Welcome to like 👍, collect ⭐, leave a message 💬

Core Python parameters and variables

What are parameters and arguments?
  • Parameters: formal parameters. Acceptable parameters specified when a function is defined are parameters, such as Max (a,

B) A and b in the function are parameters

  • Arguments: the actual arguments that are passed to the function when the function is called, such as the above function

The arguments 1 and 9 in Max (1, 9) are arguments;

What are positional parameters
  • After we define the function Max (a,b), when we call it, we don’t need to specify the parameter name, just Max (1,9), which takes the argument

In the function, a=1,b=9.

  • Of course, if we don’t want to use positional order, we can also specify the corresponding parameter name, such as Max (b=9,a=1)

After the call, the values are not assigned in the order of the input arguments, but are assigned directly to the specified parameter names.

Default parameters for core basics

Write a function that computes x to the NTH power, requiring that x and n can be passed in as arguments

def power(x, n) :
return x ** n
print(power(2.2))
Copy the code

The above function solved the problem, but obviously not perfect, assuming that in most of the calls, basically just take x to the 2nd power, but at this point I still have to pass n every time in the call, which is a little redundant. Is there any way I can call with one less input parameter?

  • If we print(power(2)), we will find that it will not work.

At the function entry, assign the default argument with an equal sign,

def power(x, n=2) :
return x ** n
print(power(2))
Copy the code

Note that the required parameter is in front of the default parameter, otherwise an error will be reported

  • What if there are multiple default arguments?
def test(a=1, b=2, c=3) :
print("a=%d b=%d c=%d" % (a, b, c))
test(c=2)
Copy the code

When there are multiple default parameters, you can explicitly specify the value of a parameter to be passed in. When calling a function, the input parameter takes the form of parameter name = parameter value

  • What if the default argument is a list?
def test(L=[]) :
   L.append("END")
print(L)
test([1.1.1])
test([2.2.2])

Copy the code
  • The above program seems to work without any problems, but let’s look at a strange phenomenon

The test function is called with no arguments, and the output gets a little weird

def test(L=[]) :
L.append("END")
print(L) test() test()'END']
['END'.'END'] is defined with a fixed value for the default argument. In other words, the address to which L refers is fixed. If the contents of the function are changed later, the value of the default argument also changesCopy the code

Variable parameters of core basic knowledge

What is a variable parameter?

As the name implies, the number of arguments passed when calling a function is variable. If you do not use mutable parameters, how can you pass an indefinite number of lists, dict, and sets

def sum(numbers) :
total = 0
for i in numbers:
 total += i
return total
print(sum([1.2.3]))

y=[1.2.3Switch to (1.2.3) Print the same resultfor x in y:
    print(x) output:6
1
2
3
Copy the code

In this way, although it can achieve an indefinite number of input parameters, but the caller does not know what type the input parameter should be. In this case, the caller has to depend on the specific implementation of the function to know that the input parameter is an iterable type, so it is not friendly to the caller

  • When defining a function, an asterisk (*) is used to indicate a variable parameter, such as
def sum(*numbers) :
total = 0
for i in numbers:
 total += i
return total
print(sum(1.2.3)) output:6
Copy the code

A variable parameter encapsulates an input parameter into a tuple

def my_fun(*numbers) :
 print(type(numbers))

 total = 0
 for i in numbers:
  total += i
 return total

print(my_fun(1.2.3) output result: <class 'tuple'>
6

Copy the code

Named keyword arguments for core basics

Let’s start by looking at the most common way to enter arguments — positional arguments
def person(name, age) :
 print(name,age)
person("wiggin".29)

Copy the code

In this way, you do not need to specify the name of the input parameter, as long as the location corresponds to it. As an alternative to positional arguments, you must specify the name of the argument, the named keyword, every time you call it

What are named keyword arguments?

The restriction caller cannot be passed positional and needs to be placed after the parameter, separated from the normal parameter by an asterisk * (an exclusive parameter bit) in front of it

Why do you have named keyword arguments? To restrict the last few parameters to being passed as keywords, this is usually because the last several parameters have very obvious meanings. Or the latter parameters are likely to change from version to version, and enforcing the keyword form helps ensure cross-version compatibility

An alternative to positional arguments is that each call must specify the name of the argument, namely named keyword ** named keyword usage

def person(name, age, *, pet) :
 print(name,age,pet)
person("wiggin".29,pet="tomcat")

Copy the code

Name the keyword with * as the separator, * before the parameter, based on the location parameter, note!! * After the parameter, in the call must specify the parameter name, once using the name of the shutdown word, if not specified parameter name, will report the corresponding error

def person(name, age, *, pet) :
 print(name,age,pet)
person("wiggin".29."tomcat")
TypeError: person() takes 2 positional arguments but 3 were given

Copy the code

* The following parameters can also be set using default parameters

def person(name, age, *, pet="cat"):
print(name,age,pet)
person("wiggin",29)

Copy the code

Special note: If a variable argument is already in the function definition, the following named keyword argument does not require a special separator

Keyword arguments for core basics

What are keyword arguments?
Def person(name, age, **kw) def person(name, age, **kw) def person(name, age, **kw) Print ('name:', name, 'age:', age, 'other:', kw) person("wiggin",29,city=" guangzhou ",pet="cat") name: wiggin age: 29 other: {'city': 'guangzhou ', 'pet': 'cat'}Copy the code

You can also pass parameters in the following way

def person(name, age, **kw) :
 print('name:', name, 'age:', age, 'other:', kw)
other_info = {"pet": "cat"}
person("wiggin".29,city="Guangzhou"**other_info) output: name: wiggin age:29 other: {'city': 'guangzhou'.'pet': 'cat'}

Copy the code

To pass all key-values of the dict other_info to ****kw, kw gets a dict. Note that the dict obtained by KW is a copy of other_info. Changes to KW do not affect other_info outside the function.

Mixing parameters The various types of parameters learned earlier in this chapter can be mixed when defining functions. However, there is a core caveat: When mixing parameters, the order of definition must be: Mandatory parameters, default parameters, variable parameters, named keyword parameters, and keyword parameters.