python基础

Posted by WK on 2025-04-10
Estimated Reading Time 5 Minutes
Words 1.1k In Total
Viewed Times

Python 的基础知识

Python 是一种高级、动态、解释型的编程语言,具有简单易学、功能强大、跨平台等优点。以下是 Python 基础知识的详细讲解,涵盖语法、数据类型、控制结构、函数等内容。

一、Python 的基本语法

  1. 程序结构
    • Python 程序由一系列语句组成,每条语句通常占一行。
    • 使用缩进(而不是大括号 {})来表示代码块。
      1
      2
      if True:
      print("Hello, World!")
  2. 注释
    • 单行注释:#
      1
      # 这是一个单行注释
    • 多行注释:使用三引号 '''"""
      1
      2
      3
      4
      """
      这是多行注释
      可以跨越多行
      """
  3. 输入输出
    • 输出:print() 函数。
      1
      print("Hello, World!")
    • 输入:input() 函数。
      1
      2
      name = input("请输入你的名字:")
      print(f"你好,{name}!")

二、数据类型与变量

  1. 基本数据类型
    • 整数:int,如 10, -5, 0
    • 浮点数:float,如 3.14, -0.001
    • 布尔值:boolTrueFalse
    • 字符串:str,用单引号 ' ' 或双引号 " " 表示。
      1
      message = "Hello, Python!"
    • 空值:None,表示没有值。
  2. 复合数据类型
    • 列表(List):有序、可变的集合。
      1
      numbers = [1, 2, 3]
    • 元组(Tuple):有序、不可变的集合。
      1
      coordinates = (10, 20)
    • 字典(Dictionary):键值对的集合。
      1
      person = {"name": "Alice", "age": 25}
    • 集合(Set):无序、不重复的元素集合。
      1
      unique_numbers = {1, 2, 3}
  3. 变量声明与赋值
    • 动态类型,无需显式声明类型。
      1
      2
      x = 10
      y = "Hello"
  4. 多重赋值
    1
    a, b, c = 1, 2, 3

三、运算符与表达式

  1. 算术运算符
    • 加减乘除:+, -, *, /
    • 整除://
    • 取模:%
    • 幂运算:**
  2. 关系运算符
    • 比较大小:==, !=, >, <, >=, <=
  3. 逻辑运算符
    • 逻辑与:and
    • 逻辑或:or
    • 逻辑非:not
  4. 位运算符
    • 按位与:&
    • 按位或:|
    • 按位异或:^
    • 左移:<<
    • 右移:>>
  5. 赋值运算符
    • 简单赋值:=
    • 复合赋值:+=, -=, *=, /=
  6. 成员运算符
    • 判断是否在序列中:in, not in
      1
      2
      if "apple" in ["apple", "banana"]:
      print("Found!")
  7. 身份运算符
    • 判断两个对象是否为同一对象:is, is not

四、控制结构

  1. 条件语句
    • if-elif-else
      1
      2
      3
      4
      5
      6
      7
      x = 10
      if x > 0:
      print("正数")
      elif x == 0:
      print("零")
      else:
      print("负数")
  2. 循环语句
    • for 循环:
      1
      2
      for i in range(5):
      print(i)
    • while 循环:
      1
      2
      3
      4
      count = 0
      while count < 5:
      print(count)
      count += 1
  3. 跳转语句
    • break:跳出循环。
    • continue:跳过当前迭代。
    • pass:占位符,表示什么都不做。

五、函数

  1. 定义函数
    1
    2
    def greet(name):
    return f"Hello, {name}!"
  2. 默认参数
    1
    2
    def greet(name="World"):
    return f"Hello, {name}!"
  3. 可变参数
    • *args:接收任意数量的位置参数。
      1
      2
      def sum_all(*args):
      return sum(args)
    • **kwargs:接收任意数量的关键字参数。
      1
      2
      3
      def print_info(**kwargs):
      for key, value in kwargs.items():
      print(f"{key}: {value}")
  4. 匿名函数(Lambda)
    1
    2
    square = lambda x: x ** 2
    print(square(5)) # 输出 25
  5. 作用域
    • 局部变量:在函数内部定义。
    • 全局变量:在函数外部定义,使用 global 关键字修改。

六、模块与包

  1. 导入模块
    • 使用 import 导入模块。
      1
      2
      import math
      print(math.sqrt(16))
    • 使用 from ... import 导入特定函数。
      1
      2
      from math import sqrt
      print(sqrt(16))
  2. 创建模块
    • 将函数保存到 .py 文件中,文件名即为模块名。
      1
      2
      3
      # my_module.py
      def greet(name):
      return f"Hello, {name}!"
    • 包是包含多个模块的目录,必须包含一个 __init__.py 文件。
      1
      2
      3
      4
      my_package/
      __init__.py
      module1.py
      module2.py

七、文件操作

  1. 打开文件
    1
    2
    with open("example.txt", "r") as file:
    content = file.read()
  2. 写入文件
    1
    2
    with open("example.txt", "w") as file:
    file.write("Hello, Python!")
  3. 读取文件内容
    • 按行读取:
      1
      2
      3
      with open("example.txt", "r") as file:
      for line in file:
      print(line.strip())

八、异常处理

  1. 捕获异常
    1
    2
    3
    4
    5
    6
    try:
    result = 10 / 0
    except ZeroDivisionError as e:
    print(f"错误:{e}")
    finally:
    print("执行完成")
  2. 抛出异常
    1
    raise ValueError("无效的值")

九、面向对象编程(OOP)

  1. 类与对象
    1
    2
    3
    4
    5
    6
    7
    class Person:
    def __init__(self, name, age):
    self.name = name
    self.age = age

    def greet(self):
    return f"Hello, my name is {self.name}."
  2. 继承
    1
    2
    3
    4
    class Student(Person):
    def __init__(self, name, age, student_id):
    super().__init__(name, age)
    self.student_id = student_id
  3. 多态
    • 不同子类可以实现相同的方法,表现出不同的行为。
  4. 封装
    • 使用私有属性和方法保护数据。
    1
    2
    3
    class MyClass:
    def __init__(self):
    self.__private_var = 10

十、其他常用功能

  1. 列表推导式
    1
    squares = [x**2 for x in range(10)]
  2. 生成器
    1
    2
    3
    def generate_numbers():
    for i in range(5):
    yield i
  3. 装饰器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    def my_decorator(func):
    def wrapper():
    print("Before function call")
    func()
    print("After function call")
    return wrapper

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

If you like this blog or find it useful for you, you are welcome to comment on it. You are also welcome to share this blog, so that more people can participate in it. If the images used in the blog infringe your copyright, please contact the author to delete them. Thank you !