Python 是一门广泛使用的编程语言,适合从小项目到大规模应用开发。本文介绍 Python 的基本语法和一些实用的编程技巧,适合初学者与开发人员。为了方便大家理解,有些例子采用两种写法,一种采用的是英文变量名,另一种则采用中文变量名,以便于大家理解
1. 数据类型
Python 支持多种基本数据类型,如整数、浮点数、复数、字符串、列表、元组、集合和字典。
英文代码:
# 整数
int_value = 20 # int
# 浮点数
float_value = 5.5 # float
# 复数
complex_value = 4 + 2j # complex
# 字符串
single_line_str = "Python"
multi_line_str = """This is a
multi-line string."""
# 列表(可变的有序集合)
sample_list = [2, 4, 6, 'eight', 10.0]
# 元组(不可变的有序集合)
sample_tuple = (3, 6, 9, 'twelve', 15.0)
# 集合(无序且不重复的元素集合)
sample_set = {1, 3, 5, 7, 9}
# 字典(键值对集合)
sample_dict = {'name': 'John', 'age': 24, 'city': 'Beijing'}
中文代码
# 整数
整数变量 = 20 # int
# 浮点数
浮点数变量 = 5.5 # float
# 复数
复数变量 = 4 + 2j # complex
# 字符串
单行字符串 = "Python"
多行字符串 = """这是一段
多行文本"""
# 列表(可变的有序集合)
列表示例 = [2, 4, 6, '八', 10.0]
# 元组(不可变的有序集合)
元组示例 = (3, 6, 9, '十二', 15.0)
# 集合(无序且不重复的元素集合)
集合示例 = {1, 3, 5, 7, 9}
# 字典(键值对集合)
字典示例 = {'姓名': '张三', '年龄': 24, '城市': '北京'}
2. 控制流语句
条件语句
Python 提供了 if-elif-else
语句来控制条件逻辑:
x = 15
if x > 0:
print("正数")
elif x == 0:
print("零")
else:
print("负数")
循环语句
for 循环
遍历一个范围内的数字或一个集合:
# 遍历数字 0 到 4
for num in range(5):
print(num)
while 循环
在条件为真时重复执行代码块:
counter = 0
while counter < 5:
print(counter)
counter += 1
跳转语句
- break 终止循环
- continue 跳过当前迭代
- pass 占位,不执行任何操作
3. 函数
函数在 Python 中使用 def 定义:
英文代码:
def greet(name):
"""输出问候语"""
return f"Hello, {name}!"
print(greet("John"))
中文代码:
def 问候(名字):
"""输出问候语"""
return f"你好,{名字}!"
print(问候("张三"))
支持位置参数、关键字参数、默认参数和可变参数:
def add(num1, num2=5):
return num1 + num2
def mulnumber(*num_list): # 接受多个参数
result = 1
for num in num_list:
result *= num
return result
4. 模块与包
模块与包扩展了 Python 的功能,可以导入标准模块或创建自定义模块:
# 导入模块
import math
from datetime import datetime
print(math.sqrt(25)) # 输出 5.0
print(datetime.now()) # 输出当前时间
5. 异常处理
Python 使用 try-except-else-finally
语句来处理异常:
try:
x = 10 / 0
except ZeroDivisionError:
print("除数不能为零!")
else:
print("无异常")
finally:
print("执行结束")
6. 文件操作
文件读写操作通过 with open 语句更安全:
英文代码:
# 写入文件
with open('sample.txt', 'w') as file:
file.write("This is a sample file.")
# 读取文件
with open('sample.txt', 'r') as file:
content = file.read()
print(content)
中文代码:
# 写入文件
with open('示例.txt', 'w') as 文件:
文件.write("这是一个示例文件。")
# 读取文件
with open('示例.txt', 'r') as 文件:
内容 = 文件.read()
print(内容)
7. 类和对象
Python 使用 class 定义类,并支持继承和多态:
英文代码:
class Person:
"""定义一个基本类"""
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
# 继承
class Student(Person):
def __init__(self, name, age, student_id):
super().__init__(name, age)
self.student_id = student_id
def study(self):
print(f"{self.name} is studying.")
student_a = Student("Mike", 18, "2024001")
student_a.introduce()
student_a.study()
中文代码:
class 人:
"""定义一个基本类"""
def __init__(self, 姓名, 年龄):
self.姓名 = 姓名
self.年龄 = 年龄
def 自我介绍(self):
print(f"你好,我是{self.姓名},年龄{self.年龄}。")
# 继承
class 学生(人):
def __init__(self, 姓名, 年龄, 学号):
super().__init__(姓名, 年龄)
self.学号 = 学号
def 学习(self):
print(f"{self.姓名}正在学习。")
学生A = 学生("李四", 18, "2024001")
学生A.自我介绍()
学生A.学习()
8. 装饰器
装饰器用于增强函数或方法的行为:
英文代码:
def print_message(func):
def wrapper(*args, **kwargs):
print("Before calling function")
result = func(*args, **kwargs)
print("After calling function")
return result
return wrapper
@print_message
def say_hello(name):
print(f"Hello, {name}!")
say_hello("Tom")
中文代码:
def 打印消息(函数):
def 包装器(*args, **kwargs):
print("调用前")
结果 = 函数(*args, **kwargs)
print("调用后")
return 结果
return 包装器
@打印消息
def 打招呼(名字):
print(f"你好,{名字}!")
打招呼("小明")
9. 文件和目录操作
可以通过 os
和 sys
模块获取系统信息或操作文件系统:
import os
import sys
print("当前工作目录:", os.getcwd())
print("命令行参数:", sys.argv)
10. 数据处理与可视化
通过第三方库如 pandas 和 matplotlib,可以进行数据处理与可视化:
英文代码:
import pandas as pd
import matplotlib.pyplot as plt
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 32, 18]
}
df = pd.DataFrame(data)
print(df)
df.plot(kind='bar', x='Name', y='Age', title="Age Comparison")
plt.show()
中文代码:
import pandas as pd
import matplotlib.pyplot as plt
数据 = {
'姓名': ['李四', '王五', '张三'],
'年龄': [25, 32, 18]
}
数据框 = pd.DataFrame(数据)
print(数据框)
数据框.plot(kind='bar', x='姓名', y='年龄', title="年龄对比")
plt.show()
11. 迭代器和生成器
迭代器
迭代器实现 __iter__() 和 __next__() 方法来生成序列。
class CustomIterator:
def __init__(self, max_value):
self.max_value = max_value
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.max_value:
value = self.current
self.current += 1
return value
else:
raise StopIteration
for num in CustomIterator(5):
print(num)
生成器
使用 yield 关键字定义生成器函数:
def custom_generator(max_value):
current = 0
while current < max_value:
yield current
current += 1
for num in custom_generator(5):
print(num)
12. 上下文管理器
使用 with 语句可以更方便地管理资源。自定义上下文管理器需实现 __enter__() 和 __exit__() 方法:
class ResourceHandler:
def __enter__(self):
print("Resource acquired")
return self
def __exit__(self, exc_type, exc_val, exc_tb):
print("Resource released")
def do_task(self):
print("Performing a task with the resource")
with ResourceHandler() as resource:
resource.do_task()
还可以使用 contextlib 模块提供的 @contextmanager 装饰器简化上下文管理器的编写:
from contextlib import contextmanager
@contextmanager
def managed_resource():
print("Resource acquired")
try:
yield
finally:
print("Resource released")
with managed_resource():
print("Performing a task with the resource")
13. 装饰器的高级用法
带参数的装饰器
使用嵌套函数实现带参数的装饰器。
def repeat(times):
def decorator(func):
def wrapper(*args, **kwargs):
for _ in range(times):
result = func(*args, **kwargs)
return result
return wrapper
return decorator
@repeat(3)
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
类装饰器
类也可以用作装饰器,实现 __call__
方法即可。
class DebugDecorator:
def __init__(self, func):
self.func = func
def __call__(self, *args, **kwargs):
print(f"Calling {self.func.__name__} with args: {args}, kwargs: {kwargs}")
result = self.func(*args, **kwargs)
print(f"{self.func.__name__} returned: {result}")
return result
@DebugDecorator
def add(a, b):
return a + b
add(5, 3)
14. 类型注解
Python 通过类型注解提高代码可读性并支持静态类型检查。
from typing import List, Dict, Tuple, Optional
def greet(name: str) -> str:
return f"Hello, {name}!"
def get_names() -> List[str]:
return ["Alice", "Bob", "Charlie"]
def get_info() -> Dict[str, int]:
return {"Alice": 25, "Bob": 30, "Charlie": 35}
def process_data(data: Tuple[int, str, float]) -> None:
num, name, score = data
print(f"Number: {num}, Name: {name}, Score: {score}")
def find_person(people: List[Dict[str, str]], name: str) -> Optional[Dict[str, str]]:
for person in people:
if person['name'] == name:
return person
return None
15. 设计模式
单例模式
确保类只有一个实例,并提供一个全局访问点:
class Singleton:
_instance = None
@staticmethod
def get_instance():
if Singleton._instance is None:
Singleton._instance = Singleton()
return Singleton._instance
def __init__(self):
if Singleton._instance is not None:
raise Exception("This class is a singleton!")
else:
Singleton._instance = self
# 使用单例
singleton1 = Singleton.get_instance()
singleton2 = Singleton.get_instance()
print(singleton1 is singleton2) # 输出 True
工厂模式
为对象创建提供接口,而不显露创建逻辑。
from abc import ABC, abstractmethod
class Product(ABC):
@abstractmethod
def use(self):
pass
class ConcreteProductA(Product):
def use(self):
print("Using ConcreteProductA")
class ConcreteProductB(Product):
def use(self):
print("Using ConcreteProductB")
class Factory:
@staticmethod
def create_product(product_type: str) -> Product:
if product_type == "A":
return ConcreteProductA()
elif product_type == "B":
return ConcreteProductB()
else:
raise ValueError("Invalid product type")
# 使用工厂
product_a = Factory.create_product("A")
product_b = Factory.create_product("B")
product_a.use()
product_b.use()
16. 其他实用技巧
枚举
使用 enum 模块定义枚举类型:
from enum import Enum
class Color(Enum):
RED = 1
GREEN = 2
BLUE = 3
print(Color.RED) # 输出 Color.RED
print(Color.RED.name) # 输出 "RED"
print(Color.RED.value) # 输出 1
数据类
使用 dataclasses 模块简化数据类的定义:
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
city: str
person = Person(name="Alice", age=30, city="New York")
print(person) # 输出 "Person(name='Alice', age=30, city='New York')"
这些高级特性和设计模式有助于编写更高效和结构化的代码。无论是类的单例模式,还是装饰器和上下文管理器,都可以大大提升 Python 应用的可读性和可维护性。Python 的灵活性使其成为初学者和资深开发者的理想选择。
结语
Python 提供了简洁而强大的语法结构和丰富的标准库,加上社区中的第三方库,Python 几乎可以适应任何编程需求。这篇文章涵盖了 Python 的基础语法与实用技巧,适合初学者和有经验的开发人员快速上手或复习。有些复杂的代码中添加了中文变量代码和英文变量代码,可以对照着看,理解起来就会更快。