# 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("You cannot divide by zero!")
# 7. with语句(上下文管理器)
with open('example.txt', 'w') as file:
file.write('Hello, world!')
# 8. lambda表达式
add = lambda x, y: x + y
print(add(5, 3))
# 9. import导入模块
import math
print(math.sqrt(16))
# 10. global和nonlocal关键字
global_var = "I am global"
def outer_function():
nonlocal_var = "I am nonlocal"
def inner_function():
global global_var
nonlocal nonlocal_var
global_var = "Changed global"
nonlocal_var = "Changed nonlocal"
print(global_var)
print(nonlocal_var)
inner_function()
outer_function()
print(global_var)
# 解释说明:
# 以上代码展示了Python中一些常见的关键字用法,包括条件语句、循环、函数定义、类定义、异常处理、上下文管理器、lambda表达式、模块导入以及global和nonlocal关键字的使用。
上一篇:python websocket
下一篇:python main
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站