python代码例子

当提供一个 Python 代码例子时,我需要知道您对什么样的功能或主题感兴趣。

Hello World:

python
print("Hello, World!")

变量和运算:

python
# 变量 x = 5 y = 10 # 运算 z = x + y print("Sum:", z)

条件语句:

python
age = 20 if age >= 18: print("You are an adult.") else: print("You are a minor.")

循环:

python
# for 循环 for i in range(5): print(i) # while 循环 count = 0 while count < 5: print(count) count += 1

函数:

python
def add_numbers(a, b): return a + b result = add_numbers(3, 7) print("Sum:", result)

列表和循环:

python
# 列表 fruits = ["apple", "banana", "orange"] # for 循环遍历列表 for fruit in fruits: print(fruit)

异常处理:

python
try: # 产生一个除零错误 result = 10 / 0 except ZeroDivisionError: print("Error: Division by zero")

文件操作:

python
# 写入文件 with open('example.txt', 'w') as file: file.write('Hello, File!\n') # 读取文件 with open('example.txt', 'r') as file: content = file.read() print("File Content:", content)

类和对象:

python
# 定义一个类 class Dog: def __init__(self, name): self.name = name def bark(self): print(f"{self.name} says Woof!") # 创建对象 my_dog = Dog("Buddy") # 调用方法 my_dog.bark()

模块和导入:

python
# 创建一个模块,例如 calculator.py # calculator.py 文件内容: # def add(a, b): # return a + b # 在另一个文件中导入模块 from calculator import add result = add(3, 5) print("Sum:", result)

正则表达式:

python
import re text = "Hello, my email is user@example.com" # 使用正则表达式查找电子邮件地址 match = re.search(r'[\w.-]+@[\w.-]+', text) if match: email = match.group() print("Email:", email)

标签