1. 变量与基本数据类型
定义变量
x = 10
字符串
s = "Hello, Python!"
列表(List)
my_list = [1, 2, 3, 'a']
字典(Dict)
person = {"name": "Alice", "age": 25}
2. 控制结构
if 语句
if x > 0:
print("正数")
elif x == 0:
print("零")
else:
print("负数")
for 循环
for i in range(5):
print(i)
while 循环
count = 0
while count < 3:
print(count)
count += 1
3. 函数定义与调用
定义函数
def greet(name):
return f"Hello, {name}!"
print(greet("Bob"))
带默认参数
def power(base, exp=2):
return base ** exp
print(power(3)) # 输出 9
print(power(3, 3)) # 输出 27
4. 文件读写
读取文件
with open('file.txt', 'r', encoding='utf-8') as f:
content = f.read()
print(content)
写入文件
with open('output.txt', 'w', encoding='utf-8') as f:
f.write("Hello from Python!")
5. 异常处理
try-except
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
6. 常用内置函数
len(), type(), str(), int()
items = [1, 2, 3]
print(len(items)) # 3
print(type(items)) # <class 'list'>
print(str(100)) # "100"
print(int("42")) # 42