Python并没有100个关键字,Python标准库中定义的关键字数量相对较少,并且是固定的。截止到Python 3.10版本,Python共有35个关键字(不包括保留字)。以下是一个简要的示例集合,涵盖大部分Python关键字:
1、 if
、elif
、else
- 条件判断:
age = 21
if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
2、 for
、in
- 遍历序列或可迭代对象:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
3、 while
- 循环:
count = 0
while count < 5:
print(count)
count += 1
4、 def
- 定义函数:
def greet(name):
print(f"Hello, {name}!")
greet("Alice")
5、 return
- 从函数返回值:
def multiply(a, b):
return a * b
result = multiply(3, 4)
print(result) # 输出:12
6、 class
- 定义类:
class Animal:
def __init__(self, name):
self.name = name
animal = Animal("Dog")
print(animal.name)
7、 try
、except
、finally
、raise
- 异常处理:
try:
raise ValueError("Invalid value!")
except ValueError as ve:
print(f"Caught an exception: {ve}")
finally:
print("Cleaning up...")
8、 import
- 导入模块:
import os
print(os.getcwd())
9、 global
- 声明全局变量:
global_var = 100
def change_global():
global global_var
global_var = 200
change_global()
print(global_var) # 输出:200
10、 nonlocal
- 在嵌套函数中访问外层作用域的变量:
def outer():
x = 1
def inner():
nonlocal x
x += 1
return x
return inner()
print(outer()) # 输出:2
当前文章价值5.91元,扫一扫支付后添加微信提供帮助!(如不能解决您的问题,可以申请退款)
评论已关闭!