精选 Python 常用指令与核心速查备忘单,涵盖高频用法、配置参数与实用技巧。 Python 3 编程语言单页极速参考与核心命令备忘单。
>>> print("Hello, World!")
Hello, World!
Python 著名的 "Hello World" 入门程序
age = 18 # age 变量类型为 int
name = "John" # name 变量类型为 str
print(name)
注意:Python 无法在不赋值的情况下声明变量。
| 类型 | 分类名称 |
|---|---|
str |
文本 (Text) |
int, float, complex |
数值 (Numeric) |
list, tuple, range |
序列 (Sequence) |
dict |
映射/字典 (Mapping) |
set, frozenset |
集合 (Set) |
bool |
布尔 (Boolean) |
bytes, bytearray, memoryview |
二进制 (Binary) |
参阅: 数据类型详解
mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
print(item) # 输出 1, 2
参阅: 列表详解
>>> def my_function():
... print("来自函数的招呼")
...
>>> my_function()
来自函数的招呼
参阅: 函数详解
with open("myfile.txt", "r", encoding='utf8') as file:
for line in file:
print(line)
参阅: 文件操作详解
result = 10 + 30 # => 40
result = 40 - 10 # => 30
result = 50 * 5 # => 250
result = 16 / 4 # => 4.0 (浮点数除法)
result = 16 // 4 # => 4 (整数整除/向下取整)
result = 25 % 2 # => 1 (取余数)
result = 5 ** 3 # => 125 (幂运算)
其中 / 表示两数相除的商(浮点数),// 表示向下取整的整数商。
counter = 0
counter += 10 # => 10
counter = 0
counter = counter + 10 # => 10
message = "Part 1."
# => Part 1.Part 2.
message += "Part 2."
>>> website = 'warpnav.com'
>>> f"Hello, {website}"
"Hello, warpnav.com"
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
参阅: Python F-Strings
hello = "Hello World"
hello = 'Hello World'
multi_string = """多行字符串
支持跨多行输入
文本内容"""
参阅: 字符串操作
x = 1 # int 整型
y = 2.8 # float 浮点型
z = 1j # complex 复数型
>>> print(type(x))
<class 'int'>
my_bool = True
my_bool = False
bool(0) # => False
bool(1) # => True
list1 = ["apple", "banana", "cherry"]
list2 = [True, False, False]
list3 = [1, 5, 7, 9, 3]
list4 = list((1, 5, 7, 9, 3))
参阅: 列表详解
my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))
tupla = (1, 2, 3, 'python')
print(tupla[0]) # 输出: 1
print(tupla.count(1)) # 统计元素出现次数
print(tupla.index(2)) # 查找元素索引
tupla1 = (1, 2, 3)
tupla2 = ('a', 'b')
len(tuple) → 返回元素总个数。
in → 检查元素是否存在于元组中。
拼接 (+) → 合并两个元组。
重复 (*) → 重复元组元素。
切片 (tuple[start:end]) → 提取子元组。
print(len(tupla1)) # 输出: 3
print(2 in tupla1) # 输出: True
print(tupla1 + tupla2) # 输出: (1, 2, 3, 'a', 'b')
print(tupla1[1:]) # 输出: (2, 3)
# 解包 (Unpacking)
a, b, c, d = tupla # 依次解包赋值给变量
类似于列表,但属于不可变类型 (Immutable)
set1 = {"a", "b", "c"}
set2 = set(("a", "b", "c"))
包含唯一元素的无序集合 (Set)
>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
>>> a["one"]
1
>>> a.keys()
dict_keys(['one', 'two', 'three'])
>>> a.values()
dict_values([1, 2, 3])
>>> a.update({"four": 4})
>>> a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>> a['four']
4
键值对 (Key-Value) 结构,类似于 JSON 对象
import heapq
myList = [9, 5, 4, 1, 3, 2]
heapq.heapify(myList) # 将 myList 转化为最小堆 (Min Heap)
print(myList) # => [1, 3, 2, 5, 9, 4]
print(myList[0]) # 堆顶第一个值永远是堆中的最小值
heapq.heappush(myList, 10) # 压入元素 10
x = heapq.heappop(myList) # 弹出并返回最小元素
print(x) # => 1
myList = [9, 5, 4, 1, 3, 2]
myList = [-val for val in myList] # 乘以 -1 取反
heapq.heapify(myList)
x = heapq.heappop(myList)
print(-x) # => 9 (取出后再乘以 -1 还原)
堆是满足父节点小于等于子节点值的二叉树,用于快速获取最小值/最大值。时间复杂度:堆化为 O(n),压入/弹出为 O(log n)。参阅:heapq 模块官方文档
from collections import deque
q = deque() # 创建空双端队列
q = deque([1, 2, 3]) # 带初始值的双端队列
q.append(4) # 右侧入队/入栈
q.appendleft(0) # 左侧入队
print(q) # => deque([0, 1, 2, 3, 4])
x = q.pop() # 右侧出队/出栈并返回
y = q.popleft() # 左侧出队并返回
print(x) # => 4
print(y) # => 0
print(q) # => deque([1, 2, 3])
q.rotate(1) # 循环右移 1 步
print(q) # => deque([3, 1, 2])
deque 是双端队列,两端的入队/出队操作时间复杂度均为 O(1)。常用于高效实现栈 (Stack) 与队列 (Queue)。参阅:deque 官方文档
>>> hello = "Hello, World"
>>> print(hello[1])
e
>>> print(hello[-1])
d
获取指定位置索引或倒数第 1 个字符
>>> for char in "foo":
... print(char)
f
o
o
遍历字符串 "foo" 中的每个字符
┌───┬───┬───┬───┬───┬───┬───┐
| m | y | b | a | c | o | n |
└───┴───┴───┴───┴───┴───┴───┘
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1
>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[0:2]
'my'
>>> s = 'mybacon'
>>> s[:2]
'my'
>>> s[2:]
'bacon'
>>> s[:2] + s[2:]
'mybacon'
>>> s[:]
'mybacon'
>>> s = 'mybacon'
>>> s[-5:-1]
'baco'
>>> s[2:6]
'baco'
>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
>>> s[4::5]
'55555'
>>> s[::-5]
'55555'
>>> s[::-1]
'5432154321543215432154321'
>>> hello = "Hello, World!"
>>> print(len(hello))
13
使用 len() 函数获取字符串长度
>>> s = '===+'
>>> n = 8
>>> s * n
'===+===+===+===+===+===+===+===+'
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'
True
>>> s = 'spam'
>>> t = 'egg'
>>> s + t
'spamegg'
>>> 'spam' 'egg'
'spamegg'
name = "John"
print("Hello, %s!" % name)
name = "John"
age = 23
print("%s is %d years old." % (name, age))
txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36)
>>> name = input("请输入你的名字: ")
请输入你的名字: Tom
>>> name
'Tom'
从控制台获取用户输入数据
>>> "#".join(["John", "Peter", "Vicky"])
'John#Peter#Vicky'
>>> "Hello, world!".endswith("!")
True
>>> website = 'warpnav.com'
>>> f"Hello, {website}"
"Hello, warpnav.com"
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
>>> f"""He said {"I'm John"}"""
"He said I'm John"
>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'
>>> name = 'Eric'
>>> age = 27
>>> f"""Hello!
... I'm {name}.
... I'm {age}."""
"Hello!\n I'm Eric.\n I'm 27."
Python 3.6+ 支持的 f-Strings 格式化语法。参阅:Formatted string literals 官方文档
>>> f'{"text":10}' # 指定宽度 [width]
'text '
>>> f'{"test":*>10}' # 左侧填充
'******test'
>>> f'{"test":*<10}' # 右侧填充
'test******'
>>> f'{"test":*^10}' # 居中填充
'***test***'
>>> f'{12345:0>10}' # 前导零填充
'0000012345'
>>> f'{10:b}' # 二进制 (Binary)
'1010'
>>> f'{10:o}' # 八进制 (Octal)
'12'
>>> f'{200:x}' # 十六进制小写
'c8'
>>> f'{200:X}' # 十六进制大写
'C8'
>>> f'{345600000000:e}' # 科学计数法
'3.456000e+11'
>>> f'{65:c}' # ASCII 字符类型
'A'
>>> f'{10:#b}' # 带有前缀标志 (0b)
'0b1010'
>>> f'{10:#o}' # 带有前缀标志 (0o)
'0o12'
>>> f'{10:#x}' # 带有前缀标志 (0x)
'0xa'
>>> f'{-12345:0=10}' # 负数填充
'-000012345'
>>> f'{12345:010}' # 快捷补零
'0000012345'
>>> f'{-12345:010}'
'-000012345'
>>> import math # 保留小数精度
>>> math.pi
3.141592653589793
>>> f'{math.pi:.2f}'
'3.14'
>>> f'{1000000:,.2f}' # 千位分隔符
'1,000,000.00'
>>> f'{1000000:_.2f}'
'1_000_000.00'
>>> f'{0.25:0%}' # 百分比格式化
'25.000000%'
>>> f'{0.25:.0%}'
'25%'
>>> f'{12345:+}' # 显式正负号 [sign]
'+12345'
>>> f'{-12345:+}'
'-12345'
>>> f'{-12345:+10}'
' -12345'
>>> f'{-12345:+010}'
'-000012345'
>>> li1 = []
>>> li1
[]
>>> li2 = [4, 5, 6]
>>> li2
[4, 5, 6]
>>> li3 = list((1, 2, 3))
>>> li3
[1, 2, 3]
>>> li4 = list(range(1, 11))
>>> li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(filter(lambda x : x % 2 == 1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x ** 2 for x in range (1, 11) if x % 2 == 1]
[1, 9, 25, 49, 81]
>>> [x for x in [3, 4, 5, 6, 7] if x > 5]
[6, 7]
>>> list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))
[6, 7]
>>> li = []
>>> li.append(1)
>>> li
[1]
>>> li.append(2)
>>> li
[1, 2]
>>> li.append(4)
>>> li
[1, 2, 4]
>>> li.append(3)
>>> li
[1, 2, 4, 3]
列表切片通用语法:
a_list[start:end]
a_list[start:end:step]
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[2:5]
['bacon', 'tomato', 'ham']
>>> a[-5:-2]
['egg', 'bacon', 'tomato']
>>> a[1:4]
['egg', 'bacon', 'tomato']
>>> a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>> a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[0:6:2]
['spam', 'bacon', 'ham']
>>> a[1:6:2]
['egg', 'tomato', 'lobster']
>>> a[6:0:-2]
['lobster', 'tomato', 'egg']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']
>>> li = ['bread', 'butter', 'milk']
>>> li.pop()
'milk'
>>> li
['bread', 'butter']
>>> del li[0]
>>> li
['butter']
>>> li = ['a', 'b', 'c', 'd']
>>> li[0]
'a'
>>> li[-1]
'd'
>>> li[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> odd = [1, 3, 5]
>>> odd.extend([9, 11, 13])
>>> odd
[1, 3, 5, 9, 11, 13]
>>> odd = [1, 3, 5]
>>> odd + [9, 11, 13]
[1, 3, 5, 9, 11, 13]
>>> li = [3, 1, 3, 2, 5]
>>> li.sort()
>>> li
[1, 2, 3, 3, 5]
>>> li.reverse()
>>> li
[5, 3, 3, 2, 1]
>>> li = [3, 1, 3, 2, 5]
>>> li.count(3)
2
>>> li = ["re"] * 3
>>> li
['re', 're', 're']
num = 5
if num > 10:
print("num 明显大于 10。")
elif num < 10:
print("num 小于 10。")
else:
print("num 正好等于 10。")
>>> a = 330
>>> b = 200
>>> r = "a" if a > b else "b"
>>> print(r)
a
value = True
if not value:
print("Value 为 False")
elif value is None:
print("Value 为 None")
else:
print("Value 为 True")
x = 1
match x:
case 0:
print("零")
case 1:
print("一")
case _:
print("其他数值")
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
输出: 2 3 5 7
animals = ["dog", "cat", "mouse"]
# enumerate() 为可迭代对象添加计数器
for i, value in enumerate(animals):
print(i, value)
输出: 0 dog 1 cat 2 mouse
x = 0
while x < 4:
print(x)
x += 1 # x = x + 1 的简写
输出: 0 1 2 3
x = 0
for index in range(10):
x = index * 10
if index == 5:
break
print(x)
输出: 0 10 20 30 40
for index in range(3, 8):
x = index * 10
if index == 5:
continue
print(x)
输出: 30 40 60 70
for i in range(4):
print(i) # 输出: 0 1 2 3
for i in range(4, 8):
print(i) # 输出: 4 5 6 7
for i in range(4, 10, 2):
print(i) # 输出: 4 6 8
words = ['Mon', 'Tue', 'Wed']
nums = [1, 2, 3]
# 使用 zip 打包为元组列表
for w, n in zip(words, nums):
print('%d:%s, ' %(n, w))
输出: 1:Mon, 2:Tue, 3:Wed,
nums = [60, 70, 30, 110, 90]
for n in nums:
if n > 100:
print("%d 大于 100" %n)
break
else:
print("未找到大于 100 的数值!")
johndict = {
"firstname": "John",
"lastname": "Doe",
"age": 30
}
for key, value in johndict.items():
print(f"{key} : {value}")
languages = ["html", "go", "rust", "javascript", "python"]
newlist = [x for x in languages if "l" not in x]
print(newlist) # 输出: ['go', 'rust', 'javascript', 'python']
languages = ["html", "go", "rust", "javascript", "python"]
language_dict = {lang: ('l' not in lang) for lang in languages}
print(language_dict)
# 输出: {'html': False, 'go': True, 'rust': True, 'javascript': True, 'python': True}
def hello_world():
print('Hello, World!')
def add(x, y):
print("x 为 %s, y 为 %s" %(x, y))
return x + y
add(5, 6) # => 11
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
args 的类型为元组 (Tuple)
def keyword_args(**kwargs):
return kwargs
keyword_args(big="foot", loch="ness")
kwargs 的类型为字典 (Dict)
def swap(x, y):
return y, x
x, y = swap(1, 2) # => x = 2, y = 1
def add(x, y=10):
return x + y
add(5) # => 15
add(5, 20) # => 25
# => True
(lambda x: x > 2)(3)
# => 5
(lambda x, y: x ** 2 + y ** 2)(2, 1)
# 在不改变原有函数代码的前提下修改或扩展函数/方法的行为
def handle_errors(func):
def wrapper(*args, **kwargs):
try:
return func(*args, **kwargs)
except Exception as e:
return print(f"捕捉到异常 : {e}")
return wrapper
@handle_errors
def divide(a, b):
return a / b
divide(10, 0) # 输出 : 捕捉到异常 : division by zero
import os
os.remove("myfile.txt")
import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("文件不存在!")
import os
os.rmdir("myfolder")
class MyNewClass:
pass
# 实例化对象
my = MyNewClass()
class Animal:
def __init__(self, voice):
self.voice = voice
cat = Animal('喵喵')
print(cat.voice) # => 喵喵
dog = Animal('汪汪')
print(dog.voice) # => 汪汪
class Dog:
# 类的成员方法
def bark(self):
print("汪汪叫")
charlie = Dog()
charlie.bark() # => "汪汪叫"
class MyClass:
class_variable = "这是一个类变量!"
# 输出: 这是一个类变量!
print(MyClass.class_variable)
x = MyClass()
# 输出: 这是一个类变量!
print(x.class_variable)
class ParentClass:
def print_test(self):
print("父类方法")
class ChildClass(ParentClass):
def print_test(self):
print("子类方法")
# 调用父类的 print_test()
super().print_test()
>>> child_instance = ChildClass()
>>> child_instance.print_test()
子类方法
父类方法
class Employee:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
john = Employee('John')
print(john) # => John
class CustomError(Exception):
pass
class ParentClass:
def print_self(self):
print('A')
class ChildClass(ParentClass):
def print_self(self):
print('B')
obj_A = ParentClass()
obj_B = ChildClass()
obj_A.print_self() # => A
obj_B.print_self() # => B
class ParentClass:
def print_self(self):
print("父类实现")
class ChildClass(ParentClass):
def print_self(self):
print("子类重写")
child_instance = ChildClass()
child_instance.print_self() # => 子类重写
class Animal:
def __init__(self, name, legs):
self.name = name
self.legs = legs
class Dog(Animal):
def sound(self):
print("汪汪!")
Yoki = Dog("Yoki", 4)
print(Yoki.name) # => Yoki
print(Yoki.legs) # => 4
Yoki.sound() # => 汪汪!
class MyClass:
@staticmethod
def greet(name):
return f"你好, {name}!"
# 无需实例化即可通过类直接调用
print(MyClass.greet("Alice")) # => 你好, Alice!
# 也可以通过实例对象调用
obj = MyClass()
print(obj.greet("Bob")) # => 你好, Bob!
string: str = "ha"
times: int = 3
def say(name: str, start: str = "Hi"):
return start + ", " + name
print(say("Python")) # => Hi, Python
from typing import Dict, Tuple, List
bill: Dict[str, float] = {
"apple": 3.14,
"watermelon": 15.92,
}
completed: Tuple[str] = ("DONE",)
succeeded: Tuple[int, str] = (1, "SUCCESS")
codes: List[int] = [0, 1, -1, -2]
bill: dict[str, float] = {
"apple": 3.14,
"watermelon": 15.92,
}
completed: tuple[str] = ("DONE",)
succeeded: tuple[int, str] = (1, "SUCCESS")
codes: list[int] = [0, 1, -1, -2]
def calc_summary(*args: int):
return sum(args)
print(calc_summary(3, 1, 4)) # => 8
所有传入参数的类型均为 int
def say_hello(name) -> str:
return "Hello, " + name
var = "Python"
print(say_hello(var)) # => Hello, Python
from typing import Union
def resp200(meaningful) -> Union[int, str]:
return "OK" if meaningful else 200
返回值类型可能是 int 或 str
def calc_summary(**kwargs: int):
return sum(kwargs.values())
print(calc_summary(a=1, b=2)) # => 3
所有关键字参数的值类型均为 int
def resp200() -> (int, str):
return 200, "OK"
returns = resp200()
print(returns) # => (200, 'OK')
def resp200(meaningful) -> int | str:
return "OK" if meaningful else 200
Python 3.10+ 原生语法
class Employee:
name: str
age: int
def __init__(self, name, age):
self.name = name
self.age = age
self.graduated: bool = False
class Employee:
name: str
def set_name(self, name) -> "Employee":
self.name = name
return self
def copy(self) -> 'Employee':
return type(self)(self.name)
from typing import Self
class Employee:
name: str
age: int
def set_name(self: Self, name) -> Self:
self.name = name
return self
from typing import TypeVar, Type
T = TypeVar("T")
# mapper 是一个类型,如 int, str, MyClass 等
# default 是 T 类型的实例对象,如 314, "string", MyClass() 等
def converter(raw, mapper: Type[T], default: T) -> T:
try:
return mapper(raw)
except:
return default
raw: str = input("请输入整数: ")
result: int = converter(raw, mapper=int, default=0)
from typing import TypeVar, Callable, Any
T = TypeVar("T")
def converter(raw, mapper: Callable[[Any], T], default: T) -> T:
try:
return mapper(raw)
except:
return default
def is_success(value) -> bool:
return value in (0, "OK", True, "success")
resp = dict(code=0, message="OK", data=[])
successed: bool = converter(resp["message"], mapper=is_success, default=False)
values = [1, "text", True, "", 2]
i = 0
# 赋值给变量的同时在布尔表达式中进行逻辑判断
while (data := values[i]):
print(data, end=",")
i = i + 1
# 预期输出: 1, "text", True
import datetime
now = datetime.datetime.now()
print(now) # 输出示例: 2024-04-27 14:35:22.123456
import datetime
# 创建日期对象
d = datetime.date(2024, 4, 27)
print(d) # 2024-04-27
# 创建时间对象
t = datetime.time(15, 30, 45)
print(t) # 15:30:45
# 创建日期时间对象
dt = datetime.datetime(2024, 4, 27, 15, 30, 45)
print(dt) # 2024-04-27 15:30:45
import datetime
# 将文本字符串解析为 datetime 对象
date_str = "2024-04-27 14:00"
dt_obj = datetime.datetime.strptime(date_str, "%Y-%m-%d %H:%M")
print(dt_obj) # 2024-04-27 14:00:00
# 将 datetime 对象格式化为指定字符串
formatted_str = dt_obj.strftime("%d/%m/%Y %H:%M")
print(formatted_str) # 27/04/2024 14:00
import datetime
# 获取当前 Unix 时间戳
timestamp = datetime.datetime.now().timestamp()
print(timestamp) # 例如: 1714188922.123456
# 将时间戳转换回 datetime 对象
dt_from_timestamp = datetime.datetime.fromtimestamp(timestamp)
print(dt_from_timestamp)
import datetime
date1 = datetime.date(2024, 4, 27)
date2 = datetime.date(2024, 5, 1)
delta = date2 - date1
print(delta.days) # 相差 4 天
# 使用 timedelta 进行日期加减计算
new_date = date1 + datetime.timedelta(days=10)
print(new_date) # 2024-05-07
# 这是单行注释
""" 使用三个双引号包裹多行字符串,
通常用作函数或类的文档说明 (Docstring)。
"""
def double_numbers(iterable):
for i in iterable:
yield i + i
生成器 (yield) 可以帮助你轻松实现惰性计算 (Lazy Evaluation)。
values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
# => [-1, -2, -3, -4, -5]
print(gen_to_list)
try:
# 使用 raise 主动抛出异常
raise IndexError("这是一个索引超出范围异常")
except IndexError as e:
pass # pass 表示空指令,通常在此处做错误恢复处理
except (TypeError, NameError):
pass # 可以同时捕获多种异常类型
else: # 可选子句:当 try 块中未触发任何异常时执行
print("一切正常运行!")
finally: # 无论是否发生异常都必然执行的收尾逻辑
print("在此处统一清理释放系统资源")
# 分发器模式允许根据用户输入或运行时条件动态选择和执行对应函数
def add(x, y):
return x + y
def subtract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
return '错误: 除数不能为零'
return x / y
# 分发器字典:将操作名称映射到其对应的处理函数
operations = {
'add': add,
'subtract': subtract,
'multiply': multiply,
'divide': divide
}
# 动态分发函数
def dispatcher(operation_name, x, y):
func = operations.get(operation_name)
if func:
return func(x, y)
else:
return f"未知操作指令: {operation_name}"
# 调用示例
print(dispatcher('add', 5, 3)) # 输出: 8
print(dispatcher('multiply', 4, 2)) # 输出: 8
print(dispatcher('divide', 10, 0)) # 输出: 错误: 除数不能为零
print(dispatcher('mod', 10, 3)) # 输出: 未知操作指令: mod