给多个变量赋值,常规做法是这样:
# 商品名称
name = '巧克力礼盒'
# 价格
price = 118
# 重量
weight = 250.00
如果使用列表,就可以让我们在两行代码中搞定赋值:
product = ['巧克力礼盒', 118, 250.00]
name2, price2, weight2 = product
print('name2 = ' + name2)
print('price2 = ' + str(price2))
print('weight2 = ' + str(weight2))
运行结果:
name2 = 巧克力礼盒
price2 = 118
weight2 = 250.0
注意: 变量的数量必须等于列表的长度, 否则会抛出 ValueError 异常:
product = ['巧克力礼盒', 118, 250.00]
name3, price3, weight3, place3 = product
运行结果:
ValueError: not enough values to unpack (expected 4, got 3)