在本文中,我们将学习Python中的**运算符。
Double Star (**)是Python中的算术运算符(如+,-,*,**,/,//,%)。幂运算符是它的另一个名称。
The rules for both Arithmetic operators and Mathematical operators are same, which are as follows: exponential is run first, followed by multiplication and division, and then addition and subtraction.
Following are the priority orders of arithmetic operators used in decreasing mode −
() >> ** >> * >> / >> // >> % >> + >> -
它也以在数值数据中执行指数运算而闻名
以下程序使用 ** 运算符作为表达式中的幂运算符 −
# using the double asterisk operator as an exponential operator x = 2 y = 4 # getting exponential value of x raised to the power y result_1 = x**y # printing the value of x raised to the power y print("result_1: ", result_1) # getting the resultant value according to the # Precedence of Arithmetic Operators result_2 = 4 * (3 ** 2) + 6 * (2 ** 2 - 5) print("result_2: ", result_2)
On executing, the above program will generate the following output −
<font face="Liberation Mono, Consolas, Menlo, Courier, monospace"><span style="font-size: 14px;">result_1: 16 result_2: 30</span></font>
双星号在函数定义中也被称为**kwargs。它用于将可变长度的关键字字典传递给函数
我们可以使用下面示例中显示的小函数打印**kwargs参数:
下面的程序展示了在用户定义的函数中使用kwargs的方法 -
# creating a function that prints the dictionary of names. def newfunction(**kwargs): # traversing through the key-value pairs if the dictionary for key, value in kwargs.items(): # formatting the key, values of a dictionary # using format() and printing it print("My favorite {} is {}".format(key, value)) # calling the function by passing the any number of arguments newfunction(language_1="Python", language_2="Java", language_3="C++")
On executing, the above program will generate the following output −
My favorite language_1 is Python My favorite language_2 is Java My favorite language_3 is C++
我们可以通过**kwargs在我们的代码中轻松使用关键字参数。最好的部分是,当我们将**kwargs作为参数使用时,可以向函数传递大量的参数。当预计参数列表中的输入数量相对较少时,创建接受**kwargs的函数是最好的选择。
This article taught us about Python's ** operator. We learned about the precedence of operators in the Python compiler, as well as how to utilize the ** operator, which functions like a kwargs and may accept any amount of arguments for a function and is also used to calculate the power.
以上是在Python中,**是指数运算符的详细内容。更多信息请关注PHP中文网其他相关文章!