2014-03-02 37 views
-6

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

+ =, - =,* =和/ =

立場在Python?你如何使用它循環?

+0

他們是速記的運營商。 – thefourtheye

+0

我認爲[你需要一本編程書籍](http://openbookproject.net/thinkcs/python/english3e/)讓你比現在更進一步。 – JFA

+0

嗨,既然你是新人,你應該知道,如果你接受一個答案(點擊最好回答你的問題的答案旁邊的複選標記),你會得到+2代表。不多,但是這是一些東西。 –

回答

0

即不僅蟒,也就是在大多數編程語言

X = 1的; x + = 1; x將是2

x = 1; x- = 1; x將爲0

x = 3; x * = 2; x將是6

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

0

他們正在執行的操作,然後將其分配到變量:

a += b是相同的a = a + b

a -= b是相同的a = a - b

a *= b是一樣a = a * b

a /= b與相同

您可以在while循環以同樣的方式使用它們,你將使用擴展形式:

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

很肯定這是教師如何「早在天」會處理這個問題:

i = 2 
while i != 1: 
    print "I will first do basic research." 
    i += 1 
    i *= 1 
    i /= 1 
    i -= 1 
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; 
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