Python编程入门教程
🐍 面向零基础学习者的Python编程完整教程,从环境搭建到实战项目,循序渐进掌握Python核心技能。
目录
- Python简介与环境搭建
- 第一个Python程序
- 变量与数据类型
- 运算符
- 字符串操作
- 列表(List)
- 元组与集合
- 字典(Dictionary)
- 条件判断
- 循环结构
- 函数
- 文件操作
- 异常处理
- 模块与包
- 面向对象编程
- 实战项目:通讯录管理系统
1. Python简介与环境搭建
什么是Python?
Python是一种简单易学、功能强大的编程语言,由Guido van Rossum于1991年创建。它的设计哲学强调代码的可读性和简洁性。
Python的特点:
- 简单易学:语法接近自然语言,适合初学者
- 功能强大:拥有丰富的标准库和第三方库
- 应用广泛:Web开发、数据分析、人工智能、自动化脚本等
- 跨平台:支持Windows、macOS、Linux
安装Python
Windows:
- 访问 https://www.python.org/downloads/
- 下载最新版本的Python安装包
- 运行安装程序,务必勾选"Add Python to PATH"
- 点击"Install Now"
macOS:
# 使用Homebrew安装
brew install python3
Linux(Ubuntu/Debian):
sudo apt update
sudo apt install python3 python3-pip
验证安装
打开终端或命令提示符,输入:
python3 --version
# 输出示例: Python 3.11.0
选择代码编辑器
推荐使用以下编辑器:
- VS Code(免费,推荐初学者)
- PyCharm(专业Python IDE)
- Jupyter Notebook(适合数据分析)
2. 第一个Python程序
Hello, World!
print("Hello, World!")
运行后输出:Hello, World!
代码解释
print()是Python的内置函数,用于在屏幕上输出内容"Hello, World!"是一个字符串,用引号包裹
注释
# 这是单行注释,Python解释器会忽略这行
"""
这是多行注释
可以写很多行
Python也会忽略这些内容
"""
print("注释不会被执行") # 行尾注释也可以
3. 变量与数据类型
变量
变量是用来存储数据的容器。Python中创建变量非常简单:
name = "Alice" # 字符串
age = 25 # 整数
height = 1.68 # 浮点数
is_student = True # 布尔值
print(name) # 输出: Alice
print(age) # 输出: 25
命名规则
# ✅ 合法的变量名
user_name = "Alice"
age2 = 25
_private = "私有变量"
MAX_SIZE = 100
# ❌ 非法的变量名
# 2name = "错误" # 不能以数字开头
# my-name = "错误" # 不能包含连字符
# class = "错误" # 不能使用Python关键字
基本数据类型
# 整数 (int)
count = 42
negative = -10
# 浮点数 (float)
price = 9.99
temperature = -5.5
# 字符串 (str)
greeting = "你好"
name = 'Python'
# 布尔值 (bool)
is_valid = True
has_error = None # None 表示"空"
# 查看数据类型
print(type(count)) # <class 'int'>
print(type(price)) # <class 'float'>
print(type(greeting)) # <class 'str'>
print(type(is_valid)) # <class 'bool'>
类型转换
# 字符串转整数
num_str = "42"
num = int(num_str) # 42
# 整数转字符串
age = 25
age_str = str(age) # "25"
# 浮点数转整数(截断小数)
pi = 3.14
pi_int = int(pi) # 3
# 输入函数(返回字符串)
user_input = input("请输入你的名字:")
print(f"你好,{user_input}!")
4. 运算符
算术运算符
a = 10
b = 3
print(a + b) # 13 加法
print(a - b) # 7 减法
print(a * b) # 30 乘法
print(a / b) # 3.333 除法(结果是浮点数)
print(a // b) # 3 整除(向下取整)
print(a % b) # 1 取余数
print(a ** b) # 1000 幂运算(10的3次方)
比较运算符
x = 5
y = 10
print(x == y) # False 等于
print(x != y) # True 不等于
print(x > y) # False 大于
print(x < y) # True 小于
print(x >= y) # False 大于等于
print(x <= y) # True 小于等于
逻辑运算符
a = True
b = False
print(a and b) # False 与(两个都为True才为True)
print(a or b) # True 或(至少一个为True就为True)
print(not a) # False 非(取反)
赋值运算符
x = 10
x += 5 # 等价于 x = x + 5,x现在是15
x -= 3 # 等价于 x = x - 3,x现在是12
x *= 2 # 等价于 x = x * 2,x现在是24
x /= 4 # 等价于 x = x / 4,x现在是6.0
5. 字符串操作
创建字符串
s1 = "Hello"
s2 = 'World'
s3 = """这是
多行字符串"""
# 包含引号的字符串
s4 = "他说:'你好'"
s5 = '她说:"Hello"'
字符串常用操作
s = "Hello, Python!"
# 长度
print(len(s)) # 14
# 索引(从0开始)
print(s[0]) # 'H'
print(s[-1]) # '!'(倒数第一个)
# 切片 [start:end:step]
print(s[0:5]) # 'Hello'
print(s[7:]) # 'Python!'
print(s[::-1]) # '!nohtyP ,olleH'(反转字符串)
# 常用方法
print(s.upper()) # 'HELLO, PYTHON!'
print(s.lower()) # 'hello, python!'
print(s.replace("Python", "World")) # 'Hello, World!'
print(s.split(", ")) # ['Hello', 'Python!']
print(s.find("Python")) # 7(返回索引位置)
print(s.startswith("Hello")) # True
f-string 格式化
name = "Alice"
age = 25
score = 95.5
# f-string(推荐方式)
print(f"我叫{name},今年{age}岁")
print(f"分数:{score:.1f}") # 保留1位小数:95.5
print(f"明年{age + 1}岁") # 可以包含表达式
# 格式化数字
price = 19.9
print(f"价格:¥{price:.2f}") # 价格:¥19.90
6. 列表(List)
列表是Python中最常用的数据结构,可以存储任意类型的元素。
创建和访问列表
# 创建列表
fruits = ["苹果", "香蕉", "橙子"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14] # 可以混合类型
# 访问元素
print(fruits[0]) # '苹果'
print(fruits[-1]) # '橙子'
print(fruits[1:3]) # ['香蕉', '橙子'](切片)
列表常用操作
fruits = ["苹果", "香蕉", "橙子"]
# 添加元素
fruits.append("葡萄") # 末尾添加
fruits.insert(1, "草莓") # 在索引1处插入
fruits.extend(["西瓜", "芒果"]) # 批量添加
# 删除元素
fruits.remove("香蕉") # 删除指定元素
last = fruits.pop() # 删除并返回最后一个元素
del fruits[0] # 删除索引0的元素
# 其他操作
print(len(fruits)) # 列表长度
print(fruits.count("苹果")) # 统计出现次数
fruits.sort() # 排序
fruits.reverse() # 反转
列表推导式
# 传统方式
squares = []
for x in range(1, 6):
squares.append(x ** 2)
# 列表推导式(简洁优雅)
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# 带条件的列表推导式
even_squares = [x ** 2 for x in range(1, 11) if x % 2 == 0]
print(even_squares) # [4, 16, 36, 64, 100]
# 字符串处理示例
words = ["hello", "world", "python"]
upper_words = [w.upper() for w in words]
print(upper_words) # ['HELLO', 'WORLD', 'PYTHON']
7. 元组与集合
元组(Tuple)
元组与列表类似,但不可修改(immutable)。
# 创建元组
point = (3, 4)
colors = ("红", "绿", "蓝")
single = (42,) # 单元素元组需要逗号
# 访问元素
print(point[0]) # 3
print(point[-1]) # 4
# 元组解包
x, y = point
print(f"x={x}, y={y}") # x=3, y=4
# 不可修改
# point[0] = 5 # ❌ 报错!TypeError
# 用途:函数返回多个值
def get_min_max(numbers):
return min(numbers), max(numbers)
lo, hi = get_min_max([3, 1, 4, 1, 5])
print(f"最小值: {lo}, 最大值: {hi}") # 最小值: 1, 最大值: 5
集合(Set)
集合是无序、不重复的元素集合。
# 创建集合
fruits = {"苹果", "香蕉", "橙子", "苹果"} # 重复的会被去除
print(fruits) # {'苹果', '香蕉', '橙子'}
# 集合操作
fruits.add("葡萄") # 添加元素
fruits.remove("香蕉") # 删除元素
# 集合运算
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # {1, 2, 3, 4, 5, 6} 并集
print(a & b) # {3, 4} 交集
print(a - b) # {1, 2} 差集
print(a ^ b) # {1, 2, 5, 6} 对称差集
# 实用场景:去重
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers))
print(unique) # [1, 2, 3, 4](顺序可能变化)
8. 字典(Dictionary)
字典是键值对的集合,类似于现实中的"通讯录"。
创建和访问字典
# 创建字典
student = {
"name": "Alice",
"age": 20,
"grades": [85, 92, 78]
}
# 访问值
print(student["name"]) # 'Alice'
print(student.get("email", "无")) # '无'(key不存在时返回默认值)
# 修改和添加
student["age"] = 21 # 修改
student["email"] = "a@b.com" # 新增
# 删除
del student["email"]
# 遍历
for key, value in student.items():
print(f"{key}: {value}")
字典推导式
# 生成平方数字典
squares = {x: x**2 for x in range(1, 6)}
print(squares) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# 字符串计数
text = "hello world"
char_count = {}
for char in text:
char_count[char] = char_count.get(char, 0) + 1
print(char_count) # {'h': 1, 'e': 1, 'l': 3, ...}
9. 条件判断
if-elif-else
score = 85
if score >= 90:
grade = "优秀"
elif score >= 80:
grade = "良好"
elif score >= 60:
grade = "及格"
else:
grade = "不及格"
print(f"成绩: {score}, 等级: {grade}") # 成绩: 85, 等级: 良好
条件表达式(三元运算符)
age = 20
status = "成年" if age >= 18 else "未成年"
print(status) # '成年'
多条件判断
username = "admin"
password = "123456"
if username == "admin" and password == "123456":
print("登录成功")
else:
print("用户名或密码错误")
# in 关键字
fruits = ["苹果", "香蕉", "橙子"]
if "苹果" in fruits:
print("有苹果!")
10. 循环结构
for 循环
# 遍历列表
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(2, 8): # 2, 3, 4, 5, 6, 7
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8(步长为2)
print(i)
# 带索引遍历
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}")
while 循环
# 基本while循环
count = 0
while count < 5:
print(count)
count += 1
# 用户输入验证
while True:
user_input = input("请输入密码:")
if user_input == "secret":
print("密码正确!")
break
print("密码错误,请重试。")
break 和 continue
# break:跳出整个循环
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
# continue:跳过本次循环
for i in range(10):
if i % 2 == 0:
continue
print(i) # 1, 3, 5, 7, 9
11. 函数
定义和调用函数
def greet(name):
"""问候函数(这是文档字符串)"""
return f"你好,{name}!"
message = greet("Alice")
print(message) # '你好,Alice!'
参数类型
# 默认参数
def greet(name, greeting="你好"):
return f"{greeting},{name}!"
print(greet("Alice")) # '你好,Alice!'
print(greet("Alice", "Hello")) # 'Hello,Alice!'
# 可变参数 *args
def sum_all(*numbers):
return sum(numbers)
print(sum_all(1, 2, 3)) # 6
print(sum_all(1, 2, 3, 4, 5)) # 15
# 关键字参数 **kwargs
def print_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
print_info(name="Alice", age=25, city="北京")
Lambda 函数
# 普通函数
def square(x):
return x ** 2
# Lambda(匿名函数)
square = lambda x: x ** 2
print(square(5)) # 25
# 常见用途:排序
students = [("Alice", 85), ("Bob", 92), ("Charlie", 78)]
students.sort(key=lambda s: s[1], reverse=True)
print(students) # [('Bob', 92), ('Alice', 85), ('Charlie', 78)]
12. 文件操作
读写文本文件
# 写入文件
with open("test.txt", "w", encoding="utf-8") as f:
f.write("第一行\n")
f.write("第二行\n")
f.write("第三行\n")
# 读取文件
with open("test.txt", "r", encoding="utf-8") as f:
content = f.read()
print(content)
# 逐行读取
with open("test.txt", "r", encoding="utf-8") as f:
for line in f:
print(line.strip()) # strip() 去除换行符
# 追加内容
with open("test.txt", "a", encoding="utf-8") as f:
f.write("追加的一行\n")
CSV文件操作
import csv
# 写入CSV
with open("students.csv", "w", newline="", encoding="utf-8") as f:
writer = csv.writer(f)
writer.writerow(["姓名", "年龄", "成绩"])
writer.writerow(["Alice", 20, 85])
writer.writerow(["Bob", 21, 92])
# 读取CSV
with open("students.csv", "r", encoding="utf-8") as f:
reader = csv.reader(f)
for row in reader:
print(row) # ['姓名', '年龄', '成绩']
13. 异常处理
try-except
try:
num = int(input("请输入一个数字:"))
result = 100 / num
print(f"结果是: {result}")
except ValueError:
print("输入的不是有效数字!")
except ZeroDivisionError:
print("不能除以零!")
except Exception as e:
print(f"发生了错误: {e}")
else:
print("没有发生错误") # 可选
finally:
print("无论如何都会执行") # 可选
自定义异常
class AgeError(Exception):
def __init__(self, age, message="年龄必须在0-150之间"):
self.age = age
self.message = message
super().__init__(self.message)
def set_age(age):
if age < 0 or age > 150:
raise AgeError(age)
return age
try:
set_age(200)
except AgeError as e:
print(f"错误: {e.message},你输入的是 {e.age}")
14. 模块与包
使用内置模块
# 数学模块
import math
print(math.sqrt(16)) # 4.0
print(math.pi) # 3.141592653589793
# 随机数模块
import random
print(random.randint(1, 10)) # 1-10的随机整数
print(random.choice(["苹果", "香蕉"])) # 随机选择一个
random.shuffle([1, 2, 3, 4, 5]) # 打乱列表
# 日期时间模块
from datetime import datetime
now = datetime.now()
print(now.strftime("%Y-%m-%d %H:%M:%S")) # 2026-05-28 08:00:00
# JSON模块
import json
data = {"name": "Alice", "age": 25}
json_str = json.dumps(data, ensure_ascii=False) # 转JSON字符串
print(json_str) # {"name": "Alice", "age": 25}
安装第三方库
# 使用pip安装
pip install requests
pip install numpy pandas
# 查看已安装的库
pip list
# 导出和安装依赖
pip freeze > requirements.txt
pip install -r requirements.txt
15. 面向对象编程
类和对象
class Dog:
"""狗类"""
# 类属性(所有实例共享)
species = "犬科"
def __init__(self, name, age):
"""初始化方法(构造函数)"""
self.name = name # 实例属性
self.age = age
def bark(self):
"""实例方法"""
return f"{self.name}:汪汪!"
def __str__(self):
"""字符串表示"""
return f"Dog(name={self.name}, age={self.age})"
# 创建对象
dog1 = Dog("旺财", 3)
dog2 = Dog("小白", 2)
print(dog1.bark()) # '旺财:汪汪!'
print(dog1) # Dog(name=旺财, age=3)
print(Dog.species) # '犬科'
继承
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("子类必须实现此方法")
class Cat(Animal):
def speak(self):
return f"{self.name}:喵喵!"
class Dog(Animal):
def speak(self):
return f"{self.name}:汪汪!"
# 多态
animals = [Cat("小花"), Dog("旺财"), Cat("咪咪")]
for animal in animals:
print(animal.speak())
# 小花:喵喵!
# 旺财:汪汪!
# 咪咪:喵喵!
封装
class BankAccount:
def __init__(self, balance=0):
self.__balance = balance # 私有属性(双下划线)
def deposit(self, amount):
if amount > 0:
self.__balance += amount
return True
return False
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
return True
return False
def get_balance(self):
return self.__balance
account = BankAccount(1000)
account.deposit(500)
print(account.get_balance()) # 1500
# print(account.__balance) # ❌ 无法直接访问私有属性
16. 实战项目:通讯录管理系统
import json
import os
CONTACTS_FILE = "contacts.json"
def load_contacts():
"""加载通讯录数据"""
if os.path.exists(CONTACTS_FILE):
with open(CONTACTS_FILE, "r", encoding="utf-8") as f:
return json.load(f)
return {}
def save_contacts(contacts):
"""保存通讯录数据"""
with open(CONTACTS_FILE, "w", encoding="utf-8") as f:
json.dump(contacts, f, ensure_ascii=False, indent=2)
def add_contact(contacts):
"""添加联系人"""
name = input("请输入姓名:").strip()
if not name:
print("姓名不能为空!")
return
if name in contacts:
print(f"联系人 {name} 已存在!")
return
phone = input("请输入电话:").strip()
email = input("请输入邮箱(可选):").strip()
note = input("请输入备注(可选):").strip()
contacts[name] = {
"电话": phone,
"邮箱": email if email else "未填写",
"备注": note if note else "无"
}
save_contacts(contacts)
print(f"✅ 联系人 {name} 添加成功!")
def search_contact(contacts):
"""搜索联系人"""
keyword = input("请输入搜索关键词:").strip()
results = {k: v for k, v in contacts.items()
if keyword in k or keyword in str(v)}
if not results:
print("未找到匹配的联系人。")
return
print(f"\n找到 {len(results)} 个匹配结果:")
for name, info in results.items():
print(f" 姓名: {name}")
print(f" 电话: {info['电话']}")
print(f" 邮箱: {info['邮箱']}")
print(f" 备注: {info['备注']}")
print(" " + "-" * 20)
def list_contacts(contacts):
"""列出所有联系人"""
if not contacts:
print("通讯录为空。")
return
print(f"\n通讯录共有 {len(contacts)} 个联系人:")
for i, (name, info) in enumerate(contacts.items(), 1):
print(f" {i}. {name} - {info['电话']}")
def delete_contact(contacts):
"""删除联系人"""
name = input("请输入要删除的姓名:").strip()
if name in contacts:
confirm = input(f"确认删除 {name}?(y/n): ").strip().lower()
if confirm == 'y':
del contacts[name]
save_contacts(contacts)
print(f"✅ 联系人 {name} 已删除。")
else:
print(f"联系人 {name} 不存在。")
def main():
"""主函数"""
contacts = load_contacts()
menu = """
╔══════════════════════════════╗
║ 📱 通讯录管理系统 ║
╠══════════════════════════════╣
║ 1. 添加联系人 ║
║ 2. 搜索联系人 ║
║ 3. 查看所有联系人 ║
║ 4. 删除联系人 ║
║ 5. 退出 ║
╚══════════════════════════════╝
"""
while True:
print(menu)
choice = input("请选择操作 (1-5): ").strip()
if choice == "1":
add_contact(contacts)
elif choice == "2":
search_contact(contacts)
elif choice == "3":
list_contacts(contacts)
elif choice == "4":
delete_contact(contacts)
elif choice == "5":
print("👋 再见!")
break
else:
print("❌ 无效选择,请重新输入。")
if __name__ == "__main__":
main()
学习建议
- 多动手:看懂不代表会写,一定要自己敲代码
- 多练习:每天至少写30分钟代码
- 多思考:理解代码背后的逻辑,而不是死记硬背
- 多查文档:遇到问题先查官方文档 https://docs.python.org/3/
推荐练习平台
- LeetCode:算法练习
- HackerRank:编程挑战
- Codewars:编程游戏化练习
📅 本教程由AI原创编写,最后更新:2026年5月28日