输入关键词开始搜索

Python 基础语法

变量与数据类型

# 动态类型,不需要声明
name = "Alice"
age = 25
height = 1.68
is_student = True

# 类型检查
print(type(name))    # <class 'str'>
print(isinstance(age, int))  # True

# 基本类型
int_val = 42
float_val = 3.14
str_val = "hello"
bool_val = False
none_val = None          # 空值

# 多变量赋值
a, b = 1, 2
x = y = z = 0            # 三个都是 0

# f-string(Python 3.6+)
print(f"{name} is {age} years old")

容器类型

# 列表 list — 可变有序
fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.insert(1, "grape")
fruits.remove("banana")
print(fruits[0])          # apple
print(fruits[-1])         # 最后一个
print(fruits[1:3])        # 切片 [1, 3)

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

# 元组 tuple — 不可变
point = (3, 4)
x, y = point              # 解包
single = (1,)             # 单元素元组,逗号不能丢

# 字典 dict — 键值对
user = {"name": "Bob", "age": 30}
user["email"] = "bob@example.com"
print(user.get("phone", "N/A"))  # 安全取值

# 字典推导式
squares_map = {x: x**2 for x in range(5)}

# 集合 set — 不重复无序
tags = {"python", "coding", "python"}  # {"python", "coding"}
tags.add("tutorial")
print("python" in tags)   # True

控制流

# if-elif-else
score = 85
if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
else:
    grade = "C"

# for 循环
for i in range(5):           # 0..4
    print(i)

for fruit in fruits:         # 遍历可迭代对象
    print(fruit)

for i, fruit in enumerate(fruits):  # 带索引
    print(f"{i}: {fruit}")

for k, v in user.items():    # 字典遍历
    print(f"{k} = {v}")

# while
count = 0
while count < 5:
    print(count)
    count += 1

# break / continue
for x in range(10):
    if x == 3:
        continue    # 跳过 3
    if x == 7:
        break       # 到 7 停止
    print(x)        # 输出 0 1 2 4 5 6

函数

def greet(name, greeting="Hello"):
    """返回问候语"""          # docstring
    return f"{greeting}, {name}!"

print(greet("Alice"))               # Hello, Alice!
print(greet("Bob", "Hi"))           # Hi, Bob!

# 可变参数
def sum_all(*args):
    return sum(args)

print(sum_all(1, 2, 3, 4))          # 10

# 关键字参数
def create_user(**kwargs):
    for k, v in kwargs.items():
        print(f"{k}: {v}")

create_user(name="Alice", age=25)

# Lambda
square = lambda x: x ** 2
sorted(fruits, key=lambda f: len(f))  # 按长度排序

class Animal:
    species = "Unknown"        # 类变量

    def __init__(self, name):  # 构造方法
        self.name = name       # 实例变量

    def speak(self):
        return f"{self.name} makes a sound"

class Dog(Animal):
    species = "Canine"         # 覆盖类变量

    def __init__(self, name, breed):
        super().__init__(name) # 调用父类构造
        self.breed = breed

    def speak(self):
        return f"{self.name} barks!"

dog = Dog("Rex", "Labrador")
print(dog.speak())             # Rex barks!
print(isinstance(dog, Animal)) # True

模块与导入

# 导入
import math
from datetime import datetime, timedelta
from pathlib import Path
import numpy as np             # 别名

print(math.sqrt(16))           # 4.0

# 文件操作
with open("file.txt", "r") as f:
    content = f.read()

with open("output.txt", "w") as f:
    f.write("Hello")

# Pathlib(推荐替代 os.path)
path = Path("data/config.json")
print(path.suffix)             # .json
print(path.parent)             # data
text = path.read_text()