1. 变量与数据类型
x = 10
pi = 3.14
name = "Alice"
flag = True
lst = [1, 2, 3]
tpl = (1, 2, 3)
dct = {"key": "value"}
st = {1, 2, 3}
2. 元组(Tuple)
tpl = (10, 20, 30)
print(tpl[0])
print(tpl[1:3])
3. 集合(Set)
st = {1, 2, 3, 3}
st.add(4)
st.remove(2)
print(3 in st)
a = {1, 2, 3}
b = {3, 4, 5}
print(a & b)
print(a | b)
print(a - b)
4. 字典(Dict)
d = {"name": "Alice", "age": 25}
print(d["name"])
print(d.get("gender"))
print(d.get("gender", "F"))
for key in d:
print(key, d[key])
for key, value in d.items():
print(key, value)
5. 条件判断与循环
if x > 0:
print("Positive")
elif x == 0:
print("Zero")
else:
print("Negative")
for item in lst:
print(item)
for i, val in enumerate(lst):
print(i, val)
count = 0
while count < 3:
print(count)
count += 1
6. 函数与参数
def add(a, b=0):
return a + b
result = add(5, 3)
print(result)
def get_pos():
return 10, 20
x, y = get_pos()
print(x, y)
def func(*args, **kwargs):
print(args)
print(kwargs)
func(1, 2, a=3, b=4)
7. 异常处理
try:
x = 1 / 0
except ZeroDivisionError as e:
print("Error:", e)
finally:
print("Always execute")
8. 列表、字典、集合推导式
squares = [x*x for x in range(5)]
square_dict = {x: x*x for x in range(5)}
square_set = {x*x for x in range(5)}
9. 文件操作
with open('data.txt', 'r') as f:
content = f.read()
with open('output.txt', 'w') as f:
f.write("Hello, world!")
10. 模块导入
import math
print(math.sqrt(16))
from datetime import datetime
print(datetime.now())
11. 类与对象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, I am {self.name}, {self.age} years old")
p = Person("Alice", 25)
p.greet()
12. 其他重要特性
12.1 生成器
def gen():
for i in range(5):
yield i*i
for val in gen():
print(val)
12.2 Lambda匿名函数
add = lambda x, y: x + y
print(add(3, 4))
12.3 上下文管理(with)
with open('file.txt', 'r') as f:
content = f.read()
12.4 类型注解
def greet(name: str) -> str:
return "Hello, " + name