摘要:本文是一份专为初学者设计的Python学习路线图。从计算机底层原理出发,逐步讲解Python基础语法、数据类型、流程控制、函数、文件操作,最后通过天气API调用和智能输入验证等实战案例,帮助读者快速建立编程思维。无论你是零基础还是有其他语言经验,这份教程都能让你系统掌握Python的核心技能。
一、计算机基础与操作系统
1.1 计算机的组成
从IT工程师视角,计算机资源分为两类:
- 硬件资源:CPU、内存、硬盘、网卡、电源等
- 软件资源:操作系统、浏览器、办公软件、数据库等
核心问题 :软件如何控制硬件?
答案 :通过操作系统(OS)。
操作系统本质上是软件与硬件之间的桥梁。应用程序通过系统调用(文件/网络/进程)与操作系统交互,操作系统再通过驱动程序控制硬件。
1.2 主流操作系统分类
| 系统 | 特点 |
|---|---|
| Windows | 桌面端为主,部分服务器(Windows Server) |
| macOS | 个人桌面系统,底层基于UNIX |
| Linux | 服务器端使用最广泛,常见发行版:CentOS、Ubuntu、Rocky、麒麟;开源、免费、稳定;绝大多数运维、云计算、容器平台都运行在Linux上 |
二、编程语言与Python简介
2.1 编程语言的本质
编程语言是人与计算机沟通的方式。计算机只认识0和1(机器语言),编程语言的作用是让人类用接近自然语言的语法描述逻辑,再由系统翻译成机器能执行的指令。
2.2 Python的核心特点
Python 是全球最受欢迎的编程语言之一,其设计哲学强调代码的可读性:
- 简单易学:语法接近英语,适合初学者
- 解释型语言:无需编译,逐行执行,便于调试
- 跨平台:同一份代码可在 Windows/macOS/Linux 运行
- 丰富的库:拥有庞大的第三方库(如 NumPy, Pandas, TensorFlow)
- 强制缩进:用缩进定义代码块,保证代码风格统一
2.3 Python应用领域
| 领域 | 常用库/框架 |
|---|---|
| 人工智能 | TensorFlow, PyTorch, Scikit-learn |
| 数据分析 | Pandas, NumPy, Matplotlib |
| Web开发 | Django, Flask, FastAPI |
| 自动化运维 | Ansible, Docker SDK |
| 网络爬虫 | Requests, Scrapy, BeautifulSoup |
2.4 Python版本选择
生产环境中建议选择最新版本的前1-2个小版本,避免未知Bug。目前主流为 Python 3.x(建议版本 >= 3.9)。
三、Python基础语法
3.1 注释与基本规范
- 单行注释 :
# 这是注释 - 多行注释 :
''' 这是多行注释 '''或""" 文档注释 """ - 语法规范 :使用缩进表示代码块(推荐4个空格),每行语句不需要分号。
3.2 变量与命名
变量是数据的临时存储器,不需要声明类型,类型由赋的值决定。
命名规则:
- 由字母、数字、下划线组成
- 不能以数字开头
- 区分大小写
- 不能使用关键字(如
if,for,def等)
python
# 变量定义与赋值
username = "admin" # 字符串
age = 25 # 整数
score = 95.5 # 浮点数
is_pass = True # 布尔值
# Python特有的变量交换
a, b = "可乐", "牛奶"
a, b = b, a # 交换后 a="牛奶", b="可乐"
# 删除变量
del username
3.3 常用数据类型
Python 是动态类型语言,变量类型在赋值时自动确定。
| 类型 | 示例 | 描述 | 特性 |
|---|---|---|---|
| int | 10, -5 |
整数 | 精确存储 |
| float | 3.14, -0.5 |
浮点数 | 可能存在精度问题 |
| str | "Hello" |
字符串 | 不可变序列 |
| bool | True, False |
布尔值 | 逻辑判断 |
| list | [1, 2, 3] |
列表 | 可变,有序 |
| tuple | (1, 2, 3) |
元组 | 不可变,有序 |
| dict | {"name": "Tom"} |
字典 | 键值对映射 |
| NoneType | None |
空值 | 表示无值 |
类型检测:
python
print(type("张三")) # <class 'str'>
print(isinstance(age, int)) # True
3.4 数据类型转换
不同数据类型之间不能直接运算,需要转换。
python
age_str = "18"
age_int = int(age_str) # 字符串转整数
age_float = float("3.14") # 字符串转浮点数
str_val = str(666) # 数字转字符串
bool_val = bool(0) # False,非0为True
# 注意:转换可能失败
# int("abc") # ValueError
# int("3.14") # ValueError (小数不能直接转整数)
3.5 格式化输出(重点推荐 f-string)
python
name, age, height = "张三", 26, 175.5
# 1. 传统 % 占位符
info = "姓名:%s,年龄:%d,身高:%.1fcm" % (name, age, height)
# 2. format() 方法
info = "姓名:{0},年龄:{1}".format(name, age)
# 3. f-string(推荐,Python 3.6+)
info = f"姓名:{name},年龄:{age},身高:{height}cm"
print(info) # 姓名:张三,年龄:26,身高:175.5cm
3.6 用户输入处理
input() 函数永远返回字符串类型,必须进行类型转换才能进行数值计算。
python
name = input("请输入你的姓名:")
age_input = input("请输入年龄:")
age = int(age_input)
print(f"欢迎你,{name}!明年你就{age + 1}岁了")
四、流程控制
4.1 条件判断(if-elif-else)
python
score = float(input("请输入成绩:"))
if score >= 90:
grade = "A"
print("优秀")
elif score >= 80:
grade = "B"
print("良好")
elif score >= 70:
grade = "C"
print("中等")
elif score >= 60:
grade = "D"
print("及格")
else:
grade = "E"
print("不及格")
print(f"你的成绩等级是:{grade}")
三元运算符(条件表达式):
python
result = "及格" if score >= 60 else "不及格"
status = "成年" if age >= 18 else "未成年"
4.2 循环语句
while 循环(循环次数不确定时使用)
python
# 无限循环直到密码正确
password = "123456"
while True:
user_input = input("请输入密码:")
if user_input == password:
print("登录成功!")
break
# 1~100 的和
i, total = 1, 0
while i <= 100:
total += i
i += 1
print(f"1~100的和:{total}") # 5050
for 循环(循环次数确定时使用)
python
# 遍历字符串
for char in "hello":
print(char)
# 遍历列表
fruits = ["苹果", "香蕉", "橙子"]
for fruit in fruits:
print(f"水果:{fruit}")
# 使用 range()
for i in range(5): # 0,1,2,3,4
print(i)
for i in range(1, 6): # 1,2,3,4,5
print(i)
for i in range(2, 11, 2): # 步长为2:2,4,6,8,10
print(i)
循环控制
python
# break: 立即停止整个循环
for i in range(10):
if i == 5:
print("找到5,停止循环")
break
print(i) # 只输出0-4
# continue: 跳过本次循环
for i in range(5):
if i == 2:
continue # 跳过i=2
print(i) # 输出0,1,3,4
五、数据容器(重点)
5.1 列表(List)- 可变的有序集合
python
# 增删改查
fruits = ["苹果", "香蕉"]
fruits.append("橙子") # 末尾添加
fruits.insert(1, "葡萄") # 指定位置插入
fruits.remove("葡萄") # 按值删除
removed = fruits.pop(1) # 按索引删除并返回
del fruits[0] # 删除索引0
fruits.clear() # 清空列表
# 其他操作
colors = ["红", "绿", "蓝", "绿"]
print(colors.index("绿")) # 1(第一个位置)
print(colors.count("绿")) # 2(出现次数)
scores = [88, 92, 75, 96]
scores.sort() # 升序
scores.sort(reverse=True) # 降序
5.2 元组(Tuple)- 不可变的有序集合
python
# 创建元组(单元素必须加逗号)
empty_tuple = ()
single = (42,)
colors = ("红", "绿", "蓝")
# 访问与解包
print(colors[0]) # 红
r, g, b = colors # r="红", g="绿", b="蓝"
# 元组不可修改
# colors[0] = "黄" # TypeError
5.3 字典(Dict)- 键值对映射
python
# 增删改查
student = {}
student["name"] = "李四" # 添加
student["age"] = 20 # 添加
student["age"] = 21 # 修改
del student["age"] # 删除键
value = student.pop("name") # 删除并返回
# 获取所有键值
person = {"name": "王五", "age": 25}
print(person.keys()) # dict_keys(['name', 'age'])
print(person.values()) # dict_values(['王五', 25])
print(person.items()) # dict_items([('name', '王五'), ('age', 25)])
# 遍历字典
for key, value in person.items():
print(f"{key}: {value}")
5.4 可变类型 vs 不可变类型
| 类型 | 示例 | 特性 |
|---|---|---|
| 不可变 | int, str, tuple, bool | 修改时创建新对象,内存地址改变 |
| 可变 | list, dict | 修改时地址不变,内容改变 |
python
a = 100
print(id(a)) # 139771779167696
a = 200
print(id(a)) # 139771779170960 (地址变了)
b = [1, 2]
print(id(b)) # 139771773082816
b.append(3)
print(id(b)) # 139771773082816 (地址不变)
六、函数:代码复用的利器
6.1 函数基本语法
python
def 函数名(参数列表):
"""函数说明文档"""
函数体代码
return 返回值 # 可选
6.2 参数类型详解
| 参数类型 | 示例 | 说明 |
|---|---|---|
| 位置参数 | def greet(name, age): |
按顺序传递 |
| 关键字参数 | greet(age=25, name="李四") |
按名称传递,顺序不重要 |
| 默认参数 | def greet(name, greeting="你好"): |
不传时使用默认值 |
| 可变参数 (*args) | def sum_all(*numbers): |
接收任意数量位置参数(元组) |
| 关键字可变参数 (**kwargs) | def print_info(**info): |
接收任意数量关键字参数(字典) |
python
# 综合示例
def complex_func(a, b, *args, **kwargs):
print(f"a={a}, b={b}")
print(f"args={args}")
print(f"kwargs={kwargs}")
complex_func(1, 2, 3, 4, 5, name="张三", age=25)
# 输出: a=1, b=2, args=(3, 4, 5), kwargs={'name': '张三', 'age': 25}
6.3 变量作用域
python
global_var = "我是全局的"
def test_scope():
global global_var # 声明修改全局变量
local_var = "我是局部的"
print(f"函数内访问全局:{global_var}")
global_var = "我已被修改"
def inner_func():
nonlocal local_var # 修改外层函数的变量
local_var = "我在内部被修改了"
inner_func()
七、文件操作
7.1 文件操作三步曲
- 打开文件 :
open(路径, 模式, 编码) - 操作文件:读/写
- 关闭文件 :
close()(推荐使用with自动管理)
7.2 写入与读取
python
# 写入文件
with open("hello.txt", "w", encoding="utf-8") as f:
f.write("Hello, World!\n")
f.write("你好,世界!")
# 读取文件
with open("hello.txt", "r", encoding="utf-8") as f:
# 方法1:read()读取全部
content = f.read()
print(content)
# 方法2:逐行读取(内存友好)
for line in f:
print(line.strip())
7.3 os模块:操作系统接口
python
import os
# 路径操作
print(os.getcwd()) # 获取当前目录
print(os.path.isdir("/etc")) # 判断是否是目录
print(os.path.isfile("test.txt")) # 判断是否是文件
print(os.path.exists("/test")) # 判断是否存在
# 路径拆分与组合
filename = os.path.basename("/home/user/data/test.txt") # test.txt
dirname = os.path.dirname("/home/user/data/test.txt") # /home/user/data
name, ext = os.path.splitext("test.txt") # test, .txt
new_path = os.path.join("data", "docs", "file.txt") # data/docs/file.txt
# 目录与文件管理
os.mkdir("/tmp/demo_dir") # 创建目录
os.rmdir("/tmp/demo_dir") # 删除目录(必须为空)
os.remove("/tmp/test.txt") # 删除文件
os.rename("/tmp/old.txt", "/tmp/new.txt") # 重命名
八、网络请求(requests库)
8.1 基础请求
python
import requests
# GET请求
response = requests.get("https://httpbin.org/get")
print(f"状态码: {response.status_code}")
print(f"响应内容: {response.text}")
# 带参数的GET请求
params = {"name": "张三", "age": 25}
response = requests.get("https://httpbin.org/get", params=params)
print(f"请求URL: {response.url}")
# POST请求(表单数据)
form_data = {"username": "admin", "password": "123456"}
response = requests.post("https://httpbin.org/post", data=form_data)
# POST请求(JSON数据)
json_data = {"user": {"name": "张三", "age": 25}}
response = requests.post("https://httpbin.org/post", json=json_data)
8.2 添加请求头与错误处理
python
from requests.exceptions import RequestException
def safe_request(url, method="GET", **kwargs):
try:
if method.upper() == "GET":
response = requests.get(url, **kwargs)
elif method.upper() == "POST":
response = requests.post(url, **kwargs)
response.raise_for_status() # 状态码非200时抛出异常
return response
except requests.exceptions.Timeout:
print(f"请求超时: {url}")
except requests.exceptions.ConnectionError:
print(f"连接错误: {url}")
except RequestException as e:
print(f"请求异常: {e}")
return None
# 使用示例
headers = {"User-Agent": "MyApp/1.0", "Accept": "application/json"}
response = safe_request("https://api.github.com/users/octocat", timeout=5, headers=headers)
if response:
print(response.json())
九、实战案例
获取实时天气(调用 Open-Meteo API)
python
import requests
# 天气代码对应中文描述
weather_map = {
0: "晴", 1: "晴间多云", 2: "多云", 3: "阴",
61: "小雨", 63: "中雨", 65: "大雨",
71: "小雪", 73: "中雪", 75: "大雪"
}
def get_weather(city):
city_map = {
"北京": {"lat": 39.9042, "lon": 116.4074},
"上海": {"lat": 31.2304, "lon": 121.4737},
"广州": {"lat": 23.1291, "lon": 113.2644},
"深圳": {"lat": 22.5431, "lon": 114.0579},
}
if city not in city_map:
print("暂不支持该城市")
return
lat, lon = city_map[city]["lat"], city_map[city]["lon"]
url = "https://api.open-meteo.com/v1/forecast"
params = {"latitude": lat, "longitude": lon, "current_weather": True}
try:
response = requests.get(url, params=params, timeout=10)
data = response.json()
current = data["current_weather"]
weather_text = weather_map.get(current["weathercode"], "未知天气")
print(f"\n{city} 实时天气")
print(f"温度:{current['temperature']} °C")
print(f"风速:{current['windspeed']} km/h")
print(f"天气:{weather_text}")
except Exception as e:
print(f"获取天气失败:{e}")
# 调用示例
get_weather("北京")
get_weather("上海")
十、总结与学习建议
核心要点回顾
| 模块 | 重点内容 | 关键函数/关键字 |
|---|---|---|
| 基础语法 | 变量、数据类型、类型转换 | int(), float(), str(), type() |
| 流程控制 | 条件判断、循环、循环控制 | if-elif-else, for, while, break, continue |
| 数据容器 | 列表、元组、字典 | list.append(), dict.get(), tuple(), len() |
| 函数 | 参数类型、作用域、lambda | def, return, *args, **kwargs, lambda |
| 文件操作 | 读写文件、路径处理 | with open(), os.path, os.mkdir() |
| 网络请求 | GET/POST、JSON处理、错误处理 | requests.get(), requests.post(), response.json() |