>>> name = 'zth'
>>> name
'zth'
>>> x,y,z = 1,2,3 # 多个赋值操作同时进行
>>> print(x,y,z)
1 2 3
>>>
>>>
>>> x,y = y,x #交换两个或多个变量的值
>>> print(x,y,z)
2 1 3
>>>
>>>
>>> nums = 1,2,3
>>> nums
(1, 2, 3)
>>> x,y,z = nums # 序列解包
>>> print(x,y,z)
1 2 3
>>>
>>>
>>>
>>> student = { 'name':'zth','age':20}
>>> key,value = student.popitem()
>>> key
'age'
>>> value
20
>>>
>>>
>>> x,y,z = 1,3 # 解包序列中的元素数和变量数不相等
Traceback (most recent call last):
File "", line 1, in
ValueError: not enough values to unpack (expected 3, got 2)
>>> x,y,z = 1,2,3,4
Traceback (most recent call last):
File "", line 1, in
ValueError: too many values to unpack (expected 3)
通过多个等式为多个变量赋同一值,这种方式叫作链式赋值。
>>> x = y = z = 10
>>> x
10
>>> print(x,y,z)
10 10 10
将表达式放置在赋值运算符 (=)的左边的赋值方式叫作增量赋值。
增量赋值对 * (乘)、/(除)、%(取模)等标准运算都使用。
增量赋值除了适用于数值类型,还适用于二元运算符的数据类型。
>>> x = 5
>>>
>>> x +=1 # x = x+1
>>> x
6
>>>
>>> x *=2 # x = x*2
>>> x
12
>>>
>>> x %=5 # x = x% 5
>>> x
2
>>>
>>>
>>>
>>> field = 'Hello'
>>>
>>> field += ' World'
>>> field
'Hello World'
>>>
>>> field *= 2
>>>
>>> field
'Hello WorldHello World'