在Python中,可以同时给多个变量赋值。这种方法通常称为赋值或多变量赋值。以下是一些例子: 1. 直接赋值: a, b, c = 1, 2, 3 print(a) # 输出: 1 print(b) # 输出: 2 print(c) # 输出: 3 2. 通过列表或元组赋值: values = [4, 5, 6] a, b, c = values print(a) # 输出: 4 print(b) # 输出: 5 print(c) # 输出: 6 3. 同时给所有变量赋予同样的值: a = b = c = 7 print(a) # 输出: 7 print(b) # 输出: 7 print(c) # 输出: 7 4. 使用字典为多个变量赋值: person = {'name': 'Alice', 'age': 25, 'city': 'New York'} name, age, city = person['name'], person['age'], person['city'] print(name) # 输出: Alice print(age) # 输出: 25 print(city) # 输出: New York 请注意,多变量赋值时,等号两边的元素数量必须匹配,否则会引发`ValueError`错误。 #如何学习编程# #编程杂谈# #编程经验# #编程观点# #分享编程技巧# ![]() |
|