以下是一些常用的Python代码段,用于不同的编程任务:
1. 读取文件内容:
def read_file(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
return content
except FileNotFoundError:
return "File not found."
except Exception as e:
return f"An error occurred: {e}"
AI 代码解读
2. 列表推导:
numbers = [1, 2, 3, 4, 5]
squared = [x ** 2 for x in numbers]
AI 代码解读
3. 字典操作:
student = {'name': 'John', 'age': 20, 'grade': 'A'}
student['school'] = 'XYZ School'
AI 代码解读
4. 条件判断:
age = 18
if age >= 18:
print("You are an adult.")
else:
print("You are a minor.")
AI 代码解读
5. 循环遍历:
fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
AI 代码解读
6. 函数定义:
def add(a, b):
return a + b
AI 代码解读
7. 异常处理:
try:
result = 10 / 0
except ZeroDivisionError:
print("Division by zero is not allowed.")
except Exception as e:
print(f"An error occurred: {e}")
AI 代码解读
8. 类定义:
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
AI 代码解读
9. 模块导入:
import math
sqrt_value = math.sqrt(25)
AI 代码解读
10. 文件写入:
data = "Hello, world!"
with open('output.txt', 'w') as file:
file.write(data)
AI 代码解读
这些代码段涵盖了Python编程中常见的操作,可帮助你进行文件操作、数据处理、条件判断、循环遍历、异常处理等任务。根据你的需求,可以将这些代码段作为基础,进行进一步的定制和扩展。