Python Syntax Basics: Types, Control Flow, Functions & Comprehensions

Numbers, strings, lists, tuples, dicts and sets; if/for/while; functions, *args and **kwargs; decorators; and comprehensions — everything needed to write real Python.

BeginnerUpdated 2026-10-2974K views

Built-in Data Types

# 数字
42                  # int
3.14                # float
2 ** 64             # 大整数自动支持

# 字符串
s = "BackendWiki"
s.upper()           # BACKENDWIKI
f"len={len(s)}"      # f-string 插值
"a,b,c".split(",") # ['a', 'b', 'c']

# 列表(可变,有序)
nums = [1, 2, 3]
nums.append(4)
nums[0] = 10
nums[1:3]           # 切片 [2, 3]

# 元组(不可变)
point = (3, 4)
x, y = point        # 解包

# 字典(键值对,3.7+ 保持插入序)
cfg = {"port": 8080, "host": "0.0.0.0"}
cfg["port"]
cfg.get("timeout", 30)   # 带默认值

# 集合(去重)
tags = {"java", "python", "java"}
print(tags)          # {'java', 'python'}

Control Flow

score = 85

# 条件(没有 switch 也不需要,用 elif 链)
if score >= 90:
    grade = "A"
elif score >= 60:
    grade = "B"
else:
    grade = "F"

# for 遍历可迭代对象
for i in range(3):
    print(i)          # 0 1 2

for k, v in {"a": 1, "b": 2}.items():
    print(k, v)

# while 与 break / continue
while True:
    if score > 100:
        break
    score += 1

# match 语句(3.10+,类似 switch)
match score:
    case 100:
        print("full")
    case s if s >= 60:
        print("pass")
    case _:
        print("fail")

Functions, *args and **kwargs

def add(a: int, b: int, *args: int, **kwargs) -> int:
    """可变位置参数 args 与关键字参数 kwargs"""
    total = a + b + sum(args)
    if kwargs.get("debug"):
        print("total =", total)
    return total

add(1, 2)                        # 3
add(1, 2, 3, 4)                  # 10
add(1, 2, debug=True)            # 打印并返回 3

# 关键字参数与默认值
def connect(host, port=3306, timeout=5): ...
connect(host="localhost", timeout=10)

# lambda 表达式
sorted([3, 1, 2], key=lambda x: -x)   # [3, 2, 1]
Strings, tuples and numbers are passed by object reference but immutable — reassignment inside a function does not affect the caller. Mutable objects (lists, dicts) share state.

Comprehensions and Decorators

# 列表推导式
squares = [x * x for x in range(10)]
evens = [x for x in squares if x % 2 == 0]

# 字典 / 集合推导式
word_len = {w: len(w) for w in ["go", "java"]}

# 装饰器:在函数前后加逻辑
import time

def timed(fn):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = fn(*args, **kwargs)
        print(f"{fn.__name__} took {time.time()-start:.3f}s")
        return result
    return wrapper

@timed
def slow():
    time.sleep(1)

slow()    # slow took 1.001s

Friends & Partners