python中 += 语法的意思和使用

+= 是python中的缩略写法,意思其一是:

两个值相加,然后返回值赋值给符号左侧的变量

a = a + b 等同于 a +=b

+=的写法中间不能有空格,否则报错,测试如下:

>>> a = 1
>>> b = 2
>>> a = a + b
>>> a
3
>>> a = 1
>>> b = 2
>>> a +=b
>>> a
3
>>> a = 1
>>> b = 2
>>> a += b
>>> a
3
>>> a + = b               # +=的写法中间不能有空格,会报错
  File "", line 1
    a + = b
        ^
SyntaxError: invalid syntax
>>> a + =b
  File "", line 1
    a + =b
        ^
SyntaxError: invalid syntax
>>> a+ =b
  File "", line 1
    a+ =b
       ^
SyntaxError: invalid syntax

+= 另一种使用是:

用于字符串链接(变量值带引号,数据类型为字符串)

>>> a = '1'
>>> b = '2'
>>> a+=b
>>> a
'12'

你可能感兴趣的:(Python,python)