python学习笔记

owofile Lv5

python学习笔记

Python基本语句代码介绍

1. 打印输出

1
print("Hello, World!")

2. 变量赋值

1
2
x = 10
name = "Alice"

3. 条件语句

1
2
3
4
5
6
if x > 5:
print("x大于5")
elif x == 5:
print("x等于5")
else:
print("x小于5")

4. 循环语句

1
2
3
4
5
for i in range(5):
print(i)
while x > 0:
print(x)
x -= 1

5. 列表操作

1
2
3
4
numbers = [1, 2, 3, 4, 5]
print(numbers[0]) # 输出:1
numbers.append(6) # 添加元素
numbers.pop() # 移除最后一个元素

6. 字典操作

1
2
3
person = {"name": "Bob", "age": 30}
print(person["name"]) # 输出:"Bob"
person["occupation"] = "Engineer" # 添加新键值对

7. 函数定义与调用

1
2
3
def greet(name):
print("Hello, " + name + "!")
greet("Tom")

8. 异常处理

1
2
3
4
try:
result = 10 / 0
except ZeroDivisionError:
print("除以零错误")

9. 导入模块

1
2
import math
print(math.sqrt(16)) # 输出:4.0

爬虫

当涉及使用Python进行网络爬虫时,以下是一些基本的代码片段和概念,帮助你入门。请注意,爬取网站的内容时需要遵守网站的使用条款和法律法规。

1. 导入所需库

首先,你需要导入所需的Python库。常用的库包括:

1
2
import requests
from bs4 import BeautifulSoup
  • requests 库用于发送HTTP请求和接收响应。
  • BeautifulSoup 用于解析HTML文档,从中提取数据。

2. 发送HTTP请求获取页面内容

使用 requests 库发送HTTP请求,获取网页内容:

1
2
3
4
5
6
url = 'https://example.com'
response = requests.get(url)
if response.status\_code == 200:
html\_content = response.content
else:
print("Failed to retrieve the page")

3. 解析HTML内容

使用 BeautifulSoup 解析获取的HTML内容,从中提取所需的信息:

1
2
3
4
5
6
7
8
soup = BeautifulSoup(html\_content, 'html.parser')
# 例如提取标题
title = soup.title.text
print("Title:", title)
# 例如提取所有链接
links = soup.find\_all('a')
for link in links:
print(link.get('href'))

4. 使用CSS选择器定位元素

你可以使用CSS选择器来定位HTML元素:

1
2
3
4
# 例如找到所有具有特定CSS类的元素
elements = soup.select('.class-name')
for element in elements:
print(element.text)

5. 处理数据

爬取的数据通常需要进一步处理,例如存储到文件或数据库中:

1
2
3
4
5
# 例如将数据存储到文本文件
with open('data.txt', 'w') as file:
file.write(title + '\n')
for link in links:
file.write(link.get('href') + '\n')

6. 添加延时和异常处理

为了避免给服务器造成过大的负载,最好在爬取过程中添加一些延时。此外,需要处理可能出现的异常情况:

1
2
3
4
5
6
7
8
9
10
import time
# 添加延时
time.sleep(2) # 等待2秒
# 异常处理
try:
response = requests.get(url)
response.raise\_for\_status() # 如果请求不成功,会抛出异常
html\_content = response.content
except requests.exceptions.RequestException as e:
print("Error:", e)

学习编程基础

1.1 编程基本概念

变量、数据类型、表达式和语句

  • 变量:在Python中,变量用于存储数据。变量名是标识符,可以是字母、数字和下划线的组合,但不能以数字开头。

    1
    2
    age = 25
    name = "Alice"
  • 数据类型:Python有多种数据类型,包括整数(int)、浮点数(float)、字符串(str)、布尔值(bool)等。

    1
    2
    3
    4
    num = 42
    price = 9.99
    message = "Hello, World!"
    is\_valid = True
  • 表达式和语句:表达式是由操作数和运算符组成的式子,而语句是执行某个操作的一组代码。

    1
    2
    sum = num1 + num2 # 表达式
    print("Welcome!") # 语句

1.2 安装Python和开发环境

安装Python解释器和选择开发环境

  1. 下载并安装Python 3.x版本:Python官网
  2. 选择一个集成开发环境(IDE)或文本编辑器,如PyCharm、VSCode等。

1.3 第一个程序

编写”Hello, World!”程序

1
print("Hello, World!")

1.4 基本语法

学习Python的缩进规则

  • Python使用缩进来表示代码块,缩进的空格数目必须一致。

定义函数、条件语句、循环语句

1
2
3
4
5
6
7
def greet(name):
if len(name) > 5:
print("Long name!")
else:
print("Short name!")
for i in range(5):
print(i)

学习数据结构和算法

2.1 列表和元组

创建、访问和修改列表和元组

1
2
3
4
my\_list = [1, 2, 3, 4, 5]
my\_tuple = (10, 20, 30)
print(my\_list[2]) # 访问列表元素
my\_tuple[1] = 25 # 错误!元组不可修改

常用方法和操作

1
2
3
my\_list.append(6) # 添加元素到列表末尾
my\_tuple.index(20) # 查找元素在元组中的索引
len(my\_list) # 获取列表长度

2.2 字典和集合

使用字典和集合

1
2
3
4
my\_dict = {"name": "Alice", "age": 30}
my\_set = {1, 2, 3, 3, 4, 5}
print(my\_dict["name"]) # 访问字典值
my\_set.add(6) # 添加元素到集合

常用方法和操作

1
2
my\_dict.keys() # 获取所有键
my\_set.remove(3) # 移除元素

2.3 字符串操作

字符串基本操作

1
2
3
4
5
greeting = "Hello"
name = "Alice"
message = greeting + ", " + name # 字符串拼接
substring = message[7:] # 切片操作
formatted = "My name is {}".format(name) # 格式化字符串

2.4 文件操作

读取和写入文件

1
2
3
4
5
6
7
8
9
# 读取文本文件
with open("file.txt", "r") as file:
content = file.read()
# 写入文本文件
with open("output.txt", "w") as file:
file.write("Hello, File!")
# 读取二进制文件
with open("image.jpg", "rb") as file:
image\_data = file.read()

2.5 基本算法

搜索算法和排序算法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
# 线性搜索
def linear\_search(arr, target):
for i, num in enumerate(arr):
if num == target:
return i
return -1
# 快速排序
def quick\_sort(arr):
if len(arr) <= 1:
return arr
pivot = arr[len(arr) // 2]
left = [x for x in arr if x < pivot]
middle = [x for x in arr if x == pivot]
right = [x for x in arr if x > pivot]
return quick\_sort(left) + middle + quick\_sort(right)

学习面向对象编程(OOP)

3.1 类和对象

创建类和对象

1
2
3
4
5
6
7
class Dog:
def \_\_init\_\_(self, name):
self.name = name
def bark(self):
print(f"{self.name} is barking!")
my\_dog = Dog("Buddy")
my\_dog.bark()

3.2 封装、继承和多态

封装、继承和多态的概念

  • 封装:隐藏对象的内部实现细节,只暴露必要的接口。
  • 继承:从已有的类创建新类,继承现有类的属性和方法。
  • 多态:不同类的对象可以共享相同的接口,但表现不同的行为。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
print("Woof!")
class Cat(Animal):
def speak(self):
print("Meow!")
def animal\_speak(animal):
animal.speak()
my\_dog = Dog()
my\_cat = Cat()
animal\_speak(my\_dog) # 输出 "Woof!"
animal\_speak(my\_cat) # 输出 "Meow!"

学习文件操作和异常处理

4.1 文件操作

深入学习文件操作

1
2
3
4
5
6
# 读取文本文件
with open("file.txt", "r") as file:
lines = file.readlines()
# 写入文本文件
with open("output.txt", "w") as file:
file.writelines(lines)

4.2 异常处理

处理异常

1
2
try:
num = int(input("Enter a

模块和包

模块的组织和使用

在Python中,模块是将代码组织成文件的一种方式,有助于代码的可维护性和复用性。下面是一个简单的例子,展示如何创建和使用模块。

1
2
3
4
5
6
7
8
# 创建一个名为mymodule.py的模块
# mymodule.py
def greet(name):
return f"Hello, {name}!"
# 在另一个文件中使用模块
import mymodule
message = mymodule.greet("Alice")
print(message) # 输出:Hello, Alice!

包的创建和使用

包是一种更高级的模块组织方式,可以将相关的模块组织在一起,形成一个文件夹层级结构。下面是一个包的示例:

1
2
3
4
mypackage/
\_\_init\_\_.py
module1.py
module2.py

__init__.py 是包的初始化文件,可以为空。模块 module1module2 是包内的模块。

函数式编程

函数式编程是一种编程范式,强调使用函数来进行计算和操作。以下是一些函数式编程的基本概念和函数的示例:

Lambda函数

Lambda函数是一种匿名函数,通常用于简单的操作。例如:

1
2
3
4
# 使用Lambda函数将列表中的每个元素平方
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x\*\*2, numbers))
print(squared) # 输出:[1, 4, 9, 16, 25]

map、filter和reduce函数

  • map 函数可以将一个函数应用到可迭代对象的每个元素上。
1
2
3
4
# 使用map函数将列表中的数字转为字符串
numbers = [1, 2, 3, 4, 5]
strings = list(map(str, numbers))
print(strings) # 输出:['1', '2', '3', '4', '5']
  • filter 函数用于过滤可迭代对象中的元素。
1
2
3
4
# 使用filter函数过滤列表中的偶数
numbers = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens) # 输出:[2, 4]
  • reduce 函数在Python 3中被移到 functools 模块下,它对可迭代对象中的元素进行累积操作。
1
2
3
4
5
# 使用reduce函数计算列表中元素的累积乘积
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x \* y, numbers)
print(product) # 输出:120

正则表达式

正则表达式是用于字符串匹配和处理的强大工具。以下是一个简单的正则表达式示例:

1
2
3
4
5
6
import re
# 查找匹配的单词
text = "Hello, my name is Alice."
pattern = r'\b\w+\b' # 匹配单词边界上的字符
matches = re.findall(pattern, text)
print(matches) # 输出:['Hello', 'my', 'name', 'is', 'Alice']

数据库连接

连接和操作数据库是在许多应用中必不可少的一部分。以下是一个使用SQLite数据库的示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import sqlite3
# 连接到数据库(如果不存在则会创建)
conn = sqlite3.connect('mydatabase.db')
# 创建游标对象
cursor = conn.cursor()
# 创建表
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# 插入数据
cursor.execute("INSERT INTO users (name, age) VALUES (?, ?)", ('Alice', 25))
# 提交更改
conn.commit()
# 查询数据
cursor.execute("SELECT \* FROM users")
data = cursor.fetchall()
print(data)
# 关闭连接
conn.close()

Web开发(可选)

前端基础

前端开发涉及构建用户界面。以下是一个简单的HTML和CSS示例:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<title>My Web Page</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<h1>Welcome to My Web Page</h1>
<p>This is a paragraph of text.</p>
</body>
</html>
css复制代码/\* styles.css \*/
body {
font-family: Arial, sans-serif;
background-color: #f0f0f0;
}
h1 {
color: #333333;
}
p {
color: #666666;
}

后端基础

后端开发处理服务器端的逻辑和数据。以下是一个使用Flask框架的简单示例:

1
2
3
4
5
6
7
from flask import Flask
app = Flask(\_\_name\_\_)
@app.route('/')
def hello():
return "Hello, World!"
if \_\_name\_\_ == '\_\_main\_\_':
app.run()

在Web应用中连接和操作数据库

在Web应用中连接和操作数据库与之前的示例类似,只是你需要结合前端和后端的知识来实现完整的功能。例如,你可以使用Flask与数据库进行交互,从前端收集用户输入,并将数据存储在数据库中。

这些学习步骤和示例将帮助你了解高级主题和模块,以及可能涉及的Web开发方向。根据你的兴趣和需求,逐步探索这些领域将带来更深入的理解和技能。

  • Title: python学习笔记
  • Author: owofile
  • Created at : 2023-12-11 10:31:12
  • Updated at : 2025-04-11 21:18:26
  • Link: https://owofile.github.io/blog/2023/12/11/python/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments