Python编程全面教程
一、环境配置
-
安装Python
-
推荐安装3.x版本(当前最新3.13)
-
安装时勾选"Add Python to PATH"
-
开发工具选择
-
IDE:PyCharm、VS Code、Jupyter Notebook
-
文本编辑器:Sublime Text、Atom
-
-
验证安装
python --version
二、基础语法
1. 变量与数据类型
# 基本类型
name = "Alice" # 字符串(str)
age = 25 # 整数(int)
height = 1.68 # 浮点数(float)
is_student = True # 布尔值(bool)
# 复合类型
numbers = [1, 2, 3] # 列表(list)
coordinates = (40.7128, -74.0060) # 元组(tuple)
person = {"name": "Bob", "age": 30} # 字典(dict)
unique_numbers = {1, 2, 3} # 集合(set)
2. 运算符
# 算术运算符
print(10 + 3) # 13
print(10 ** 2) # 100(幂运算)
# 比较运算符
print(5 >= 3) # True
# 逻辑运算符
print(True and False) # False
3. 字符串操作
text = "Python Programming"
print(text.upper()) # "PYTHON PROGRAMMING"
print(text.split()) # ['Python', 'Programming']
print(f"Hello {name}!") # f-string格式化
三、流程控制
1. 条件语句
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
else:
grade = "C"
2. 循环结构
# for循环
for i in range(5):
print(i) # 输出0-4
# while循环
count = 0
while count < 3:
print(count)
count += 1
# 循环控制
for num in [1, 2, 3, 4, 5]:
if num == 3:
continue
if num == 5:
break
print(num)
四、函数编程
1. 基本函数
def greet(name, message="Hello"):
"""返回问候语"""
return f"{message}, {name}!"
print(greet("Alice")) # Hello, Alice!
2. 参数类型
# 可变参数
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3)) # 6
# 关键字参数
def create_profile(**info):
print(info)
create_profile(name="Bob", age=30)
五、数据结构
1. 列表操作
fruits = ["apple", "banana"]
fruits.append("orange") # 添加元素
fruits.insert(1, "grape") # 插入元素
removed = fruits.pop(0) # 删除并返回第一个元素
2. 字典使用
student = {
"name": "Alice",
"courses": ["Math", "CS"]
}
print(student.get("age", 20)) # 安全获取值
student["graduated"] = False # 添加新键
六、文件操作
# 写入文件
with open("diary.txt", "w") as f:
f.write("2023-10-01\nToday I learned Python")
# 读取文件
with open("diary.txt", "r") as f:
content = f.readlines()
七、面向对象编程
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError
class Dog(Animal):
def speak(self):
return "Woof!"
buddy = Dog("Buddy")
print(buddy.speak()) # Woof!
八、异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("不能除以零!")
finally:
print("执行清理操作")
九、模块与包
# 导入标准库
import math
print(math.sqrt(16)) # 4.0
# 安装第三方库
# pip install requests
# 自定义模块
# 在mymodule.py中定义函数,然后:
# import mymodule
十、实战项目示例
1. 简易计算器
def calculator():
while True:
try:
num1 = float(input("输入第一个数字: "))
operator = input("选择操作 (+ - * /): ")
num2 = float(input("输入第二个数字: "))
if operator == '+':
result = num1 + num2
elif operator == '-':
result = num1 - num2
elif operator == '*':
result = num1 * num2
elif operator == '/':
result = num1 / num2
else:
print("无效运算符")
continue
print(f"结果: {result}")
except ValueError:
print("请输入有效数字!")
except ZeroDivisionError:
print("不能除以零!")
2. 数据可视化示例
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
plt.plot(x, y)
plt.title("示例图表")
plt.xlabel("X轴")
plt.ylabel("Y轴")
plt.show()
学习建议
-
每天坚持编码练习
-
阅读官方文档(https://docs.python.org)
-
参与开源项目
-
学习常用库:
-
数据分析:NumPy, Pandas
-
机器学习:Scikit-learn, TensorFlow
-
Web开发:Django, Flask
-
建议通过实际项目巩固知识,例如:
-
开发个人博客系统
-
数据分析项目
-
自动化脚本工具
-
简单游戏开发
掌握这些基础后,可以继续学习:
-
装饰器
-
生成器与迭代器
-
多线程/多进程编程
-
异步编程(async/await)
-
元类编程
记住:编程的核心在于实践!开始你的第一个项目吧!
收藏
扫描二维码,在手机上阅读
打赏
如果觉得文章对您有用,请随意打赏。
您的支持是我们继续创作的动力!
请备注您的网站账号名哦

微信扫一扫

支付宝扫一扫
评论一下?