在Python中,**是指數運算符

WBOY
發布: 2023-08-20 23:10:30
轉載
1569 人瀏覽過

在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 gumount of operator, which functions like a kwargs and may accept gumount of operator, which functions like a kwargs and may acceptargu for may acceptar guil for 鞋function and is also used to calculate the power.

以上是在Python中,**是指數運算符的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板