Python 什么是** 运算符

Python 什么是** 运算符

在本文中,我们将学习 Python 中的 ** 运算符。

双星号 (**) 是 Python 中的一种算术运算符(就像 +、-、*、**、/、//、%)。它也被称为幂运算符。

算术运算符的优先级是什么

算术运算符和数学运算符的规则相同,按照以下顺序运行:先运行指数运算,然后是乘法和除法,最后是加法和减法。

以下是按照降序使用的算术运算符的优先级顺序 –

() >> ** >> * >> / >> // >> % >> + >> -

使用双星(**)运算符的用途

使用**作为指数运算符

它也被用于数字数据中执行指数运算

示例

以下程序示例了在表达式中使用**运算符作为幂运算符:

# 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)

输出

执行以上程序后,将生成以下输出 –

result_1:  16
result_2:  30

**作为函数和方法的参数使用

双星号在函数定义中也被称为**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++")

输出

执行以上程序后,将生成以下输出:

My favorite language_1 is Python
My favorite language_2 is Java
My favorite language_3 is C++

我们可以使用**kwargs来轻松地在我们的代码中使用关键字参数。最好的部分是,当我们将**kwargs作为参数时,可以向函数传递大量的参数。创建接受**kwargs的函数最好在参数列表中的输入数量预计较小的情况下使用。

结论

本文向我们介绍了Python的**操作符。我们学习了Python编译器中运算符的优先级,以及如何利用**操作符,它的功能类似于kwargs,并且可以接受任意数量的函数参数,也可以用来计算幂。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程