Skip to content

Python 变量

如何 创建 and use 变量 in Python — 动态输入, naming, and assignment.

你将学到

  • 如何 assign 值到 变量 (否 declaration keyword 需要)
  • Python's 动态输入 and 如何 检查类型
  • 变量 naming 规则 and 约定 (PEP 8)
  • 多个 assignment and swapping 变量

概念讲解

Creating Variables

In Python, you create a variable simply by assigning a value. There is no let, const, or var keyword — the assignment = creates the variable automatically:

name = "Ada"
age = 25
pi = 3.14159
is_admin = True

Dynamic Typing

Python is dynamically typed — a variable can hold any type, and the type can change at runtime. You do not declare the type; Python figures it out:

x = 10          # x is an int
x = "hello"     # now x is a str
x = [1, 2, 3]   # now x is a list

Use 类型() to check what a variable currently holds, and isinstance() to test against a type:

print(type(age))         # <class 'int'>
print(isinstance(age, int))  # True

Naming Rules

Variable names must:

  • Start with a letter or underscore (not a digit)
  • Contain only letters, digits, and underscores
  • Not be a reserved keyword (如果, for, 类, etc.)
  • Be case-sensitive (age and Age are different)

PEP 8 conventions:

  • Use snake_case for variables and functions: user_count, total_price
  • Use UPPER_SNAKE_CASE for constants: MAX_CONNECTIONS, PI
  • Use PascalCase for classes: MyClass
  • Names starting with _ are "私有" by convention: _internal_value

Multiple Assignment

Python lets you assign multiple variables at once, which is both concise and readable:

# Assign the same value to multiple variables
x = y = z = 0

# Assign different values in one line
name, age, role = "Ada", 25, "admin"

# Swap two variables without a temp variable
a, b = 1, 2
a, b = b, a  # now a=2, b=1

Variables Are References

When you assign an object (like a list) to a variable, the variable is a reference to that object. This matters for mutability:

a = [1, 2, 3]
b = a           # b points to the SAME list
b.append(4)
print(a)        # [1, 2, 3, 4] — a changed too!

To create a copy, use b = .复制() or b = 列表().

示例代码

              # Basic assignment — no declaration keyword
name = "Ada Lovelace"
age = 25
height = 1.68
is_student = True

print(f"{name} is {age} years old and {height}m tall")

# Dynamic typing — the same variable can change type
x = 10
print(type(x))   # <class 'int'>
x = "now a string"
print(type(x))   # <class 'str'>

# Multiple assignment
a, b, c = 1, 2, 3
print(f"a={a}, b={b}, c={c}")

# Swap without a temp variable
a, b = b, a
print(f"After swap: a={a}, b={b}")

# Variables are references — be careful with mutable objects
original = [1, 2, 3]
reference = original
reference.append(4)
print(f"original is also changed: {original}")  # [1, 2, 3, 4]

# Make a real copy instead
copy = original.copy()
copy.append(5)
print(f"original is NOT changed: {original}")   # still [1, 2, 3, 4]
            

Shows 基础 assignment, 动态输入使用类型(), 多个 assignment, swap trick, shared-引用 pitfall 使用列表, and 如何 .复制() avoids 它.

动手试一试

常见错误

错误写法

Using 单个 = (assignment) 相反的 == (comparison) in 条件

正确做法

In Python, = assigns 值 and == compares. 如果 x = 5 是 SyntaxError; use 如果 x == 5. Python catches 这个 at parse 时间, unlike 一些 other languages.

错误写法

Expecting b = 到复制列表, 然后是 surprised 当两者都更改

正确做法

b = 创建引用到 相同对象, 不复制. Use b = .复制() for shallow 复制, or 导入复制; b = 复制.deepcopy() for nested 结构.

相关速查表

练习 Python 变量

9 个练习

练习 Python 变量

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误