以下是一些 Python 语法的实例练习:
1. 变量和数据类型
# 整数
a = 10
print(a)
# 浮点数
b = 3.14
print(b)
# 字符串
c = "Hello, World!"
print(c)
# 布尔值
d = True
print(d)
# 列表
e = [1, 2, 3, 4, 5]
print(e)
# 元组
f = (6, 7, 8, 9, 10)
print(f)
# 字典
g = {'name': 'Alice', 'age': 30}
print(g)
2. 控制流语句
# if 语句
x = 10
if x > 5:
print("x is greater than 5")
# if-else 语句
y = 3
if y > 5:
print("y is greater than 5")
else:
print("y is not greater than 5")
# for 循环
for i in range(5):
print(i)
# while 循环
count = 0
while count < 5:
print(count)
count += 1
3. 函数
# 定义函数
def add_numbers(a, b):
return a + b
print(add_numbers(3, 4))
# 匿名函数(lambda 表达式)
square = lambda x: x**2
print(square(5))
4. 列表推导式
# 生成一个包含 1 到 10 的平方的列表
squares = [i**2 for i in range(1, 11)]
print(squares)
5. 类和对象
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
p = Person("Bob", 25)
p.introduce()