引言:为什么选择Python作为编程入门语言

Python作为一种高级编程语言,自1991年由Guido van Rossum首次发布以来,已经成为全球最受欢迎的编程语言之一。它的设计理念强调代码的可读性和简洁性,使得初学者能够快速上手,同时为专业开发者提供强大的功能支持。

Python的语法非常接近自然语言,这意味着你可以用更少的代码表达更多的想法。与其他编程语言相比,Python避免了复杂的符号和冗长的代码结构,让编程初学者能够专注于解决问题的逻辑,而不是被语法细节所困扰。

在当今数据科学、人工智能、Web开发、自动化脚本等领域,Python都占据着主导地位。掌握Python基础语法不仅能够帮助你理解编程的核心概念,还能为你打开通往多个热门职业方向的大门。

Python环境搭建:你的第一个Python程序

安装Python解释器

在开始编写Python代码之前,我们需要先安装Python解释器。Python解释器是能够执行Python代码的程序。

步骤1:下载Python

  • 访问Python官方网站:https://www.python.org/downloads/
  • 根据你的操作系统(Windows、macOS或Linux)下载最新版本的Python 3.x
  • 推荐下载Python 3.8或更高版本,因为这些版本包含了最新的功能和安全更新

步骤2:安装Python

  • Windows用户:运行下载的安装程序,务必勾选”Add Python to PATH”选项
  • macOS用户:通常系统预装了Python 2.x,但你需要单独安装Python 3.x
  • Linux用户:大多数Linux发行版预装了Python,可以通过命令python3 --version检查

步骤3:验证安装 打开终端(Windows用户使用命令提示符或PowerShell),输入以下命令:

python --version
# 或者
python3 --version

如果显示类似”Python 3.9.7”的版本信息,说明安装成功。

选择合适的代码编辑器

选择一个好的代码编辑器可以大大提高编程效率。以下是几个推荐的选择:

  1. VS Code (Visual Studio Code):微软开发的免费编辑器,功能强大,插件丰富

  2. PyCharm:JetBrains开发的Python专用IDE

    • 社区版免费,专业版付费
    • 提供强大的调试功能和项目管理工具
  3. Jupyter Notebook:特别适合数据科学和学习Python

    • 可以在浏览器中运行代码,即时看到结果
    • 适合做笔记和实验

编写和运行你的第一个Python程序

现在让我们编写最经典的”Hello, World!“程序:

方法1:使用Python交互式环境

# 在终端输入python或python3
python
>>> print("Hello, World!")
Hello, World!

方法2:创建Python文件

  1. 创建一个新文件,命名为hello.py
  2. 在文件中输入:
print("Hello, World!")
  1. 保存文件
  2. 在终端中运行:
python hello.py
# 或者
python3 hello.py

方法3:使用IDE

  • 在VS Code或PyCharm中创建新文件
  • 输入代码后,右键选择”Run”或使用快捷键运行

Python基础语法:变量与数据类型

变量:数据的容器

变量是编程中最基本的概念之一。你可以把变量想象成一个贴了标签的盒子,盒子里面可以存放各种类型的数据。

在Python中创建变量非常简单,只需要选择一个名字并给它赋值:

# 创建不同类型的变量
name = "Alice"           # 字符串变量
age = 25                 # 整数变量
height = 165.5           # 浮点数变量
is_student = True        # 布尔变量

# 打印变量的值
print("姓名:", name)
print("年龄:", age)
print("身高:", height)
print("是否是学生:", is_student)

变量命名规则:

  • 变量名只能包含字母、数字和下划线
  • 不能以数字开头
  • 不能使用Python的关键字(如if、else、for等)
  • 变量名应该具有描述性(推荐使用蛇形命名法,如user_name

变量赋值的多种方式:

# 基本赋值
x = 10

# 链式赋值
a = b = c = 0

# 同时赋值多个变量
name, age, city = "Bob", 30, "Beijing"

# 使用其他变量赋值
x = 5
y = x * 2  # y的值为10

Python的基本数据类型

Python有几种内置的基本数据类型,每种类型都有其特定的用途和操作方法。

1. 整数(int)

整数是完整的数字,没有小数部分。

# 整数示例
year = 2024
population = 1400000000
negative_number = -100

# 整数运算
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

2. 浮点数(float)

浮点数是带有小数点的数字。

# 浮点数示例
price = 19.99
temperature = -5.5
pi = 3.1415926535

# 浮点数运算
x = 5.5
y = 2.0
print(x + y)   # 7.5
print(x * y)   # 11.0

# 注意浮点数精度问题
result = 0.1 + 0.2
print(result)  # 0.30000000000000004
# 解决方法:使用round()函数或decimal模块
print(round(result, 1))  # 0.3

3. 字符串(str)

字符串是文本数据,用单引号、双引号或三引号括起来。

# 创建字符串
single_quote = 'Hello'
double_quote = "World"
triple_quote = '''这是
多行
字符串'''

# 字符串拼接
first_name = "John"
last_name = "Doe"
full_name = first_name + " " + last_name  # "John Doe"

# 字符串重复
line = "-" * 50  # "--------------------------------------------------"

# 字符串格式化(多种方式)
name = "Alice"
age = 25

# 方式1:使用+拼接
message1 = name + " is " + str(age) + " years old"

# 方式2:使用format()
message2 = "{} is {} years old".format(name, age)

# 方式3:使用f-string(推荐,Python 3.6+)
message3 = f"{name} is {age} years old"

# 常用字符串方法
text = "  Hello, World!  "
print(text.strip())        # "Hello, World!"(去除空格)
print(text.upper())        # "  HELLO, WORLD!  "
print(text.lower())        # "  hello, world!  "
print(text.split(","))     # ['  Hello', ' World!  ']
print(text.find("World"))  # 8(查找位置)
print(text.replace("Hello", "Hi"))  # "  Hi, World!  "

4. 布尔值(bool)

布尔值只有两个:True和False,用于条件判断。

# 布尔值示例
is_raining = True
has_ticket = False

# 比较运算符产生布尔值
age = 18
print(age > 18)      # False
print(age == 18)     # True
print(age != 18)     # False

# 逻辑运算符
a = True
b = False
print(a and b)       # False(两个都为True才为True)
print(a or b)        # True(有一个为True就为True)
print(not a)         # False(取反)

类型转换

有时候我们需要将一种类型的数据转换为另一种类型,这称为类型转换。

# 字符串转整数
age_str = "25"
age_int = int(age_str)
print(age_int + 5)  # 30

# 整数转字符串
number = 100
number_str = str(number)
print("编号:" + number_str)  # "编号:100"

# 浮点数转整数(截断小数部分)
price = 19.99
price_int = int(price)
print(price_int)  # 19

# 整数转浮点数
count = 5
count_float = float(count)
print(count_float)  # 5.0

# 字符串转浮点数
price_str = "19.99"
price_float = float(price_str)
print(price_float + 1)  # 20.99

# 注意:无效的转换会引发错误
# int("abc")  # ValueError: invalid literal for int()

运算符与表达式

算术运算符

算术运算符用于执行数学运算。

# 基本算术运算
a = 15
b = 4

print(f"a + b = {a + b}")   # 19
print(f"a - b = {a - b}")   # 11
print(f"a * b = {a * b}")   # 60
print(f"a / b = {a / b}")   # 3.75
print(f"a // b = {a // b}") # 3(整除)
print(f"a % b = {a % b}")   # 3(取余)
print(f"a ** b = {a ** b}") # 50625(幂运算)

# 复合运算符(简化写法)
x = 10
x += 5    # 等同于 x = x + 5
print(x)  # 15

x *= 2    # 等同于 x = x * 2
print(x)  # 30

比较运算符

比较运算符用于比较两个值,返回布尔值结果。

# 比较运算符示例
x = 10
y = 20

print(x == y)  # False(等于)
print(x != y)  # True(不等于)
print(x > y)   # False(大于)
print(x < y)   # True(小于)
print(x >= 10) # True(大于等于)
print(y <= 20) # True(小于等于)

# 字符串比较
str1 = "apple"
str2 = "banana"
print(str1 < str2)  # True(按字母顺序比较)

# 比较运算符的链式使用
age = 25
print(18 <= age <= 65)  # True(年龄在18-65之间)

逻辑运算符

逻辑运算符用于组合多个条件判断。

# 逻辑运算符示例
age = 25
has_license = True
is_employed = False

# and:两个条件都必须为True
print(age >= 18 and has_license)  # True

# or:至少一个条件为True
print(age >= 18 or is_employed)   # True

# not:取反
print(not is_employed)            # True

# 复杂条件组合
is_eligible = (age >= 18 and age <= 65) and (has_license or is_employed)
print(f"是否符合资格: {is_eligible}")

# 短路求值:如果第一个条件已经能确定结果,就不会计算第二个条件
def check():
    print("这个函数被调用了")
    return True

# 由于第一个条件是False,check()不会被调用
result = False and check()
print(result)  # False

成员运算符

成员运算符用于检查一个值是否在序列(如字符串、列表等)中。

# 成员运算符 in 和 not in
fruits = ["apple", "banana", "orange"]
print("apple" in fruits)      # True
print("grape" not in fruits)  # True

# 在字符串中检查子串
text = "Hello, World!"
print("World" in text)        # True
print("Python" not in text)   # True

# 实际应用:验证密码强度
password = "MyPassword123"
has_upper = any(c.isupper() for c in password)
has_lower = any(c.islower() for c in password)
has_digit = any(c.isdigit() for c in password)

is_strong = has_upper and has_lower and has_digit
print(f"密码强度: {'强' if is_strong else '弱'}")

控制流:让程序做出决策

条件语句(if/elif/else)

条件语句允许程序根据不同的条件执行不同的代码块。

# 基本的if语句
temperature = 25
if temperature > 30:
    print("天气炎热,注意防暑")
    print("建议待在室内")

# if-else语句
score = 85
if score >= 60:
    print("考试通过")
else:
    print("考试未通过")

# if-elif-else语句
grade = 85
if grade >= 90:
    print("优秀")
elif grade >= 80:
    print("良好")
elif grade >= 70:
    print("中等")
elif grade >= 60:
    print("及格")
else:
    print("不及格")

# 嵌套条件语句
age = 20
has_id = True
if age >= 18:
    if has_id:
        print("可以进入酒吧")
    else:
        print("需要携带身份证")
else:
    print("未满18岁,不能进入")

# 多个条件的组合
username = "admin"
password = "123456"
if username == "admin" and password == "123456":
    print("登录成功")
elif username == "admin" or password == "123456":
    print("用户名或密码错误")
else:
    print("登录失败")

# 实际应用:计算器
def calculate(a, b, operator):
    if operator == "+":
        return a + b
    elif operator == "-":
        return a - b
    elif operator == "*":
        return a * b
    elif operator == "/":
        if b == 0:
            return "错误:除数不能为0"
        return a / b
    else:
        return "错误:无效的运算符"

print(calculate(10, 5, "+"))  # 15
print(calculate(10, 0, "/"))  # 错误:除数不能为0

循环语句

循环用于重复执行一段代码,直到满足某个条件为止。

for循环

for循环用于遍历序列(如列表、字符串、范围等)。

# 基本的for循环
for i in range(5):
    print(f"这是第 {i+1} 次循环")

# 遍历列表
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"我喜欢吃{fruit}")

# 遍历字符串
for char in "Python":
    print(char)

# 使用enumerate()获取索引和值
colors = ["red", "green", "blue"]
for index, color in enumerate(colors):
    print(f"颜色 {index}: {color}")

# 使用range()生成数字序列
# range(5) -> 0, 1, 2, 3, 4
# range(2, 6) -> 2, 3, 4, 5
# range(0, 10, 2) -> 0, 2, 4, 6, 8(步长为2)

# 计算1到100的和
total = 0
for i in range(1, 101):
    total += i
print(f"1到100的和是: {total}")

# 列表推导式(for循环的简洁写法)
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]

while循环

while循环在条件为True时重复执行代码块。

# 基本的while循环
count = 0
while count < 5:
    print(f"计数: {count}")
    count += 1

# 使用while循环计算1到100的和
total = 0
i = 1
while i <= 100:
    total += i
    i += 1
print(f"1到100的和是: {total}")

# 使用while循环实现猜数字游戏
import random

secret_number = random.randint(1, 10)
attempts = 0
max_attempts = 3

while attempts < max_attempts:
    guess = int(input(f"猜一个1-10之间的数字(还剩{max_attempts - attempts}次机会): "))
    attempts += 1
    
    if guess == secret_number:
        print(f"恭喜!你猜对了!答案是{secret_number}")
        break
    elif guess < secret_number:
        print("猜小了")
    else:
        print("猜大了")
else:
    print(f"很遗憾,机会用完了。正确答案是{secret_number}")

# 使用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

实际应用:综合示例

让我们通过一个实际的例子来展示控制流的综合应用:

# 学生成绩分析系统
def analyze_scores(scores):
    if not scores:
        print("没有成绩数据")
        return
    
    total = 0
    excellent = 0
    good = 0
    pass_score = 0
    fail = 0
    
    for score in scores:
        total += score
        if score >= 90:
            excellent += 1
        elif score >= 80:
            good += 1
        elif score >= 60:
            pass_score += 1
        else:
            fail += 1
    
    average = total / len(scores)
    
    print(f"学生成绩分析报告")
    print("=" * 40)
    print(f"学生总数: {len(scores)}")
    print(f"平均分: {average:.2f}")
    print(f"优秀(≥90): {excellent}人")
    print(f"良好(80-89): {good}人")
    print(f"及格(60-79): {pass_score}人")
    print(f"不及格(<60): {fail}人")
    
    if average >= 80:
        print("整体表现优秀!")
    elif average >= 70:
        print("整体表现良好")
    else:
        print("需要继续努力")

# 测试数据
student_scores = [85, 92, 78, 95, 68, 88, 91, 72, 83, 90]
analyze_scores(student_scores)

数据结构:组织和管理数据

列表(List)

列表是Python中最常用的数据结构,用于存储有序的元素集合。

# 创建列表
empty_list = []
numbers = [1, 2, 3, 4, 5]
mixed_list = [1, "hello", 3.14, True, [1, 2]]

# 访问列表元素(索引从0开始)
fruits = ["apple", "banana", "orange"]
print(fruits[0])   # "apple"
print(fruits[-1])  # "orange"(负数索引从末尾开始)

# 修改列表元素
fruits[1] = "grape"
print(fruits)  # ["apple", "grape", "orange"]

# 列表切片
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])    # [2, 3, 4](从索引2到4)
print(numbers[:3])     # [0, 1, 2](从开始到2)
print(numbers[6:])     # [6, 7, 8, 9](从6到结束)
print(numbers[::2])    # [0, 2, 4, 6, 8](步长为2)
print(numbers[::-1])   # [9, 8, 7, 6, 5, 4, 3, 2, 1, 0](反转)

# 列表操作
# 添加元素
fruits.append("mango")      # 末尾添加
fruits.insert(1, "pear")    # 指定位置插入
print(fruits)  # ["apple", "pear", "grape", "orange", "mango"]

# 删除元素
removed = fruits.pop()      # 删除并返回最后一个元素
print(removed)  # "mango"
fruits.remove("pear")       # 删除指定元素
print(fruits)  # ["apple", "grape", "orange"]

# 列表长度和查找
print(len(fruits))          # 3
print(fruits.index("grape")) # 1(查找元素位置)
print("apple" in fruits)    # True

# 列表排序
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
numbers.sort()              # 原地排序
print(numbers)  # [1, 1, 2, 3, 4, 5, 6, 9]

numbers.sort(reverse=True)  # 降序排序
print(numbers)  # [9, 6, 5, 4, 3, 2, 1, 1]

# 列表推导式(高级用法)
# 创建平方数列表
squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

# 带条件的列表推导式
even_numbers = [x for x in range(1, 11) if x % 2 == 0]
print(even_numbers)  # [2, 4, 6, 8, 10]

# 嵌套列表推导式
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened)  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

元组(Tuple)

元组是不可变的有序序列,使用圆括号定义。

# 创建元组
empty_tuple = ()
single_tuple = (1,)  # 注意:单元素元组需要逗号
point = (10, 20)
person = ("Alice", 25, "Engineer")

# 访问元组元素
print(point[0])  # 10
print(point[1])  # 20

# 元组解包
x, y = point
print(f"x={x}, y={y}")

# 元组不可变性
# point[0] = 15  # 这会引发TypeError

# 元组的用途
# 1. 函数返回多个值
def get_user_info():
    return ("Bob", 30, "bob@example.com")

name, age, email = get_user_info()
print(f"姓名: {name}, 年龄: {age}, 邮箱: {email}")

# 2. 作为字典的键(因为不可变)
coordinates = {(10, 20): "A", (30, 40): "B"}
print(coordinates[(10, 20)])  # "A"

字典(Dictionary)

字典是键值对的无序集合(Python 3.7+有序),使用花括号定义。

# 创建字典
empty_dict = {}
person = {
    "name": "Alice",
    "age": 25,
    "city": "Beijing",
    "is_student": False
}

# 访问字典元素
print(person["name"])  # "Alice"
print(person.get("age"))  # 25

# 使用get()方法避免KeyError
print(person.get("salary", "N/A"))  # 如果键不存在,返回默认值"N/A"

# 添加/修改元素
person["email"] = "alice@example.com"  # 添加新键值对
person["age"] = 26  # 修改现有值

# 删除元素
removed = person.pop("city")  # 删除并返回值
print(removed)  # "Beijing"

# 检查键是否存在
print("name" in person)  # True

# 遍历字典
for key, value in person.items():
    print(f"{key}: {value}")

# 字典推导式
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict)  # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

# 实际应用:统计词频
text = "apple banana apple orange banana apple"
words = text.split()
word_count = {}
for word in words:
    word_count[word] = word_count.get(word, 0) + 1
print(word_count)  # {'apple': 3, 'banana': 2, 'orange': 1}

集合(Set)

集合是无序的、不重复的元素集合。

# 创建集合
empty_set = set()
fruits_set = {"apple", "banana", "orange"}
numbers_set = {1, 2, 3, 2, 1}  # 自动去重:{1, 2, 3}

# 集合操作
# 添加元素
fruits_set.add("grape")
print(fruits_set)  # {'apple', 'banana', 'orange', 'grape'}

# 删除元素
fruits_set.remove("banana")  # 如果元素不存在会报错
fruits_set.discard("mango")  # 如果元素不存在不会报错

# 集合运算
set_a = {1, 2, 3, 4}
set_b = {3, 4, 5, 6}

print(set_a | set_b)  # 并集:{1, 2, 3, 4, 5, 6}
print(set_a & set_b)  # 交集:{3, 4}
print(set_a - set_b)  # 差集:{1, 2}
print(set_a ^ set_b)  # 对称差集:{1, 2, 5, 6}

# 集合推导式
even_numbers = {x for x in range(1, 11) if x % 2 == 0}
print(even_numbers)  # {2, 4, 6, 8, 10}

# 实际应用:去重
duplicates = [1, 2, 2, 3, 4, 4, 5, 1]
unique = list(set(duplicates))
print(unique)  # [1, 2, 3, 4, 5]

函数:代码复用的艺术

函数的定义与调用

函数是可重用的代码块,用于执行特定任务。

# 定义函数
def greet():
    """打印问候语"""
    print("Hello, World!")

# 调用函数
greet()

# 带参数的函数
def greet_person(name):
    """向指定的人问候"""
    print(f"Hello, {name}!")

greet_person("Alice")
greet_person("Bob")

# 带多个参数的函数
def add_numbers(a, b):
    """计算两个数的和"""
    return a + b

result = add_numbers(5, 3)
print(result)  # 8

# 默认参数
def create_person(name, age=18, city="Unknown"):
    """创建个人信息"""
    return {
        "name": name,
        "age": age,
        "city": city
    }

person1 = create_person("Alice")
person2 = create_person("Bob", 25)
person3 = create_person("Charlie", 30, "Shanghai")
print(person1)  # {'name': 'Alice', 'age': 18, 'city': 'Unknown'}
print(person2)  # {'name': 'Bob', 'age': 25, 'city': 'Unknown'}
print(person3)  # {'name': 'Charlie', 'age': 30, 'city': 'Shanghai'}

# 关键字参数(位置无关)
def display_info(name, age, city):
    print(f"姓名: {name}, 年龄: {age}, 城市: {city}")

display_info(age=25, city="Beijing", name="Alice")

变量作用域

理解变量的作用域对于编写正确的函数很重要。

# 全局变量
global_var = "我是全局变量"

def test_scope():
    # 局部变量
    local_var = "我是局部变量"
    print(f"函数内部访问局部变量: {local_var}")
    print(f"函数内部访问全局变量: {global_var}")

test_scope()
# print(local_var)  # 错误:local_var在函数外部不可访问

# 函数内部修改全局变量(需要使用global关键字)
counter = 0

def increment():
    global counter  # 声明使用全局变量
    counter += 1

increment()
increment()
print(counter)  # 2

# LEGB规则:Python查找变量的顺序
# L: Local(局部) -> E: Enclosing(嵌套函数) -> G: Global(全局) -> B: Built-in(内置)

匿名函数(Lambda)

Lambda函数是小型的、匿名的函数。

# 基本语法:lambda 参数: 表达式

# 示例1:简单的lambda
square = lambda x: x ** 2
print(square(5))  # 25

# 示例2:带多个参数
add = lambda a, b: a + b
print(add(3, 4))  # 7

# 示例3:在函数中使用lambda
def apply_operation(x, y, operation):
    return operation(x, y)

result = apply_operation(10, 5, lambda a, b: a * b)
print(result)  # 50

# 示例4:与map()函数结合
numbers = [1, 2, 3, 4, 5]
squares = list(map(lambda x: x ** 2, numbers))
print(squares)  # [1, 4, 9, 16, 25]

# 示例5:与filter()函数结合
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # [2, 4, 6, 8, 10]

# 示例6:与sorted()函数结合
students = [
    {"name": "Alice", "age": 25},
    {"name": "Bob", "age": 20},
    {"name": "Charlie", "age": 23}
]
# 按年龄排序
sorted_students = sorted(students, key=lambda x: x["age"])
print(sorted_students)

高级函数技巧

装饰器(Decorator)

装饰器是修改函数行为的函数。

# 简单的装饰器示例
def my_decorator(func):
    def wrapper():
        print("函数执行前")
        func()
        print("函数执行后")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

say_hello()
# 输出:
# 函数执行前
# Hello!
# 函数执行后

# 带参数的装饰器
def repeat(num_times):
    def decorator_repeat(func):
        def wrapper(*args, **kwargs):
            for _ in range(num_times):
                result = func(*args, **kwargs)
            return result
        return wrapper
    return decorator_repeat

@repeat(num_times=3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
# 输出3次:Hello, Alice!

# 实际应用:计时装饰器
import time

def timer(func):
    def wrapper(*args, **kwargs):
        start = time.time()
        result = func(*args, **kwargs)
        end = time.time()
        print(f"{func.__name__} 执行时间: {end - start:.4f}秒")
        return result
    return wrapper

@timer
def slow_function():
    time.sleep(1)

slow_function()  # slow_function 执行时间: 1.0012秒

递归函数

递归函数是调用自身的函数。

# 阶乘函数(递归实现)
def factorial(n):
    """计算n的阶乘"""
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

print(factorial(5))  # 120

# 斐波那契数列(递归实现)
def fibonacci(n):
    """计算第n个斐波那契数"""
    if n <= 1:
        return n
    else:
        return fibonacci(n - 1) + fibonacci(n - 2)

print(fibonacci(10))  # 55

# 递归的注意事项:避免无限递归
def countdown(n):
    if n <= 0:
        print("发射!")
        return
    print(n)
    countdown(n - 1)

countdown(5)
# 输出:5, 4, 3, 2, 1, 发射!

文件操作:读写数据

读取文件

文件操作是程序与外部数据交互的重要方式。

# 方法1:使用open()和close()(需要手动关闭)
file = open("example.txt", "r")  # r表示读取模式
content = file.read()
file.close()
print(content)

# 方法2:使用with语句(推荐,自动关闭文件)
try:
    with open("example.txt", "r", encoding="utf-8") as file:
        content = file.read()
        print(content)
except FileNotFoundError:
    print("文件不存在")

# 读取大文件(逐行读取)
try:
    with open("large_file.txt", "r", encoding="utf-8") as file:
        for line in file:
            print(line.strip())  # strip()去除换行符和空格
except FileNotFoundError:
    print("文件不存在")

# 读取文件的不同方式
with open("example.txt", "r", encoding="utf-8") as file:
    # read():读取整个文件内容
    content = file.read()
    
    # readline():读取一行
    file.seek(0)  # 回到文件开头
    first_line = file.readline()
    
    # readlines():读取所有行到列表
    file.seek(0)
    all_lines = file.readlines()

写入文件

# 写入文件(覆盖模式)
with open("output.txt", "w", encoding="utf-8") as file:
    file.write("这是第一行\n")
    file.write("这是第二行\n")

# 追加模式(在文件末尾添加内容)
with open("output.txt", "a", encoding="utf-8") as file:
    file.write("这是追加的一行\n")

# 写入多行
lines = ["第一行\n", "第二行\n", "第三行\n"]
with open("output.txt", "w", encoding="utf-8") as file:
    file.writelines(lines)

# 实际应用:日志记录器
def log_message(message, level="INFO"):
    """将消息写入日志文件"""
    from datetime import datetime
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    log_entry = f"[{timestamp}] [{level}] {message}\n"
    
    with open("app.log", "a", encoding="utf-8") as file:
        file.write(log_entry)

log_message("程序启动")
log_message("发生错误", "ERROR")
log_message("程序正常结束")

处理CSV文件

CSV(逗号分隔值)是常见的数据格式。

import csv

# 读取CSV文件
def read_csv_file(filename):
    """读取CSV文件并返回数据列表"""
    data = []
    try:
        with open(filename, "r", encoding="utf-8", newline='') as file:
            reader = csv.reader(file)
            for row in reader:
                data.append(row)
    except FileNotFoundError:
        print(f"文件 {filename} 不存在")
    return data

# 写入CSV文件
def write_csv_file(filename, data):
    """将数据写入CSV文件"""
    with open(filename, "w", encoding="utf-8", newline='') as file:
        writer = csv.writer(file)
        writer.writerows(data)

# 示例:处理学生成绩
student_data = [
    ["姓名", "数学", "英语", "科学"],
    ["Alice", "92", "88", "95"],
    ["Bob", "78", "85", "82"],
    ["Charlie", "88", "91", "89"]
]

# 写入数据
write_csv_file("students.csv", student_data)

# 读取数据
loaded_data = read_csv_file("students.csv")
for row in loaded_data:
    print(row)

# 使用DictReader和DictWriter(更方便)
def process_students_dict(filename):
    """使用字典方式处理CSV"""
    # 写入
    with open(filename, "w", encoding="utf-8", newline='') as file:
        fieldnames = ["name", "math", "english", "science"]
        writer = csv.DictWriter(file, fieldnames=fieldnames)
        writer.writeheader()
        writer.writerow({"name": "Alice", "math": 92, "english": 88, "science": 95})
        writer.writerow({"name": "Bob", "math": 78, "english": 85, "science": 82})
    
    # 读取
    with open(filename, "r", encoding="utf-8", newline='') as file:
        reader = csv.DictReader(file)
        for row in reader:
            print(f"{row['name']}: 数学={row['math']}, 英语={row['english']}")

process_students_dict("students_dict.csv")

异常处理:让程序更健壮

基本异常处理

异常处理是处理程序运行时错误的机制。

# 基本语法
try:
    # 可能引发异常的代码
    result = 10 / 0
except ZeroDivisionError:
    # 处理特定异常
    print("错误:除数不能为0")
except ValueError:
    # 处理其他异常
    print("错误:无效的值")
except Exception as e:
    # 处理所有其他异常
    print(f"发生未知错误: {e}")
else:
    # 如果没有异常发生,执行这里的代码
    print("计算成功")
finally:
    # 无论是否发生异常,都会执行
    print("清理工作完成")

# 多个except块
try:
    number = int(input("请输入一个整数: "))
    result = 100 / number
    print(f"结果是: {result}")
except ValueError:
    print("错误:请输入有效的整数")
except ZeroDivisionError:
    print("错误:不能输入0")
except KeyboardInterrupt:
    print("\n用户中断了程序")
except Exception as e:
    print(f"发生错误: {e}")

自定义异常

# 自定义异常类
class InvalidAgeError(Exception):
    """当年龄不在有效范围内时抛出"""
    pass

class InsufficientFundsError(Exception):
    """当余额不足时抛出"""
    pass

# 使用自定义异常
def set_age(age):
    if age < 0 or age > 150:
        raise InvalidAgeError(f"年龄 {age} 不在有效范围内(0-150)")
    return age

def withdraw(balance, amount):
    if amount > balance:
        raise InsufficientFundsError(f"余额不足,当前余额: {balance}, 需要: {amount}")
    return balance - amount

# 使用示例
try:
    age = set_age(200)
except InvalidAgeError as e:
    print(f"年龄设置错误: {e}")

try:
    new_balance = withdraw(100, 150)
except InsufficientFundsError as e:
    print(f"取款失败: {e}")

实际应用:健壮的文件处理

def safe_file_copy(source, destination):
    """安全地复制文件内容"""
    try:
        # 打开源文件
        with open(source, "r", encoding="utf-8") as src_file:
            content = src_file.read()
        
        # 写入目标文件
        with open(destination, "w", encoding="utf-8") as dest_file:
            dest_file.write(content)
        
        print(f"成功复制文件: {source} -> {destination}")
        return True
        
    except FileNotFoundError:
        print(f"错误:源文件 {source} 不存在")
        return False
    except PermissionError:
        print(f"错误:没有权限访问文件")
        return False
    except IOError as e:
        print(f"文件操作错误: {e}")
        return False
    except Exception as e:
        print(f"未知错误: {e}")
        return False

# 使用示例
safe_file_copy("source.txt", "destination.txt")

模块和包:组织代码

导入模块

模块是包含Python代码的文件,可以被其他程序导入使用。

# 导入整个模块
import math
print(math.sqrt(16))  # 4.0
print(math.pi)        # 3.141592653589793

# 导入特定函数/变量
from math import sqrt, pi
print(sqrt(16))       # 4.0
print(pi)             # 3.141592653589793

# 导入并重命名
import math as m
print(m.sqrt(16))     # 4.0

# 导入多个项目
from math import sqrt, sin, cos

# 导入所有内容(不推荐,可能导致命名冲突)
# from math import *

创建自己的模块

创建一个名为my_utils.py的文件:

# my_utils.py 文件内容
def add(a, b):
    """返回两个数的和"""
    return a + b

def multiply(a, b):
    """返回两个数的积"""
    return a * b

PI = 3.14159

def circle_area(radius):
    """计算圆的面积"""
    return PI * radius ** 2

# 这个代码块只在直接运行此文件时执行
if __name__ == "__main__":
    # 测试代码
    print("测试模块功能")
    print(add(2, 3))
    print(circle_area(5))

在另一个文件中使用这个模块:

# main.py
import my_utils

result = my_utils.add(5, 3)
print(result)  # 8

area = my_utils.circle_area(10)
print(area)  # 314.159

# 或者
from my_utils import add, circle_area

print(add(2, 3))  # 5
print(circle_area(5))  # 78.53975

包(Package)

包是包含多个模块的目录。

my_package/
├── __init__.py
├── module1.py
└── module2.py
# my_package/__init__.py
# 可以为空,也可以定义包的初始化代码
print("my_package 被导入")

# my_package/module1.py
def function1():
    return "来自module1"

# my_package/module2.py
def function2():
    return "来自module2"

# 使用包
from my_package.module1 import function1
from my_package.module2 import function2

print(function1())  # 来自module1
print(function2())  # 来自module2

常用标准库模块

Python拥有丰富的标准库,以下是几个常用的模块:

# 1. random - 随机数生成
import random

# 生成随机整数
print(random.randint(1, 100))  # 1-100之间的随机整数

# 随机选择
fruits = ["apple", "banana", "orange"]
print(random.choice(fruits))  # 随机选择一个

# 随机打乱
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)  # 随机顺序

# 2. datetime - 日期时间处理
from datetime import datetime, timedelta

now = datetime.now()
print(now)  # 2024-01-15 10:30:45.123456

# 格式化日期
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)  # 2024-01-15 10:30:45

# 日期计算
tomorrow = now + timedelta(days=1)
print(tomorrow)

# 3. os - 操作系统接口
import os

# 获取当前工作目录
print(os.getcwd())

# 列出目录内容
print(os.listdir('.'))

# 检查文件是否存在
print(os.path.exists("example.txt"))

# 创建目录
os.makedirs("new_folder", exist_ok=True)

# 4. sys - 系统相关
import sys

# Python版本
print(sys.version)

# 命令行参数
print(sys.argv)

# 退出程序
# sys.exit(0)

# 5. json - JSON数据处理
import json

# Python对象转JSON字符串
data = {"name": "Alice", "age": 25, "city": "Beijing"}
json_str = json.dumps(data, indent=4)
print(json_str)

# JSON字符串转Python对象
loaded_data = json.loads(json_str)
print(loaded_data)

# 读写JSON文件
with open("data.json", "w") as f:
    json.dump(data, f, indent=4)

with open("data.json", "r") as f:
    loaded = json.load(f)
    print(loaded)

面向对象编程(OOP)基础

类和对象

面向对象编程是一种编程范式,使用”类”和”对象”来组织代码。

# 定义类
class Dog:
    """狗的类"""
    
    # 类属性(所有实例共享)
    species = "Canis familiaris"
    
    # 初始化方法(构造函数)
    def __init__(self, name, age, breed):
        # 实例属性
        self.name = name
        self.age = age
        self.breed = breed
    
    # 实例方法
    def bark(self):
        return f"{self.name} 在叫!"
    
    def describe(self):
        return f"{self.name} 是一只 {self.age} 岁的 {self.breed}"
    
    def __str__(self):
        """字符串表示"""
        return f"Dog({self.name}, {self.age}, {self.breed})"

# 创建对象(实例化)
dog1 = Dog("Buddy", 3, "Golden Retriever")
dog2 = Dog("Max", 5, "German Shepherd")

# 访问属性和方法
print(dog1.name)        # Buddy
print(dog1.age)         # 3
print(dog1.bark())      # Buddy 在叫!
print(dog1.describe())  # Buddy 是一只 3 岁的 Golden Retriever
print(dog1)             # Dog(Buddy, 3, Golden Retriever)

# 类属性访问
print(Dog.species)      # Canis familiaris
print(dog1.species)     # Canis familiaris

继承和多态

# 继承示例
class Animal:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def speak(self):
        return "未知的声音"
    
    def describe(self):
        return f"{self.name} 是 {self.age} 岁的动物"

class Cat(Animal):
    def __init__(self, name, age, color):
        super().__init__(name, age)  # 调用父类的初始化方法
        self.color = color
    
    def speak(self):
        return "喵喵喵"
    
    def describe(self):
        return f"{self.name} 是 {self.age} 岁的 {self.color} 色猫"

class Dog(Animal):
    def speak(self):
        return "汪汪汪"
    
    def fetch(self):
        return f"{self.name} 在捡球"

# 多态:不同对象对同一方法的不同响应
animals = [
    Animal("动物", 1),
    Cat("咪咪", 2, "白色"),
    Dog("旺财", 3)
]

for animal in animals:
    print(f"{animal.name}: {animal.speak()}")
# 输出:
# 动物: 未知的声音
# 咪咪: 喵喵喵
# 旺财: 汪汪汪

封装和属性

class BankAccount:
    def __init__(self, owner, initial_balance=0):
        self.owner = owner
        self._balance = initial_balance  # 使用下划线表示"受保护"的属性
    
    def deposit(self, amount):
        if amount > 0:
            self._balance += amount
            return f"存入 {amount},当前余额: {self._balance}"
        else:
            return "存款金额必须大于0"
    
    def withdraw(self, amount):
        if 0 < amount <= self._balance:
            self._balance -= amount
            return f"取出 {amount},当前余额: {self._balance}"
        else:
            return "取款金额无效"
    
    # 使用property装饰器创建只读属性
    @property
    def balance(self):
        return self._balance
    
    # 使用property创建计算属性
    @property
    def is_rich(self):
        return self._balance > 100000

# 使用示例
account = BankAccount("Alice", 1000)
print(account.deposit(500))   # 存入 500,当前余额: 1500
print(account.withdraw(200))  # 取出 200,当前余额: 1300
print(account.balance)        # 1300(只读)
print(account.is_rich)        # False

# 尝试直接修改balance会失败(因为没有setter)
# account.balance = 5000  # AttributeError

实用编程技巧

代码风格和最佳实践

PEP 8编码规范

PEP 8是Python的官方编码风格指南,遵循这些规范可以让代码更易读。

# 好的命名示例
def calculate_student_average(scores):
    """计算学生的平均分"""
    if not scores:
        return 0
    return sum(scores) / len(scores)

# 坏的命名示例
def calc(s):
    return sum(s)/len(s) if s else 0

# 好的代码结构
def process_data(data):
    """处理数据的清晰步骤"""
    # 1. 验证输入
    if not data:
        return None
    
    # 2. 清理数据
    cleaned = [x for x in data if x is not None]
    
    # 3. 计算结果
    result = sum(cleaned) / len(cleaned)
    
    # 4. 返回
    return result

# 注释应该解释"为什么",而不是"做什么"
# 不好的注释
x = x + 1  # x加1

# 好的注释
x = x + 1  # 补偿数组索引从0开始

代码格式化工具

# 使用black自动格式化代码
# 安装:pip install black
# 使用:black your_file.py

# 使用flake8检查代码质量
# 安装:pip install flake8
# 使用:flake8 your_file.py

# 示例:需要格式化的代码
def bad_format(a,b,c):
    x=a+b;    y=c*2;    return x+y

# 格式化后:
def bad_format(a, b, c):
    x = a + b
    y = c * 2
    return x + y

调试技巧

# 1. 使用print()调试
def calculate_discount(price, discount):
    print(f"原始价格: {price}, 折扣: {discount}")  # 调试信息
    final_price = price * (1 - discount)
    print(f"最终价格: {final_price}")  # 调试信息
    return final_price

# 2. 使用logging模块(更专业)
import logging

# 配置日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='app.log'
)

def divide(a, b):
    logging.debug(f"尝试计算 {a}/{b}")
    try:
        result = a / b
        logging.info(f"计算成功: {result}")
        return result
    except ZeroDivisionError:
        logging.error("除数不能为0")
        return None

# 3. 使用pdb调试器
import pdb

def complex_calculation(x, y, z):
    result = x * y
    pdb.set_trace()  # 设置断点
    result = result + z
    return result

# 4. 使用assert进行测试
def calculate_area(length, width):
    assert length > 0, "长度必须为正数"
    assert width > 0, "宽度必须为正数"
    return length * width

性能优化技巧

# 1. 使用列表推导式而不是循环
# 慢的方式
squares = []
for i in range(1000):
    squares.append(i ** 2)

# 快的方式
squares = [i ** 2 for i in range(1000)]

# 2. 使用生成器处理大数据
# 内存友好的方式
def read_large_file(filename):
    with open(filename, 'r') as f:
        for line in f:
            yield line.strip()

# 使用
for line in read_large_file("huge_file.txt"):
    process(line)

# 3. 使用集合进行快速查找
# 慢的方式(列表)
items = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
if 5 in items:  # O(n)
    print("找到")

# 快的方式(集合)
items_set = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
if 5 in items_set:  # O(1)
    print("找到")

# 4. 使用join()连接字符串
# 慢的方式
result = ""
for i in range(100):
    result += str(i)  # 每次都创建新字符串

# 快的方式
result = "".join(str(i) for i in range(100))

# 5. 使用f-string而不是format()或%
name = "Alice"
age = 25
# 慢
message1 = "{} is {} years old".format(name, age)
message2 = "%s is %s years old" % (name, age)
# 快
message3 = f"{name} is {age} years old"

测试基础

# 单元测试示例
import unittest

def add(a, b):
    return a + b

def multiply(a, b):
    return a * b

class TestMathOperations(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(2, 3), 5)
        self.assertEqual(add(-1, 1), 0)
        self.assertEqual(add(0, 0), 0)
    
    def test_multiply(self):
        self.assertEqual(multiply(2, 3), 6)
        self.assertEqual(multiply(-2, 3), -6)
        self.assertEqual(multiply(0, 5), 0)

# 运行测试
if __name__ == "__main__":
    unittest.main()

# 简单的测试函数
def test_function():
    """简单的测试框架"""
    assert add(2, 3) == 5, "加法测试失败"
    assert multiply(2, 3) == 6, "乘法测试失败"
    print("所有测试通过!")

test_function()

总结与下一步学习建议

本指南涵盖的核心概念回顾

通过本指南,你已经学习了Python编程的基础知识:

  1. 环境搭建:安装Python和选择合适的编辑器
  2. 基础语法:变量、数据类型、运算符
  3. 控制流:条件语句和循环
  4. 数据结构:列表、元组、字典、集合
  5. 函数:定义、参数、作用域、装饰器、递归
  6. 文件操作:读写文件和处理CSV
  7. 异常处理:让程序更健壮
  8. 模块和包:代码组织和重用
  9. 面向对象编程:类、对象、继承、封装
  10. 实用技巧:调试、性能优化、测试

学习建议

1. 练习是关键

  • 每天编写至少30分钟代码
  • 从简单的问题开始,逐步增加难度
  • 重写本指南中的示例,理解每一行代码的作用

2. 项目驱动学习

  • 初级项目:计算器、待办事项列表、简单的游戏(如猜数字)
  • 中级项目:文件管理器、简单的Web应用、数据分析脚本
  • 高级项目:自动化工具、爬虫、机器学习应用

3. 阅读优秀代码

  • 浏览GitHub上的Python项目
  • 学习标准库的源代码
  • 阅读PEP 8和Python文档

4. 加入社区

  • Stack Overflow:提问和回答问题
  • Reddit的r/learnpython:与其他学习者交流
  • Python官方邮件列表和论坛

5. 进阶学习路径

  • 数据科学:NumPy, Pandas, Matplotlib
  • Web开发:Flask, Django
  • 自动化:Selenium, Beautiful Soup
  • 机器学习:Scikit-learn, TensorFlow, PyTorch
  • GUI开发:Tkinter, PyQt

常见陷阱和注意事项

# 陷阱1:可变默认参数
def add_to_list(value, my_list=[]):  # 错误!
    my_list.append(value)
    return my_list

print(add_to_list(1))  # [1]
print(add_to_list(2))  # [1, 2]  # 期望是[2],但实际是[1,2]

# 正确做法
def add_to_list_correct(value, my_list=None):
    if my_list is None:
        my_list = []
    my_list.append(value)
    return my_list

# 陷阱2:修改正在迭代的列表
numbers = [1, 2, 3, 4, 5]
for num in numbers:
    if num % 2 == 0:
        numbers.remove(num)  # 危险!
# 正确做法:创建副本或使用列表推导式
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0]

# 陷阱3:混淆==和is
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)  # True(值相等)
print(a is b)  # False(不是同一个对象)

# 陷阱4:忽略编码问题
# 在文件开头指定编码
# -*- coding: utf-8 -*-
# 或使用UTF-8保存文件

最后的建议

编程是一项实践技能,就像学习乐器或运动一样。理论知识是必要的,但真正的掌握来自于不断的练习和项目实践。不要害怕犯错误,每一个错误都是学习的机会。

保持好奇心,探索Python的更多功能。当你遇到问题时,学会使用搜索引擎和官方文档。记住,即使是经验丰富的程序员也会经常查阅文档。

祝你在Python编程之旅中取得成功!记住:最好的学习方法是开始编写代码