Python

语言学习

Posted by LXG on May 10, 2025

为什么要学习python

使用场景 常见库/框架 说明
Web 开发 Django, Flask, FastAPI 构建网站、后台服务、API 接口等
数据分析 Pandas, NumPy 数据清洗、处理、可视化等
机器学习/AI TensorFlow, PyTorch, scikit-learn 模型训练、预测与深度学习
自动化脚本 os, subprocess, shutil 自动化办公、文件处理、定时任务等
网络爬虫 requests, BeautifulSoup, Scrapy 抓取网页数据,做数据采集与分析
科学计算 SciPy, SymPy, Matplotlib 工程、数学、物理等复杂计算与可视化
运维/DevOps Ansible, Fabric, SaltStack 自动化部署、配置管理、远程命令执行等
桌面应用开发 PyQt5, Tkinter 构建图形界面的桌面应用
游戏开发 Pygame 开发 2D 游戏或教学小游戏
嵌入式系统 MicroPython, CircuitPython 用于资源受限设备上的快速开发
金融分析 zipline, backtrader, pandas 股票数据分析、回测交易策略等
教育/教学 Turtle, Jupyter Notebook 编程教学、交互式教学、图形演示

🐍 Python 发展历史(时间轴)

时间 版本 / 事件 说明
1989 年 Python 起源 Guido van Rossum 在圣诞假期开始开发 Python
1991 年 Python 0.9.0 发布 第一个公开版本,支持函数、异常处理、模块等基本功能
1994 年 Python 1.0 发布 引入 lambda、map、filter、reduce 等函数式编程特性
2000 年 Python 2.0 发布 支持垃圾回收(GC)、Unicode,标志着现代 Python 的开始
2008 年 Python 3.0 发布 不兼容 Python 2,print 成为函数,字符串统一为 Unicode
2010 年 Python 3.2 Python 3 系列逐渐成熟与普及
2020 年 Python 2.7 停止支持 官方不再维护 Python 2,推动全面迁移至 Python 3
2021 年 Python 3.10 发布 引入结构化模式匹配(类似 switch-case),语法更现代
2022 年 Python 3.11 发布 性能大幅提升,Traceback 信息更清晰
2023 年 Python 3.12 发布 引入静态类型改进(如类型参数化),类型系统更强

查看本机python版本


$ python
Python 3.10.12 (main, Feb  4 2025, 14:57:36) [GCC 11.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()

语法学习

变量 和 字符串 数字


message = "hello python3"
print(message)

# 字符串函数

message = "I am a 'programmer' who is learning python"
print(message.title())
print(message.upper())
print(message.lower())

# 字符串合并

first_name = "xiaogang"
last_name = "li"
full_name = first_name + "." + last_name
print(full_name)

# 数字

print(2*0.3)
age = 23
print("Happy " + str(age) + "rd Birthday")

列表


# 列表

Bytes = ['A', 'B', "C"]
print(Bytes)
print(Bytes[1])
Bytes.append('D')
print(Bytes)
Bytes.insert(4, 'E')
print(Bytes)
del Bytes[2]
print(Bytes)
print(Bytes.pop())
Bytes.remove('A')
print(Bytes)

组织和操作列表


# 组织列表

cars = ['bmw', 'audi', 'toyota', 'tesla', 'byd', 'geek']
cars.sort()
print(cars)
cars.sort(reverse=True)
print(cars)

# 临时排序

print(sorted(cars))
print(cars)
cars.reverse()
print(cars)
print(len(cars))

for car in cars:
    print(car)
    print(car.upper())

数值列表


# 数值列表

for value in range(1,10):
    print(value)
numbers = list(range(1, 10))
print(numbers)
numbers = list(range(1, 10, 2))
print(numbers)
squares = []
for value in range(1, 10):
    squares.append(value**2) # 平方运算
print(squares)
print(min(squares))
print(max(squares))
print(sum(squares))

# 使用列表的一部分

print(squares[1:3])
print(squares[-3:])

# 列表复制

copy_squares = squares[:]
print(copy_squares)

元组-元素只读


# 元组

dimensions = (50, 200)
print(dimensions)
for dimension in dimensions:
    print(dimension)

if语句


for car in cars:
    if car == 'bmw' or car == 'byd':
        print(car.upper())
    elif car == 'tesla':
        print(car.title())
    else:
        print(car)
car = "aito"
if car not in cars:
    print(car.upper() + " not exit")
if cars:
    print("cars is not empty")
else:
    print("cars is empty")

字典

字典语法和json语法非常接近

import json
from string import ascii_lowercase

# 字典

alien_0 = {'color':'green', 'point': 5}
print(alien_0)
print(alien_0['color'])
alien_0['x_position'] = 0
alien_0['y_position'] = 25
print(alien_0)
del alien_0['point']
print(alien_0)

for key,value in alien_0.items():
    print(key)
    print(value)
for key in alien_0.keys():
    print(key)
for value in  alien_0.values():
    print(value)

# 列表中存储字典

alien_1 = {'color':'red', 'point': 10}
alien_2 = {'color':'yellow', 'point': 20}
aliens = [alien_0, alien_1, alien_2]
print(aliens)

# 字典中存储列表

favorite_languages = {
    'jen':['python', 'ruby'],
    'sarah':['c'],
    'tom':['go', 'java'],
    'xiaoming':['c++', 'kotlin']
}
for name, language in favorite_languages.items():
    print(name)
    print(language)

# 字典中存储字典

user = {
    'tom': {
        'first':'xiaogang',
        'last':'li',
        'location':'zhengzhou',
    },
    'jack': {
        'first': 'ming',
        'last': 'li',
        'location': 'shanghai',
    },
}
print(user)
print(json.dumps(user, indent=4, ensure_ascii=False))

用户输入和While循环



# 用户输入

# message = input("How old are you:")
# print(int(message))

prompt = "\nTell me something, and I will repeat it back to you: "
prompt += "\nEnter 'quit' to end the program \n"
message = ""
while message != 'quit':
    message = input(prompt)
    print(message)
    if message == 'exit':
        break

函数


def greet_user(username, new_age:int = 10):
    print("Name: " + username + ", Age: " + str(new_age))
    userinfo = username + "-" + str(new_age)
    return userinfo.title()

greet_user("xiaoming", 10)
greet_user(new_age = 15, username="xiaopeng")
user = greet_user(username="xiaoming")
print(user)

# 可变参数

def make_pizza(*foods):
    print(foods)
make_pizza("pepperoni")
make_pizza("mushrooms", "green", "cheese")