Python 初学者与中级开发者完整指南
发布: (2025年12月5日 GMT+8 11:22)
4 min read
原文: Dev.to
Source: Dev.to
为什么选择 Python?
- 对初学者友好
- 易于阅读和编写
- 可用于网页开发、数据科学、人工智能/机器学习、自动化、DevOps、游戏开发等众多领域
- 拥有庞大的社区支持
- 在所有主流操作系统上均可使用
1. Python 基础
1.1 变量
name = "Farhad"
age = 20
is_active = True
print(name)
print(age)
print(is_active)
解释
- 字符串使用引号。
- 整数不使用引号。
- 布尔值首字母大写:
True或False。
1.2 数据类型
x = 10 # int
pi = 3.14 # float
name = "Python" # str
is_ok = True # bool
items = [1, 2, 3] # list
points = (4, 5) # tuple
user = {"name": "Ali", "age": 25} # dict
1.3 用户输入
username = input("Enter your name: ")
print("Hello, " + username)
1.4 条件语句(if、elif、else)
age = 18
if age > 18:
print("You are an adult.")
elif age == 18:
print("You just turned 18!")
else:
print("You are under 18.")
2. 循环的使用
2.1 for 循环
for i in range(5):
print("Number:", i)
解释: range(5) 生成 0 到 4 的数字。
2.2 while 循环
count = 1
while count <= 5:
print(count)
count += 1
3. 函数
def greet(name):
print("Hello,", name)
greet("Farhad")
greet("Klie")
4. 列表、元组和字典
4.1 列表
fruits = ["apple", "banana", "orange"]
fruits.append("mango")
print(fruits)
4.2 元组(不可变)
point = (10, 20)
print(point[0])
4.3 字典
person = {
"name": "Farhad",
"age": 20
}
print(person["name"])
5. 中级 Python 概念
5.1 列表推导式
numbers = [1, 2, 3, 4, 5]
squares = [x * x for x in numbers]
print(squares)
5.2 Lambda 函数
square = lambda x: x * x
print(square(5))
5.3 Map、Filter、Reduce
map()
nums = [1, 2, 3]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)
filter()
nums = [1, 2, 3, 4, 5, 6]
even = list(filter(lambda x: x % 2 == 0, nums))
print(even)
5.4 错误处理(try/except)
try:
number = int(input("Enter a number: "))
print("You entered:", number)
except ValueError:
print("Invalid number. Please enter digits only.")
5.5 文件操作
写入文件
with open("data.txt", "w") as f:
f.write("Hello, Python!")
读取文件
with open("data.txt", "r") as f:
content = f.read()
print(content)
5.6 面向对象编程(OOP)
类和对象示例
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"My name is {self.name}, and I am {self.age} years old.")
p1 = Person("Farhad", 20)
p1.introduce()
解释
__init__在创建对象时运行。self指代当前对象。- 方法是定义在类内部的函数。
6. Python 最佳实践
- 使用有意义的变量名。
- 保持函数简短且可复用。
- 在需要时为代码添加注释。
- 遵循 PEP 8 风格指南。
- 为项目依赖使用虚拟环境。
7. 用 Python 可以构建的项目
- Web 应用(Django、Flask、FastAPI)
- 机器学习模型(TensorFlow、PyTorch)
- 自动化脚本
- API 服务
- 聊天机器人
- 数据可视化工具
- 游戏(pygame)
只要掌握了基础,Python 的可能性是无限的。
结论
Python 是初学者的完美起点,也是中级开发者的强大工具。凭借其简洁的语法和丰富的生态系统,你可以快速构建从小脚本到大型应用的任何东西。