1. 基础语法示例
```python
# 变量和数据类型
name = "Alice"
age = 25
height = 1.65
is_student = True
# 列表操作
fruits = ["apple", "banana", "orange"]
fruits.append("grape")
fruits.remove("banana")
# 字典操作
person = {
"name": "Bob",
"age": 30,
"city": "New York"
}
# 条件判断
if age >= 18:
print(f"{name}是成年人")
else:
print(f"{name}是未成年人")
# 循环
for fruit in fruits:
print(f"我喜欢吃{fruit}")
for i in range(5):
print(f"这是第{i+1}次循环")
```
2. 函数定义和使用
```python
def calculate_bmi(weight, height):
"""计算BMI指数"""
bmi = weight / (height ** 2)
return bmi
def greet(name, greeting="Hello"):
"""打招呼函数"""
return f"{greeting}, {name}!"
# 使用函数
bmi = calculate_bmi(70, 1.75)
print(f"BMI指数: {bmi:.2f}")
message = greet("Alice")
print(message)
```
3. 文件操作
```python
# 写入文件
with open("example.txt", "w", encoding="utf-8") as file:
file.write("Hello, World!\n")
file.write("这是第二行内容\n")
# 读取文件
with open("example.txt", "r", encoding="utf-8") as file:
content = file.read()
print("文件内容:")
print(content)
# 逐行读取
with open("example.txt", "r", encoding="utf-8") as file:
lines = file.readlines()
for line_num, line in enumerate(lines, 1):
print(f"第{line_num}行: {line.strip()}")
```
4. 数据处理示例
```python
import pandas as pd
# 创建数据
data = {
'姓名': ['张三', '李四', '王五', '赵六'],
'年龄': [25, 30, 35, 28],
'城市': ['北京', '上海', '广州', '深圳'],
'工资': [5000, 7000, 6000, 8000]
}
df = pd.DataFrame(data)
# 基本数据分析
print("数据概览:")
print(df.head())
print("\n基本统计信息:")
print(df.describe())
print("\n按城市分组统计平均工资:")
city_salary = df.groupby('城市')['工资'].mean()
print(city_salary)
```
5. 网络请求示例
```python
import requests
import json
def get_weather(city):
"""获取天气信息(示例)"""
# 这里使用模拟数据,实际使用时需要真实的API
weather_data = {
"北京": {"temperature": 25, "condition": "晴"},
"上海": {"temperature": 28, "condition": "多云"},
"广州": {"temperature": 32, "condition": "雨"}
}
return weather_data.get(city, {"error": "城市不存在"})
# 使用示例
city = "北京"
weather = get_weather(city)
print(f"{city}的天气: {weather}")
# 实际的API请求示例(需要安装requests库)
try:
response = requests.get('https://api.github.com/users/octocat')
if response.status_code == 200:
user_data = response.json()
print(f"用户名: {user_data['login']}")
print(f"主页: {user_data['html_url']}")
except requests.exceptions.RequestException as e:
print(f"请求失败: {e}")
```
6. 面向对象编程
```python
class Student:
def __init__(self, name, age, major):
self.name = name
self.age = age
self.major = major
self.grades = []
def add_grade(self, grade):
self.grades.append(grade)
def get_average(self):
if not self.grades:
return 0
return sum(self.grades) / len(self.grades)
def display_info(self):
print(f"学生: {self.name}")
print(f"年龄: {self.age}")
print(f"专业: {self.major}")
print(f"平均分: {self.get_average():.2f}")
# 使用类
student1 = Student("张三", 20, "计算机科学")
student1.add_grade(85)
student1.add_grade(92)
student1.add_grade(78)
student1.display_info()
```
7. 错误处理
```python
def safe_divide(a, b):
"""安全的除法运算"""
try:
result = a / b
except ZeroDivisionError:
print("错误: 除数不能为零!")
return None
except TypeError:
print("错误: 请输入数字!")
return None
else:
return result
finally:
print("除法运算完成")
# 测试错误处理
print(safe_divide(10, 2)) # 正常情况
print(safe_divide(10, 0)) # 除零错误
print(safe_divide(10, "2")) # 类型错误
```
8. 列表推导式和生成器
```python
# 列表推导式
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# 筛选偶数
even_numbers = [x for x in numbers if x % 2 == 0]
print(f"偶数: {even_numbers}")
# 平方数
squares = [x**2 for x in numbers]
print(f"平方数: {squares}")
# 生成器表达式
even_squares = (x**2 for x in numbers if x % 2 == 0)
print("生成器结果:")
for num in even_squares:
print(num, end=" ")
```
这些示例涵盖了Python编程的多个重要方面。
20万+

被折叠的 条评论
为什么被折叠?



