【重要】python所有关键字示例

以下是一个按照要求整理的表格,包含了Python关键字的序号、关键字、用途以及示例:

序号 关键字 用途 示例
1 False 布尔值,表示假 if not condition: print("Condition is False")
2 None 空值,表示无 result = None
3 True 布尔值,表示真 if condition: print("Condition is True")
4 and 逻辑与运算符 if a and b: print("Both a and b are True")
5 as 别名,用于导入模块或重命名变量 import numpy as np
6 assert 断言,用于调试 assert x > 0, "x must be positive"
7 async 异步函数声明 async def fetch_data(): ...
8 await 等待异步操作完成 data = await fetch_data()
9 break 跳出循环 for i in range(10): if i == 5: break
10 class 定义类 class MyClass: pass
11 continue 跳过当前循环迭代 for i in range(10): if i % 2 == 0: continue
12 def 定义函数 def my_function(): pass
13 del 删除变量或对象 del my_variable
14 elif 条件语句的“否则如果”部分 if condition1: pass elif condition2: pass
15 else 条件语句的“否则”部分 if condition: pass else: pass
16 except 异常处理 try: pass except Exception as e: print(e)
17 finally 无论是否发生异常,都执行的代码块 try: pass finally: print("This will always be executed")
18 for 循环遍历序列 for i in range(10): print(i)
19 from 从模块中导入特定部分 from module import function
20 global 声明全局变量 def my_function(): global x; x = 10
21 if 条件语句 if condition: pass
22 import 导入模块 import module
23 in 检查成员是否在序列中 if x in my_list: print("x is in the list")
24 is 判断两个变量是否相同(身份运算符) if x is y: print("x and y are the same object")
25 lambda 创建匿名函数 lambda x: x + 1
26 nonlocal 声明非局部变量(用于嵌套函数) def outer(): x = "local"; def inner(): nonlocal x; x = "nonlocal"; inner(); print(x)
27 not 逻辑非运算符 if not condition: pass
28 or 逻辑或运算符 if a or b: print("At least one of a or b is True")
29 pass 空操作,占位符 def my_function(): pass
30 raise 引发异常 raise ValueError("An error occurred")
31 return 从函数返回值 def my_function(): return 10
32 try 异常处理 try: pass except Exception: pass
33 while 循环,直到条件为假 while condition: pass
34 with 上下文管理器,简化资源管理 with open("file.txt") as f: pass
35 yield 生成器函数返回值 def my_generator(): yield 10

请注意,以上示例仅为简单的演示,实际应用中可能需要根据具体情况进行调整。

posted @   nxhujiee  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 【杭电多校比赛记录】2025“钉耙编程”中国大学生算法设计春季联赛(1)
点击右上角即可分享
微信分享提示