在Python中,我们知道算术运算符可以用于对两个变量进行加法、减法、除法和乘法等操作。

在本文中,我们将学习如何在计算表达式时以精确的形式扩展运算符的功能。

让我们来看一些示例,这些示例将帮助我们清楚地理解增强赋值表达式的用法。

我们将讨论以下表达式 -

  1. +=
  2. -=
  3. *=
  4. /=
  5. %=
  6. **=
  7. //=
  8. >>=
  9. <<=
  10. &=

我们将看看涉及增强赋值表达式的程序,并了解它们如何使用。

1. 使用 +=

在下面的程序中,我们进行了以下操作 -

  1. 首先,我们添加了两个变量x和y。
  2. 使用增强赋值加法来将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. 使用 -=

在下面的程序中,我们进行了以下操作 -

  1. 首先,我们从两个变量x和y中减去了。
  2. 使用增强赋值减法来减去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. 使用 *=

在下面的程序中,我们进行了以下操作 -

  1. 首先,我们将两个变量x和y相乘。
  2. 使用增强赋值乘法来将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. 使用 /=

在下面的程序中,我们进行了以下操作 -

  1. 首先,我们将两个变量x和y相除。
  2. 使用增强赋值除法来将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. 使用 %=

在下面的程序中,我们进行了以下操作 -

  1. 首先,我们计算了两个变量x和y的模数。
  2. 使用增强赋值模数操作来获取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. 使用 **=

在下面的程序中,我们进行了以下操作 -

  1. 首先,我们计算了x的y次方。
  2. 使用增强赋值表达式来计算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. 使用 //=

在下面的程序中,我们进行了以下操作 -

  1. 首先,我们计算了x和y的整数除法的值。
  2. 使用增强赋值表达式来计算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之间的按位与操作。

示例 -

#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中使用增强赋值表达式。

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程