在 Python 中,我們知道如何使用算術運算符來加、減、除和乘兩個變量。
在本文中,我們將學習如何在計算表達式時以精確的形式擴展運算符的功能。
讓我們看幾個例子,讓我們清楚擴充賦值表達式的使用。
我們將討論以下表達式-
- +=
- -=
- *=
- /=
- %=
- **=
- //=
- <<=
- &=
我們將看一下包含複合賦值表達式的程序,並了解如何使用它們。
1.使用+=
在下面給出的程序中,我們完成了以下操作-
- 首先,我們添加了兩個變量 x 和 y。
- 用複合賦值加法來加 x 和 5。
示例-
#adding two numbers x and y
x=15
y=10
z=x+y
print("Value of z is: ",z)
x+=5 #x=x+5
print("Value of x is: ",x)
輸出
Value of z is: 25
Value of x is: 20
2.使用-=
在下面給出的程序中,我們完成了以下操作-
- 首先,我們減去了兩個變量 x 和 y。
- 用複合賦值減法減去 x 和 5。
示例-
#subtracting two numbers x and y
x=15
y=10
z=x-y
print("Value of z is: ",z)
x-=5 #x=x-5
print("Value of x is: ",x)
輸出
Value of z is: 5
Value of x is: 10
3.使用*=
在下面給出的程序中,我們完成了以下操作-
- 首先,我們將兩個變量 x 和 y 相乘。
- 用複合賦值乘法將 x 和 5 相乘。
示例-
#multiplying two numbers x and y
x=15
y=10
z=x*y
print("Value of z is: ",z)
x*=5 #x=x*5
print("Value of x is: ",x)
輸出
Value of z is: 150
Value of x is: 75
4.使用/=
在下面給出的程序中,我們完成了以下操作-
- 首先,我們劃分了兩個變量 x 和 y。
- 用複合賦值除法來除 x 和 5。
示例-
#dividing two numbers x and y
x=15
y=10
z=x/y
print("Value of z is: ",z)
x/=5 #x=x/5
print("Value of x is: ",x)
輸出
Value of z is: 1.5
Value of x is: 3.0
5.使用%=
在下面給出的程序中,我們完成了以下操作-
- 首先,我們取了兩個變量 x 和 y 的模。
- 用複合賦值模運算得到 x 和 5 的結果。
示例-
#modulus of two numbers x and y
x=15
y=10
z=x%y
print("Value of z is: ",z)
x%=5 #x=x%5
print("Value of x is: ",x)
輸出
Value of z is: 5
Value of x is: 0
6.使用**=
在下面的程序中,我們執行了以下操作-
- 首先,我們計算了 x 的冪 y。
- 使用擴充賦值表達式計算 x 的 3 次方。
示例-
#power of two numbers x and y
x=15
y=2
z=x**y
print("Value of z is: ",z)
x**=3 #x=x**3
print("Value of x is: ",x)
輸出
Value of z is: 225
Value of x is: 3375
7.使用//=
在下面的程序中,我們執行了以下操作-
- 首先,我們計算了 x 和 y 的整數除法的值。
- 用複合賦值表達式計算 x 和 3 的整數除法。
示例-
#integer division of two numbers x and y
x=15
y=2
z=x//y
print("Value of z is: ",z)
x//=3 #x=x//3
print("Value of x is: ",x)
輸出
Value of z is: 7
Value of x is: 5
8.使用> >=
在下面的程序中,我們計算了變量 x 和 y 之間按位右移的表達式。
示例-
#bitwise right shift on two numbers x and y
x=15
y=2
x>>=y
print("Value of x is: ",x)
輸出
Value of x is: 3
9.使用< < =
在下面的程序中,我們計算了變量 x 和 y 之間按位左移的表達式。
示例-
#bitwise left shift on two numbers x and y
x=15
y=2
x<<=y
print("Value of x is: ",x)
輸出
Value of x is: 60
10.使用&=
在下面的程序中,我們計算了變量 x 和 y 之間按位 and 移位的表達式。
示例-
#bitwise and on two numbers x and y
x=15
y=2
x&=y
print("Value of x is: ",x)
輸出
Value of x is: 2
因此,在本文中,我們學習了如何在 Python 中使用複合賦值表達式。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/248783.html