专栏名称: 机器学习算法与Python实战
长期跟踪关注统计学、数据挖掘、机器学习算法、深度学习、人工智能技术与行业发展动态,分享Python、机器学习等技术文章。回复机器学习有惊喜资料。
目录
相关文章推荐
中核集团  ·  校园招聘🤩 ·  2 天前  
吉林生态环境  ·  来啦 !吉林省生态环境分区管控应用平台正式上线 ·  2 天前  
中核集团  ·  从奠基者变智囊团!中核集团向他们通报! ·  3 天前  
51好读  ›  专栏  ›  机器学习算法与Python实战

2025年了,居然还有人 Python 都没入门

机器学习算法与Python实战  · 公众号  ·  · 2025-01-01 10:59

正文

大家好,我是章北海

很多初学者在开始学习编程时,往往会陷入一个误区:花太多时间在"完整地学习每一个知识点"上。这种学习方式不仅效率低下,而且容易让人失去兴趣。

Python 的美妙之处在于它的简单直观,你不需要花费数月时间去啃教材或教程,只需要跟着这篇教程敲一遍代码,就能掌握基础知识。

记住,编程最重要的不是"知道",而是"做到"。

"纸上得来终觉浅,绝知此事要躬行",我的建议是:

  1. 先快速过一遍这篇教程,边看边敲代码
  2. 找一个感兴趣的小项目开始动手
  3. 遇到问题时再回来查阅相关章节
  4. 在解决实际问题中加深理解
  5. 通过调试 bug 来积累经验

1. Python 基础语法与概念

1.1 变量与数据类型

  • 变量命名规则和最佳实践
  • 基本数据类型:
    • 数值类型 (int, float, complex)
    • 字符串 (str)
    • 布尔值 (bool)
  • 类型转换和检查
  • Python 的动态类型特性
# 数值类型示例
age = 25          # 整数
price = 19.99     # 浮点数
complex_num = 3 + 4j  # 复数

# 字符串示例
name = "Python 学习者"
message = '''这是一个
多行字符串示例'''


# 布尔值示例
is_student = True
is_working = False

# 类型检查和转换
print(type(age))       
str_num = "100"
num = int(str_num)     # 字符串转整数

1.2 运算符

  • 算术运算符 (+, -, *, /, //, %, **)
  • 比较运算符 (==, !=, >, <, >=, <=)
  • 逻辑运算符 (and, or, not)
  • 赋值运算符 (=, +=, -=等)
  • 位运算符 (&, |,^, >>, <<)
# 算术运算符示例
a = 10
b = 3

print(a + b)    # 13  (加法)
print(a - b)    # 7   (减法)
print(a * b)    # 30  (乘法)
print(a / b)    # 3.3333... (除法)
print(a // b)   # 3   (整除)
print(a % b)    # 1   (取余)
print(a ** b)   # 1000(幂运算)

# 比较和逻辑运算符
x = 5
y = 10
print(x < y and y < 15)  # True
print(x > y or y < 15)   # True

1.3 条件语句

  • if 语句的基本结构
  • elif 和 else 的使用
  • 嵌套条件语句
  • 三元运算符
  • match-case 语句 (Python 3.10+)
# if-elif-else 示例
score = 85

if score >= 90:
    print("优秀")
elif score >= 80:
    print("良好")
elif score >= 60:
    print("及格")
else:
    print("不及格")

# 三元运算符
age = 20
status = "成年" if age >= 18 else "未成年"

# match-case 示例 (Python 3.10+)
def check_status(status_code):
    match status_code:
        case 200:
            return "成功"
        case 404:
            return "未找到"
        case _:
            return "未知状态"

1.4 循环结构

  • for 循环
    • range() 函数的使用
    • 遍历序列和集合
    • enumerate() 的应用
  • while 循环
    • 循环条件设计
    • break 和 continue
    • else 子句
  • 循环嵌套和控制
# for 循环示例
for i in range(5):
    print(i)  # 打印 0 到 4

fruits = ["苹果""香蕉""橙子"]
for fruit in fruits:
    print(fruit)

# enumerate 示例
for index, fruit in enumerate(fruits):
    print(f"第{index+1}个水果是:{fruit}")

# while 循环示例
count = 0
while count < 5:
    print(count)
    count += 1
    if count == 3:
        continue  # 跳过本次循环
    if count == 4:
        break    # 结束循环

2. 函数与模块

2.1 函数基础

  • 函数定义与调用
  • 参数类型:
    • 位置参数
    • 关键字参数
    • 默认参数
    • 可变参数 (*args, **kwargs)
  • 返回值处理
  • 函数文档字符串
# 基本函数定义
def greet(name, greeting="你好"):
    """
    向指定的人打招呼
    
    参数:
        name (str): 人名
        greeting (str): 问候语,默认为"你好"
    返回:
        str: 完整的问候语
    """

    return f"{greeting}{name}!"

# 函数调用
print(greet("小明"))           # 你好,小明!
print(greet("小红""早安"))    # 早安,小红!

# 可变参数示例
def sum_numbers(*args):
    return sum(args)

print(sum_numbers(1234))  # 10

# 关键字参数示例
def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}{value}")

print_info(name="张三", age=20, city="北京")

2.2 模块使用

  • 模块导入方式
  • 包的概念和结构
  • 常用内置模块使用示例
# 常用模块示例
import math
import random
import datetime
import os

# math 模块
print(math.pi)                 # 圆周率
print(math.sqrt(16))          # 平方根

# random 模块
print(random.randint(110))  # 随机整数
print(random.choice(['苹果''香蕉''橙子']))  # 随机选择

# datetime 模块
now = datetime.datetime.now()
print(f"当前时间:{now}")
print(f"明天:{now + datetime.timedelta(days=1)}")

# os 模块
print(os.getcwd())            # 当前工作目录
print(os.listdir())           # 目录内容列表

3. 数据处理基础

3.1 数据结构

  • 列表 (List)
  • 元组 (Tuple)
  • 集合 (Set)
  • 字典 (Dict)
# 列表示例
fruits = ["苹果""香蕉""橙子"]
fruits.append("葡萄")         # 添加元素
fruits.insert(1"梨")       # 插入元素
fruits.remove("香蕉")        # 删除元素
print(fruits[1:3])          # 切片操作

# 元组示例
point = (34)
x, y = point                # 元组解包

# 集合示例
numbers = {12345}
more_numbers = {45678}
print(numbers & more_numbers)  # 交集
print(numbers | more_numbers)  # 并集

# 字典示例
student = {
    "name""张三",
    "age"20,
    "scores": {
        "数学"90,
        "英语"85
    }
}
print(student.get("grade""未知"))  # 安全获取值

3.2 字符串操作

  • 字符串方法
  • 格式化方式
  • 正则表达式
# 字符串方法示例
text = "  Python 编程  "
print(text.strip())          # 去除空白
print(text.upper())          # 转大写
print(text.lower())          # 转小写

# 字符串格式化
name = "小明"
age = 20
# f-string
print(f"{name}今年{age}岁")
# format 方法
print("{}今年{}岁".format(name, age))
# %-格式化
print("%s今年%d岁" % (name, age))

# 正则表达式
import re
text = "我的电话是 123-4567-8900"
phone = re.search(r"\d{3}-\d{4}-\d{4}", text)
if phone:
    print(f"找到电话号码:{phone.group()}")

3.3 文件操作

  • 文件读写
  • JSON 处理
  • CSV 处理
# 文件读写示例
with open("example.txt""w", encoding="utf-8"as f:
    f.write("这是一个示例文件\n")
    f.write("包含多行文本")

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

# JSON 处理
import json

data = {
    "name""Python 教程",
    "version""2025",
    "topics": ["基础""进阶""实战"]
}

# 写入 JSON
with open("data.json""w", encoding="utf-8"as f:
    json.dump(data, f, ensure_ascii=False, indent=2 )

# 读取 JSON
with open("data.json""r", encoding="utf-8"as f:
    loaded_data = json.load(f)

4. 错误处理

  • 异常处理机制
  • 自定义异常
# 异常处理示例
def divide(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("错误:除数不能为 0")
        return None
    except TypeError:
        print("错误:参数类型必须是数字")
        return None
    else:
        return result
    finally:
        print("计算完成")

# 自定义异常
class ValidationError(Exception):
    def __init__(self, message):
        self.message = message
        super().__init__(self.message)

def validate_age(age):
    if not isinstance(age, int):
        raise ValidationError("年龄必须是整数")
    if age < 0 or age > 150:
        raise ValidationError("年龄必须在 0-150 之间")
    return True

# 异常处理示例
try:
    validate_age("20")
except ValidationError as e:
    print(f"验证失败:{e.message}")

5. 面向对象编程 (OOP)

5.1 类和对象

  • 类的定义和实例化
  • 属性和方法
  • 构造函数和析构函数
  • 访问修饰符
  • 属性装饰器 (@property)
class Student:
    # 类变量
    school = "Python 大学"
    
    def __init__(self, name: str, age: int):
        # 实例变量
        self.name = name        # 公有属性
        self._age = age         # 受保护属性
        self.__score = 0        # 私有属性
        
    def __del__(self):
        print(f"{self.name}对象被销毁")
    
    # 实例方法
    def study(self, course: str) -> None:
        print(f"{self.name}正在学习{course}")
    
    # 属性装饰器 - getter
    @property
    def score(self) -> int:
        return self.__score
    
    # 属性装饰器 - setter
    @score.setter
    def score(self, value: int) -> None:
        if not isinstance(value, int):
            raise TypeError("分数必须是整数")
        if 0 <= value <= 100:
            self.__score = value
        else:
            raise ValueError("分数必须在 0-100 之间")
    
    # 类方法
    @classmethod
    def get_school(cls) -> str:
        return cls.school
    
    # 静态方法
    @staticmethod
    def is_adult(age: int) -> bool:
        return age >= 18

# 使用示例
if __name__ == "__main__":
    # 创建实例
    student = Student("张三"20)
    
    # 访问公有属性和方法
    print(student.name)         # 张三
    student.study("Python")     # 张三正在学习 Python
    
    # 使用属性装饰器
    student.score = 95          # 设置分数
    print(student.score)        # 95
    
    # 使用类方法和静态方法
    print(Student.get_school()) # Python 大学
    print(Student.is_adult(20)) # True

5.2 继承与多态

  • 单继承和多继承
  • 方法重写
  • super() 函数
  • 抽象类和接口
  • 混入类 (Mixins)
from abc import ABC, abstractmethod
from typing import List

# 抽象基类
class Animal(ABC):
    def






请到「今天看啥」查看全文