这个页面展示了 Python 语言的示例代码,您可以在这里找到一些基础和进阶的代码实例。

基础示例

变量和数据类型

# 定义一个变量
x = 10

# 输出变量
print(x)

循环结构

# 使用 for 循环打印数字 1 到 5
for i in range(1, 6):
    print(i)

函数定义

# 定义一个函数
def greet(name):
    return f"Hello, {name}!"

# 调用函数
print(greet("World"))

高级示例

类和对象

class Dog:
    def __init__(self, breed, age):
        self.breed = breed
        self.age = age

    def bark(self):
        return "Woof!"

# 创建对象
my_dog = Dog("Golden Retriever", 5)

# 调用方法
print(my_dog.bark())

文件操作

# 打开文件
with open('example.txt', 'w') as file:
    file.write('Hello, world!')

# 读取文件
with open('example.txt', 'r') as file:
    content = file.read()
    print(content)

Python 示例代码

更多关于 Python 的学习资料,请访问Python 教程页面。