Fundamentals 9 min read

15 Common Python Variable Assignment Techniques

This article demonstrates fifteen practical ways to assign values to variables in Python, ranging from simple direct assignment and augmented operators to unpacking, dictionary unpacking, slicing, conditional expressions, and various comprehension forms, each accompanied by code examples and their outputs.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
15 Common Python Variable Assignment Techniques

Python is a dynamically typed language that allows flexible variable assignment. This article presents fifteen common methods for assigning values to variables, each illustrated with code snippets and their corresponding output.

1. Direct assignment

# 直接对变量赋值
a = 1
b = 2
c = 1
print("直接赋值后的变量值:")
print("a =", a)
print("b =", b)
print("c =", c)

Output shows the values of a, b, and c after direct assignment.

2. Augmented assignment

# 使用 +=、-=、*=、/= 等运算符来更新变量的值
a = 1
a += 2  # a = a + 2
a -= 1  # a = a - 1
a *= 3  # a = a * 3
a /= 2  # a = a / 2
print("增量赋值后的变量值:")
print("a =", a)

Output displays the final value of a after the series of augmented operations.

3. Multiple assignment

# 同时为多个变量赋不同的值
a, b = 1, 2
print("多重赋值后的变量值:")
print("a =", a)
print("b =", b)

Both a and b receive distinct values in a single statement.

4. Unpacking assignment

# 将一个序列(如列表、元组或字符串)的元素分别赋给多个变量
a, b, c = [1, 2, 3]
print("解包赋值后的变量值:")
print("a =", a)
print("b =", b)
print("c =", c)

The elements of the list are unpacked into a, b, and c.

5. Swapping variables

# 直接交换两个变量的值,而无需使用临时变量
a = 5
b = 10
a, b = b, a
print("交换变量值后的结果:")
print("a =", a)
print("b =", b)

Values of a and b are swapped without a temporary variable.

6. Assignment via function parameters

# 使用函数参数来为变量赋新值
def func(a):
return a * 2
a = func(1)
print("函数参数赋值后的变量值:")
print("a =", a)

The function returns a new value that is assigned to a.

7. Assignment with exception handling

# 使用异常处理来为变量赋新值
try:
a = 1 / 0
except ZeroDivisionError:
a = None
print("异常处理赋值后的变量值:")
print("a =", a)

If an exception occurs, a is assigned None.

8. Dictionary unpacking for multiple assignment

# 使用字典解包进行多重赋值
person = {'name': 'Alice', 'age': 25}
name, age = person.values()
print("字典解包赋值后的变量值:")
print("name =", name)
print("age =", age)

Values from a dictionary are unpacked into separate variables.

9. Assignment from function return values

# 使用函数返回值进行多重赋值
def get_info():
return 'Alice', 25
name, age = get_info()
print("函数返回值赋值后的变量值:")
print("name =", name)
print("age =", age)

The tuple returned by a function is unpacked into name and age.

10. Assignment using slicing

# 使用切片进行多重赋值
numbers = [1, 2, 3, 4, 5]
first, *middle, last = numbers
print("切片赋值后的变量值:")
print("first =", first)
print("middle =", middle)
print("last =", last)

Slicing extracts the first, middle, and last elements.

11. Conditional expression assignment

# 使用条件表达式进行赋值
x = True
value = "真" if x else "假"
print("条件表达式赋值后的变量值:")
print("value =", value)

The value is chosen based on a boolean condition.

12. List comprehension assignment

# 使用列表推导式进行赋值
squares = [x**2 for x in range(5)]
print("列表推导式赋值后的变量值:")
print("squares =", squares)

Creates a list of squares using a comprehension.

13. Generator expression assignment

# 使用生成器表达式进行赋值
squares_gen = (x**2 for x in range(5))
squares_list = list(squares_gen)
print("生成器表达式赋值后的变量值:")
print("squares_list =", squares_list)

Generates squares lazily and then converts to a list.

14. Set comprehension assignment

# 使用集合推导式进行赋值
unique_squares = {x**2 for x in range(5)}
print("集合推导式赋值后的变量值:")
print("unique_squares =", unique_squares)

Creates a set of unique square numbers.

15. Dictionary comprehension assignment

# 使用字典推导式进行赋值
square_dict = {x: x**2 for x in range(5)}
print("字典推导式赋值后的变量值:")
print("square_dict =", square_dict)

Builds a dictionary mapping each number to its square.

Conclusion

The presented Python variable assignment methods cover simple direct assignment to advanced comprehension techniques, helping programmers write more concise and efficient code.

pythoncode examplesProgramming FundamentalsVariable Assignment
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.