在Python中,**是指数运算符

WBOY
发布: 2023-08-20 23:10:30
转载
1562 人浏览过

在Python中,**是指数运算符

在本文中,我们将学习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 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)
登录后复制

Output

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>
登录后复制

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 arguments
newfunction(language_1="Python", language_2="Java", language_3="C++")
登录后复制

Output

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中文网其他相关文章!

相关标签:
来源:tutorialspoint.com
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板