简介:本文为Python初学者提供系统性学习路径,涵盖环境配置、基础语法、核心模块及实战项目,帮助快速掌握编程思维并完成首个作品。
选择Python版本时需注意:3.x系列是当前主流(如3.11+),2.x已停止官方支持。推荐使用Anaconda管理多版本环境,其优势在于:
安装步骤示例(Windows):
python --versionPython采用动态类型系统,常见数据类型包括:
# 数值类型age: int = 25height: float = 1.75# 字符串操作greeting: str = "Hello, Python!"print(greeting[7:13]) # 切片操作输出"Python"# 布尔运算is_active: bool = Trueprint(not is_active or (5 > 3)) # 输出True
条件语句:
score = 85if score >= 90:print("A")elif score >= 80:print("B") # 此处会执行else:print("C")
循环结构:
```python
fruits = [“apple”, “banana”, “cherry”]
for fruit in fruits:
if fruit == “banana”:
continue # 跳过本次循环
print(fruit.upper())
count = 0
while count < 5:
print(f”Count: {count}”)
count += 1
#### 2.3 函数与模块化编程函数定义最佳实践:```pythondef calculate_area(radius: float, pi: float = 3.14159) -> float:"""计算圆面积Args:radius: 圆的半径pi: 圆周率(可选参数)Returns:圆的面积"""return pi * radius ** 2# 调用示例print(calculate_area(5)) # 使用默认pi值
# 读写文本文件with open("data.txt", "w", encoding="utf-8") as f:f.write("第一行内容\n第二行内容")# 逐行读取大文件with open("data.txt", "r") as f:for line_num, line in enumerate(f, 1):print(f"Line {line_num}: {line.strip()}")# CSV文件处理import csvwith open("data.csv", "w", newline="") as f:writer = csv.writer(f)writer.writerow(["Name", "Age"])writer.writerow(["Alice", 28])
try:result = 10 / 0except ZeroDivisionError as e:print(f"数学错误: {str(e)}")except Exception as e: # 捕获其他异常print(f"未知错误: {str(e)}")else:print("无异常时执行")finally:print("始终执行") # 常用于资源释放
def calculator():print("简易计算器")print("1. 加法")print("2. 减法")choice = input("请选择操作(1/2): ")num1 = float(input("输入第一个数字: "))num2 = float(input("输入第二个数字: "))if choice == "1":print(f"结果: {num1 + num2}")elif choice == "2":print(f"结果: {num1 - num2}")else:print("无效输入")if __name__ == "__main__":calculator()
import requestsdef fetch_weather(city):url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid=YOUR_API_KEY"try:response = requests.get(url)data = response.json()temp = data["main"]["temp"] - 273.15 # 转换为摄氏度print(f"{city}当前温度: {temp:.1f}°C")except Exception as e:print(f"获取天气失败: {str(e)}")fetch_weather("Beijing")
包安装失败:
python -m pip install --upgrade pippip install package -i https://pypi.tuna.tsinghua.edu.cn/simple编码问题:
# -*- coding: utf-8 -*-性能优化:
[x*2 for x in range(10)]初级阶段(1-3个月):
中级阶段(3-6个月):
高级阶段(6个月+):
建议每周保持10-15小时的有效学习时间,通过实际项目巩固知识。记住:编程是实践科学,代码量决定熟练度。遇到问题时,先尝试独立解决,再查阅文档或寻求帮助。