1. Python 简介

Python 是一门简洁、易读、功能强大的高级编程语言,由 Guido van Rossum 在 1991 年首次发布。它强调代码可读性,用缩进表达代码块,拥有丰富的标准库和第三方生态,被广泛应用于 Web 开发、数据分析、人工智能、自动化运维和科学计算等领域。

Python 的主要优点包括:

  • 语法简洁,接近自然语言,适合初学者快速上手。
  • 跨平台,支持 Windows、macOS、Linux 等主流操作系统。
  • 拥有庞大的第三方库,如 NumPy、Pandas、Django、Flask、Requests 等。
  • 既是解释型语言,又支持面向对象、函数式等多种编程范式。

2. 环境搭建

2.1 安装 Python

访问 Python 官方网站下载适合自己操作系统的安装包。安装时建议勾选「Add Python to PATH」,这样可以在命令行中直接使用 python 命令。

安装完成后,可在终端中检查版本:

python --version

如果同时安装了 Python 2 和 Python 3,部分系统可能需要使用 python3 命令。

2.2 选择开发工具

初学者可以使用 IDLE、VS Code、PyCharm Community 等编辑器。推荐安装 VS Code 并搭配 Python 扩展,以获得代码补全、调试和虚拟环境管理等能力。

2.3 创建虚拟环境

虚拟环境可以隔离不同项目的依赖,避免版本冲突:

python -m venv venv

激活虚拟环境:

  • Windows:venv\Scripts\activate
  • macOS/Linux:source venv/bin/activate

3. 基础语法

3.1 注释

单行注释使用 #,多行注释可以使用三个引号:

# 这是一个单行注释

"""
这是一个多行注释,
通常用于说明函数或模块。
"""

3.2 变量与数据类型

Python 是动态类型语言,变量无需声明类型,直接赋值即可:

name = "Alice"       # 字符串 str
age = 25             # 整数 int
height = 1.75        # 浮点数 float
is_student = True    # 布尔值 bool

常用数据类型包括:

  • 数字:intfloatcomplex
  • 字符串:str
  • 布尔值:bool
  • 列表:list
  • 元组:tuple
  • 字典:dict
  • 集合:set

3.3 字符串操作

text = "Hello, Python"

print(text.upper())      # 转大写
print(text.lower())      # 转小写
print(text.replace("Python", "World"))  # 替换
print(text.split(","))   # 分割为列表
print(len(text))         # 获取长度

字符串格式化常用 f-string:

name = "Alice"
age = 25
print(f"我叫 {name},今年 {age} 岁。")

3.4 列表、元组、字典与集合

列表是有序、可变的序列:

fruits = ["apple", "banana", "cherry"]
fruits.append("orange")
fruits.remove("banana")
print(fruits[0])

元组是有序、不可变的序列:

point = (3, 5)
x, y = point

字典存储键值对:

user = {"name": "Alice", "age": 25}
user["city"] = "Beijing"
print(user.get("name"))

集合存储不重复元素,适合去重和集合运算:

numbers = {1, 2, 2, 3, 3}
print(numbers)  # {1, 2, 3}

4. 控制流程

4.1 条件判断

score = 85

if score >= 90:
    grade = "A"
elif score >= 80:
    grade = "B"
elif score >= 60:
    grade = "C"
else:
    grade = "D"

print(grade)

4.2 循环

for 循环常用于遍历序列或配合 range 使用:

for i in range(5):
    print(i)

for fruit in ["apple", "banana"]:
    print(fruit)

while 循环在条件为真时持续执行:

count = 0
while count < 5:
    print(count)
    count += 1

循环中可以使用 break 提前退出,使用 continue 跳过本次迭代。

5. 函数

函数使用 def 关键字定义,可以设置默认参数、接收任意数量参数:

def greet(name, greeting="Hello"):
    return f"{greeting}, {name}!"

print(greet("Alice"))
print(greet("Bob", greeting="Hi"))

使用 *args 接收多个位置参数,使用 **kwargs 接收多个关键字参数:

def summarize(*args, **kwargs):
    print("位置参数:", args)
    print("关键字参数:", kwargs)

summarize(1, 2, 3, name="Alice", age=25)

6. 面向对象编程

6.1 类与对象

类通过 class 关键字定义,__init__ 是构造方法:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        return f"我是 {self.name},今年 {self.age} 岁。"

alice = Person("Alice", 25)
print(alice.introduce())

6.2 继承

子类可以继承父类的属性和方法,并重写或扩展:

class Student(Person):
    def __init__(self, name, age, school):
        super().__init__(name, age)
        self.school = school

    def introduce(self):
        base = super().introduce()
        return f"{base} 我在 {self.school} 上学。"

student = Student("Bob", 18, "第一中学")
print(student.introduce())

7. 异常处理

使用 tryexceptelsefinally 捕获和处理异常,避免程序崩溃:

try:
    result = 10 / 0
except ZeroDivisionError as e:
    print(f"发生错误: {e}")
else:
    print("没有异常时执行")
finally:
    print("无论是否异常都会执行")

也可以主动抛出异常:

def divide(a, b):
    if b == 0:
        raise ValueError("除数不能为 0")
    return a / b

8. 模块与包

一个 .py 文件就是一个模块。使用 import 导入模块,使用 as 起别名:

import math
from datetime import datetime
from os import path as os_path

print(math.sqrt(16))
print(datetime.now())

包是包含 __init__.py 文件的目录,用来组织多个模块。标准库之外,还可使用 pip 安装第三方包:

pip install requests

9. 文件操作

使用 open 函数读写文件,推荐用 with 自动管理资源:

# 写入
with open("example.txt", "w", encoding="utf-8") as f:
    f.write("Hello, Python\n")

# 读取
with open("example.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

常用模式包括 r(读)、w(写,覆盖)、a(追加)、rb(二进制读)、wb(二进制写)。

10. 常用标准库

Python 内置了大量实用模块:

  • os:操作系统接口,处理路径、环境变量。
  • sys:系统相关参数和函数。
  • json:JSON 数据序列化与反序列化。
  • re:正则表达式。
  • datetime:日期和时间处理。
  • collections:提供 Counterdefaultdict 等数据结构。

示例:

import json
from collections import Counter

data = {"name": "Alice", "age": 25}
json_str = json.dumps(data, ensure_ascii=False)
print(json_str)

words = ["apple", "banana", "apple", "cherry"]
print(Counter(words))

11. 列表推导式与生成器

列表推导式可以快速生成列表:

squares = [x ** 2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]

生成器按需产生数据,节省内存:

def count_up(n):
    i = 0
    while i < n:
        yield i
        i += 1

for num in count_up(5):
    print(num)

12. 进阶特性

12.1 装饰器

装饰器在不修改原函数的情况下增强函数功能:

import time

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

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

slow_function()

12.2 Lambda 函数

lambda 用于创建匿名函数,适合简单场景:

add = lambda a, b: a + b
print(add(3, 5))

numbers = [4, 1, 3, 2]
numbers.sort(key=lambda x: -x)
print(numbers)

12.3 mapfilterreduce

nums = [1, 2, 3, 4, 5]

squared = list(map(lambda x: x ** 2, nums))
evens = list(filter(lambda x: x % 2 == 0, nums))

from functools import reduce
total = reduce(lambda a, b: a + b, nums)

13. 学习路径建议

  1. 先掌握基础语法和数据类型,多写小例子巩固。
  2. 熟悉函数、面向对象和异常处理,理解代码组织方式。
  3. 练习文件操作、模块导入和常用标准库。
  4. 选择一个方向深入学习:Web 开发、数据分析、爬虫、自动化或人工智能。
  5. 动手完成小项目,如待办事项应用、博客爬虫、数据分析脚本等。

Python 的学习曲线相对平缓,关键在于持续练习。从解决小问题开始,逐步构建完整的项目能力,就能把语言基础转化为实战技能。

Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐