# Python的关键字示例代码
# 1. if-else 语句
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
# 2. for 循环
for i in range(5):
print(f"Current value of i is {i}")
# 3. while 循环
count = 0
while count < 3:
print(f"Count is {count}")
count += 1
# 4. def 定义函数
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
# 5. class 定义类
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("Cannot divide by zero!")
# 7. with 语句用于文件操作
with open('example.txt', 'w') as file:
file.write("Hello, world!")
# 8. import 导入模块
import math
print(math.sqrt(16))
# 9. lambda 表达式
add = lambda x, y: x + y
print(add(5, 3))
# 10. global 和 nonlocal 关键字
global_var = 10
def modify_global():
global global_var
global_var = 20
modify_global()
print(global_var)
def outer():
nonlocal_var = 10
def inner():
nonlocal nonlocal_var
nonlocal_var = 20
inner()
print(nonlocal_var)
outer()
# 以上代码展示了Python中一些常用的关键字及其用法。
下一篇:python 字符串查找
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站