首页 > 编程知识 正文

Python 中的复合赋值表达式

时间:2023-11-26 13:13:06 阅读:309320 作者:HRZW

在 Python 中,我们知道如何使用算术运算符来加、减、除和乘两个变量。

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

让我们看几个例子,让我们清楚扩充赋值表达式的使用。

我们将讨论以下表达式-

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

我们将看一下包含复合赋值表达式的程序,并了解如何使用它们。

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 之间按位 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 中使用复合赋值表达式。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。