本文将从多个方面对Python开发的记录进行详细阐述,包括语法基础、常用库和框架、开发实践等。
一、语法基础
1、变量与数据类型
# 声明变量并赋值 name = "John" age = 25 is_student = True # 数据类型转换 age_str = str(age) age_int = int(age_str)
2、条件语句
# if-else语句 if age < 18: print("未成年") elif age < 60: print("成年人") else: print("老年人")
3、循环语句
# for循环 numbers = [1, 2, 3, 4, 5] for number in numbers: print(number) # while循环 count = 0 while count < 5: print(count) count += 1
二、常用库和框架
1、NumPy库
import numpy as np # 创建一维数组 array1 = np.array([1, 2, 3, 4, 5]) # 创建二维数组 array2 = np.array([[1, 2, 3], [4, 5, 6]]) # 数组运算 array_sum = np.sum(array1) array_mean = np.mean(array2)
2、Pandas库
import pandas as pd # 创建数据框 data = {'Name': ['John', 'Amy', 'Peter'], 'Age': [25, 30, 35]} df = pd.DataFrame(data) # 数据操作 df.head() # 查看前几行数据 df['Age'].mean() # 计算平均年龄
3、Django框架
# 定义数据模型 from django.db import models class Person(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() # 创建视图函数 from django.http import HttpResponse def hello(request): return HttpResponse("Hello, world!") # 配置URL路由 from django.urls import path urlpatterns = [ path('hello/', hello), ]
三、开发实践
1、Web爬虫
import requests from bs4 import BeautifulSoup # 发送HTTP请求获取HTML页面 response = requests.get("https://www.example.com") html = response.text # 使用BeautifulSoup解析HTML页面 soup = BeautifulSoup(html, 'html.parser') title = soup.title.string # 输出结果 print(title)
2、数据分析
import pandas as pd # 读取CSV文件 data = pd.read_csv("data.csv") # 数据清洗与处理 cleaned_data = data.dropna() # 删除缺失值 filtered_data = cleaned_data[cleand_data['quantity'] > 10] # 筛选数量大于10的数据 # 数据可视化 import matplotlib.pyplot as plt plt.plot(filtered_data['date'], filtered_data['quantity']) plt.xlabel('Date') plt.ylabel('Quantity') plt.show()
3、机器学习
import numpy as np from sklearn.linear_model import LinearRegression # 准备数据集 X = np.array([[1, 1], [1, 2], [2, 2], [2, 3]]) y = np.dot(X, np.array([1, 2])) + 3 # 训练模型 model = LinearRegression() model.fit(X, y) # 进行预测 new_data = np.array([[3, 5], [4, 4]]) predicted = model.predict(new_data)
通过以上的内容,我们对Python开发的基础语法、常用库和框架、开发实践有了初步了解。希望这些记录能够对你在Python开发中有所帮助。