Python 是一种动态的、解释型的、面向对象的通用编程语言,由 Guido van Rossum 于 1991 年首次发布。Python 的设计哲学强调 代码可读性 和 简洁性,其语法简洁清晰,被称为 "可执行伪代码"。
Python 的核心定位是 "全民编程语言"。它提供了:
1989 年圣诞节期间,Guido van Rossum 开始设计 Python,作为 ABC 语言的继承者。Python 的名称来源于 Guido 喜爱的英国喜剧团体 Monty Python(巨蟒剧团)。1991 年,Python 0.9.0 首次公开发布。
with 语句、条件表达式:=)、位置参数💡 在 Python 解释器中输入 import this,可以看到完整的 "Python 之禅"(Zen of Python)。
if __name__ == "__main__":# 单行注释,""" 多行文档字符串#!/usr/bin/env python3
# -*- coding: utf-8 -*-
def main():
"""程序入口函数"""
print("Hello, Python!")
if __name__ == "__main__":
main()
int:整数(任意大小)float:浮点数bool:布尔值(True/False)str:字符串(Unicode)tuple:元组((1, 2, 3))frozenset:不可变集合list:列表([1, 2, 3])dict:字典({"key": "value"})set:集合({1, 2, 3})bytearray:可变字节数组None:空值type:类型对象function:函数class:类f"Hello, {name}!"(Python 3.6+)"{}".format(value)split()、join()、strip()、replace()text[1:10:2]"""多行字符串"""if / elif / elsefor item in iterable:、while condition:break、continue、else(循环结束执行)match value: case 1: ...# for 循环
numbers = [1, 2, 3, 4, 5]
for n in numbers:
if n % 2 == 0:
print(f"{n} is even")
else:
print(f"{n} is odd")
# 列表推导式(Python 特色)
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
# 字典推导式
square_dict = {x: x**2 for x in range(5)}
[x**2 for x in range(10)](x**2 for x in range(10))(惰性求值)# 集合操作
list_a = [1, 2, 3, 4, 5]
list_b = [4, 5, 6, 7, 8]
# 集合运算
set_a = set(list_a)
set_b = set(list_b)
union = set_a | set_b # 并集
intersection = set_a & set_b # 交集
difference = set_a - set_b # 差集
def func(param1, param2=default):def func(x: int, y: str) -> bool:*args(列表)、**kwargs(字典)lambda x: x * 2@decorator_nameyield 关键字# 装饰器示例
def timer(func):
import time
def wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
print(f"{func.__name__} took {time.time() - start:.4f}s")
return result
return wrapper
@timer
def slow_function():
import time
time.sleep(1)
return "Done"
# 生成器示例
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
yield a
a, b = b, a + b
for num in fibonacci(10):
print(num)
class Person:def __init__(self, name):class_variableself.instance_variabledef method(self):@classmethod@staticmethodclass Student(Person):__str__、__repr__、__eq__ 等@dataclassfrom dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
def greet(self) -> str:
return f"Hello, I'm {self.name}, {self.age} years old."
class Student(Person):
school: str
def __init__(self, name: str, age: int, school: str):
super().__init__(name, age)
self.school = school
def greet(self) -> str:
return f"{super().greet()} I study at {self.school}."
try: ... except Exception as e: ...Exception 类class CustomError(Exception):
pass
try:
value = int(input("Enter a number: "))
if value < 0:
raise CustomError("Number must be positive")
except ValueError:
print("Invalid number")
except CustomError as e:
print(f"Error: {e}")
else:
print(f"Valid number: {value}")
finally:
print("Program finished")
async withasync forimport asyncio
async def fetch_data(url):
print(f"Fetching {url}...")
await asyncio.sleep(2) # 模拟网络请求
return f"Data from {url}"
async def main():
tasks = [
fetch_data("https://api1.example.com"),
fetch_data("https://api2.example.com")
]
results = await asyncio.gather(*tasks)
for result in results:
print(result)
# asyncio.run(main())
Python 拥有 "自带电池"(Batteries Included)的哲学,标准库功能极其丰富:
os、sys、shutil、pathlibjson、pickle、xml、csvurllib、http、socketthreading、multiprocessing、concurrent.futuresasynciounittest、doctestloggingredatetime、time、calendarmath、random、statisticszipfile、tarfile、gziphashlib、hmacPython 的语法接近自然英语,初学者可以在几周内掌握基础,有 "可执行伪代码" 的美誉。
PyPI(Python Package Index)拥有超过 50 万个包,几乎覆盖了所有领域,是任何编程语言中最庞大的生态系统。
Python 是 AI、机器学习、数据科学领域的事实标准语言,没有任何语言能撼动其地位。
Python 可以在 Windows、Linux、macOS、Android、iOS 等所有主流平台上运行。
Python 可以轻松调用 C/C++、Java、Rust 等语言编写的库,是理想的 "胶水语言"。
Jupyter Notebook 和 IPython 让数据探索和原型开发变得极其高效。
Python 基础语法、数据类型、控制流、函数、列表/字典/元组
面向对象、文件 I/O、异常处理、模块/包、生成器/迭代器
数据分析:Pandas + NumPy + Matplotlib
Web 开发:Django/Flask/FastAPI
AI 方向:scikit-learn + PyTorch/TensorFlow
数据可视化项目、Web 应用、机器学习项目、自动化脚本
Python 是 21 世纪编程语言的"全民语言"。
它不像 C++ 那样复杂,不像 Java 那样冗长,Python 用 最简洁的语法、最庞大的生态 征服了全球开发者。
从 AI 研究员到数据科学家,从 Web 开发者到自动化工程师,Python 已成为 跨领域通用的语言。TIOBE 排行榜上,Python 常年位居第一,是名副其实的 编程语言之王。
"人生苦短,我用 Python。" 🐍
—— Python 社区的经典名言