在Python中,+ =, - =,* =和/ =代表什么?

时间:2014-03-02 19:27:47

标签: python loops while-loop

是什么

  

+ =, - =,* =和/ =

代表Python?以及如何将它用于 while 循环?

5 个答案:

答案 0 :(得分:1)

这不仅仅是python,也就是大多数编程语言

X = 1; X + = 1; x将是2

X = 1; X- = 1; x将为0

X = 3; X * = 2; x将是6

X = 6; X / = 2; x将是3

答案 1 :(得分:1)

这些(+=-=*=/=)称为augmented arithmetic assignments。它们对应于以下方法:

object.__iadd__(self, other)
object.__isub__(self, other)
object.__imul__(self, other)
object.__idiv__(self, other)

i在语义上的意思是“就地”,这意味着他们修改对象(或数字的情况下的引用),而不必另外分配它们:

while condition:
    foo += bar

相当于:

while condition:
    foo = foo + bar

答案 2 :(得分:0)

他们正在执行操作,然后将其分配到变量中:

a += ba = a + b

相同

a -= ba = a - b

相同

a *= ba = a * b

相同

a /= ba = a / b

相同

您可以在while循环中使用它们,方法与使用扩展表单的方式相同:

i = 0
while i < 5:
    print i
    i += 1   # The same of i = i + 1

答案 3 :(得分:0)

非常肯定这就是教师“回到白天”会如何处理这个问题:

i = 2
while i != 1:
   print "I will first do basic research."
   i += 1
   i *= 1
   i /= 1
   i -= 1

答案 4 :(得分:0)

这些是操作员分配缩写:

Operator symbol       Name of the operator    Example     Equivalent construct 

          +=           Addition assignment        x += 4;     x = x + 4;
          -=           Subtraction assignment     x -= 4;     x = x - 4;
          *=           Multiplication assignment  x *= 4;     x = x * 4;
          /=           Division assignment        x /= 4;     x = x / 4;
          %=           Remainder assignment       x %= 4;     x = x % 4;