# Python语言关键字示例代码
# 1. if-else语句
x = 10
if x > 5:
print("x 大于 5")
else:
print("x 小于等于 5")
# 2. for循环
for i in range(5):
print(f"当前数字是: {i}")
# 3. while循环
count = 0
while count < 3:
print(f"计数: {count}")
count += 1
# 4. 函数定义
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
# 5. 类定义
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
return f"My name is {self.name}, and I am {self.age} years old."
person = Person("Bob", 30)
print(person.introduce())
# 6. try-except异常处理
try:
result = 10 / 0
except ZeroDivisionError:
print("除零错误")
# 7. with语句(上下文管理器)
with open('example.txt', 'w') as file:
file.write("这是一个示例文件。")
# 8. lambda表达式
add = lambda x, y: x + y
print(add(5, 3))
# 9. global和nonlocal关键字
global_var = 0
def modify_global():
global global_var
global_var = 1
modify_global()
print(global_var)
def outer():
nonlocal_var = "outer"
def inner():
nonlocal nonlocal_var
nonlocal_var = "inner"
print(nonlocal_var)
inner()
print(nonlocal_var)
outer()
# 10. yield关键字(生成器)
def simple_generator():
yield 1
yield 2
yield 3
for value in simple_generator():
print(value)
# 11. import关键字
import math
print(math.sqrt(16))
# 12. pass关键字
def empty_function():
pass
empty_function()
# 13. break和continue关键字
for i in range(10):
if i == 5:
break
if i % 2 == 0:
continue
print(i)
# 14. return关键字
def add_numbers(a, b):
return a + b
result = add_numbers(3, 4)
print(result)
以上代码展示了Python中常用的关键字及其用法,包括条件语句、循环、函数定义、类定义、异常处理、上下文管理器、lambda表达式、全局和非局部变量的修改、生成器、模块导入、pass语句、break和continue语句以及return语句等。每个示例都附带了简要的注释,帮助理解各个关键字的作用。
上一篇:python where
下一篇:python 判断数字
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站