一、变量与数据类型(编程世界的基石)
Python的变量就像魔法贴纸(随贴随用)!不需要声明类型,直接赋值就能用:
age = 25 # 整型
price = 9.9 # 浮点型
name = "码农小明" # 字符串
is_active = True # 布尔型
数据类型重点区分:
- 不可变类型:数字、字符串、元组(tuple)→ 修改会创建新对象
- 可变类型:列表(list)、字典(dict)、集合(set)→ 原地修改(划重点)
(新手常见坑)注意字符串的不可变性:
text = "hello"
text[0] = "H" # 报错!字符串不可修改
new_text = "H" + text[1:] # 正确做法
二、运算符与表达式(程序员的计算器)
除了常规的+ - * /
,Python有几个杀手锏运算符:
**
幂运算:2**3 → 8
//
整除:7//2 → 3
:=
海象运算符(Python3.8+):在表达式中赋值
(实战技巧)三元运算符的妙用:
result = "通过" if score >= 60 else "补考"
三、流程控制(让程序学会思考)
3.1 条件判断
if temperature > 30:
print("开启空调")
elif 20 <= temperature <= 30:
print("开窗通风")
else:
print("穿上秋裤!")
3.2 循环结构
- while循环:适合不确定次数的循环
count = 0
while count < 5:
print(f"这是第{count+1}次循环")
count +=1
- for循环(强烈推荐):
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(f"今天吃{fruit}")
# 生成九九乘法表(经典案例)
for i in range(1,10):
for j in range(1,i+1):
print(f"{j}×{i}={i*j}", end="\t")
print()
四、函数编程(代码复用的艺术)
4.1 基础函数定义
def greet(name, times=1): # 默认参数必须在后
"""打招呼函数(文档字符串很重要)"""
return f"你好{name}!" * times
print(greet("王老师", 3))
4.2 参数传递的坑(超级重要)
- 不可变对象传值,可变对象传引用!
def update_list(lst):
lst.append(4) # 修改原列表
my_list = [1,2,3]
update_list(my_list)
print(my_list) # [1,2,3,4]
五、模块与包(站在巨人肩膀上)
5.1 导入方式对比
import math # 标准导入
from random import randint # 精准导入
import numpy as np # 别名导入
print(math.sqrt(16))
print(randint(1,10))
5.2 自定义模块
创建calculator.py
:
def add(a, b):
return a + b
def multiply(a, b):
return a * b
使用时:
import calculator
print(calculator.add(3,5))
六、异常处理(代码的保险丝)
6.1 基础try-except
try:
num = int(input("输入数字:"))
except ValueError:
print("输入的不是数字!")
else:
print(f"输入正确:{num}")
finally:
print("执行完毕")
6.2 自定义异常
class AgeError(Exception):
"""自定义年龄异常"""
def __init__(self, value):
self.value = value
super().__init__(f"非法年龄:{value}(应在0-150之间)")
def set_age(age):
if not 0 <= age <= 150:
raise AgeError(age)
print(f"年龄设置为:{age}")
七、文件操作(数据持久化关键)
7.1 基础读写
# 写入文件
with open("diary.txt", "w", encoding="utf-8") as f:
f.write("2024年5月20日\n")
f.write("今天学会了Python文件操作!\n")
# 读取文件(推荐方式)
with open("diary.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
7.2 CSV文件处理
import csv
# 写入CSV
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["姓名", "年龄", "城市"])
writer.writerow(["张三", 25, "北京"])
# 读取CSV
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
八、Pythonic编程技巧(写出优雅代码)
- 列表推导式:
squares = [x**2 for x in range(10)]
- 字典合并(Python3.9+):
dict1 = {"a": 1}
dict2 = {"b": 2}
merged = dict1 | dict2
- f-string格式化:
name = "Alice"
age = 30
print(f"{name=}, {age=}") # 输出:name='Alice', age=30
- 类型提示(Python3.5+):
def greet(name: str) -> str:
return f"Hello {name}"
(终极建议)坚持遵守PEP8代码规范:
- 4空格缩进
- 行长度不超过79字符
- 使用snake_case命名变量
- 类名用CamelCase
结语
Python语法就像乐高积木,看似简单却能构建复杂系统!记住:
- 多写注释和文档字符串(你会感谢三个月后的自己)
- 善用虚拟环境管理依赖
- 掌握调试器使用(pdb或IDE调试工具)
- 定期回顾官方文档(https://docs.python.org)
(彩蛋)试试在Python控制台输入:
import this
你会发现Python哲学的真谛!