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 的作用,可以接受函式的任意數量的引數,也可用於計算冪。
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP