在本文中,我们将学习python中的**运算符。
double star (**)是python中的算术运算符(如+,-,*,**,/,//,%)。幂运算符是它的另一个名称。
what order/precedence do arithmetic operators take?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 ** as exponentiation operator:它也以在数值数据中执行指数运算而闻名
example以下程序使用 ** 运算符作为表达式中的幂运算符 −
# using the double asterisk operator as an exponential operatorx = 2y = 4# getting exponential value of x raised to the power yresult_1 = x**y# printing the value of x raised to the power yprint(result_1: , result_1)# getting the resultant value according to the# precedence of arithmetic operatorsresult_2 = 4 * (3 ** 2) + 6 * (2 ** 2 - 5)print(result_2: , result_2)
outputon executing, the above program will generate the following output −
result_1: 16result_2: 30
using **as arguments in functions and methods:双星号在函数定义中也被称为**kwargs。它用于将可变长度的关键字字典传递给函数
我们可以使用下面示例中显示的小函数打印**kwargs参数:
example下面的程序展示了在用户定义的函数中使用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 argumentsnewfunction(language_1=python, language_2=java, language_3=c++)
outputon executing, the above program will generate the following output −
my favorite language_1 is pythonmy favorite language_2 is javamy 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中,**是指数运算符的详细内容。