This article introduces the usage of Python3 * and ** operators. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.
In Python, * and ** are grammatically ambiguous, specifically there are four types of usage.
1. Arithmetic operations
* represents multiplication
** represents exponentiation
>>> 2 * 5 //10 >>> 2 ** 5 //32
2. Function form Parameters
*args and **kwargs are mainly used for function definitions.
You can pass an unlimited number of arguments to a function. Uncertain means: you don’t know in advance how many parameters the function user will pass to you, so use these two keywords in this scenario. In fact, it is not necessary to write *args and **kwargs. *(asterisk) is required. You can also write *ar and **k. Writing *args and **kwargs is just a common naming convention.
There are two ways for python functions to pass parameters:
*args and **kwargs, both are variable parameters in python:
If you use *args and **kwargs at the same time, the *args parameter column must be before **kwargs.
>>> def fun(*args, **kwargs): ... print('args=', args) ... print('kwargs=', kwargs) ... >>> fun(1, 2, 3, 4, A='a', B='b', C='c', D='d') //args= (1, 2, 3, 4) //kwargs= {'A': 'a', 'B': 'b', 'C': 'c', 'D': 'd'}
Use *args
>>> def fun(name, *args): ... print('你好:', name) ... for i in args: ... print("你的宠物有:", i) ... >>> fun("Geek", "dog", "cat") //你好: Geek //你的宠物有: dog //你的宠物有: cat
Use **kwargs
>>> def fun(**kwargs): ... for key, value in kwargs.items(): ... print("{0} 喜欢 {1}".format(key, value)) ... >>> fun(Geek="cat", cat="box") //Geek 喜欢 cat //cat 喜欢 box
3. Function actual parameters
If the formal parameters of the function It is a fixed-length parameter. You can also use *args and **kwargs to call functions, similar to dereferencing tuples and dictionaries:
>>> def fun(data1, data2, data3): ... print("data1: ", data1) ... print("data2: ", data2) ... print("data3: ", data3) ... >>> args = ("one", 2, 3) >>> fun(*args) data1: one data2: 2 data3: 3 >>> kwargs = {"data3": "one", "data2": 2, "data1": 3} >>> fun(**kwargs) data1: 3 data2: 2 data3: one
4. Sequence unpacking
Sequence Unpacking I have written about it in previous blogs. Here is only one example. There is no ** in sequence unpacking.
>>> a, b, *c = 0, 1, 2, 3 >>> a 0 >>> b 1 >>> c [2, 3]
Related free learning recommendations: python video tutorial!
The above is the detailed content of What is the usage of * and ** operators in Python3. For more information, please follow other related articles on the PHP Chinese website!