python

python相关知识点

python入门

python入门

安装指导

注释

1
2
3
4
#这里是注释内容
"""
这里是注释内容
"""

多行文本一并打印:

1
2
3
4
print("""你好
世界
""")
#python中的每个print都会自动另起一行

变量不需要定义类型

次方

1
2
3**5#表示3的5次方
9**#9的平方

导入库和使用库

1
2
import math
math.函数名([参数])
  • 字符串 str
  • 整数 int
  • 浮点数 float
  • 布尔类型 bool
  • 空值类型 NoneType
1
2
3
4
s = "hello world"
len(s)#返回字符串的长度,这里是11
s[0]#取字符串第一个字符
type(变量名)#返回该变量的类型名

python的交互模式

区别与命令行模式,命令行模式是保存整个文件然后一行一行执行

交互模式是输入一行执行一行,关闭后代码全部消失。

交互模式可以不用print直接看到执行结果。

可以在下图位置打开python的交互模式,或者在终端输入python进入

image-20211218134815095

输入quit()或control+d可以退出交互模式。

用户输入

1
2
3
4
input("请输入:")#让用户输入,返回字符串类型
类型名(xxx)#将xxx转换为类型名类型
int("156")#将"156"字符串类型转换成156整数类型
str(156)#将156整数类型转换成"156"字符串类型

条件语句

1
2
3
4
5
6
7
  if [条件]:
[执行语句]
[执行语句]
else :
[执行语句]
[执行语句]
#语句可以不止一句,但每一行前面都要带有缩进,因为python会根据缩进来评断这行语句是归谁管

pybind11 是用来将c++的函数\类等封装为python模块的。从而在python中就可以调用C++的header-only的库。

https://chunleili.github.io/pybind11/first

python爬虫相关

简单案例:

1
2
3
4
5
6
7
8
from urllib.request import urlopen
url = "http://www.baidu.com"
resp = urlopen(url)
print(resp)
#写入到mybaidu.html文件
with open("mybaidu.html",mode="w") as f:
f.write(resp.read().decode("utf-8")) #读取到网页的页面源代码
print("over!")

requests库

需要安装requests库:pip install requests

1
2
3
4
5
6
7
8
9
import requests
query=input("请输入一个喜欢的明星:")
url=f'https://www.sogou.com/web?query={query}'
dic={
"User-Agent":"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 Safari/537.36"
}
resp = requests.get(url,headers=dic)
print(resp)
print(resp.text)

图表库:Streamlit

PyAutoGUI python键鼠模拟库

pip命令详解

使用pip安装的程序,可以使用pip show xxx确认是否安装好了,如果bin文件夹没有添加到系统的PATH路径下,没法全局执行安装的可执行文件,那么可以通过python -m xxxx执行xxxx可执行文件

永久更换镜像源

更换为官方镜像源:pip config set global.index-url https://pypi.org/simple

不同版本的python通过python3.13,python3.10等指令可以直接调用

python vscode环境

需要的拓展

python拓展

代码检查,测试,调试,环境切换,一些重构等

python Extended

提供大量代码自动完成选项

python Docstring Generator

注释生成

Python Test Explorer for Visual Studio Code

python单元测试侧边栏显示

Python Preview

可视化调试过程

Jupyter

在VS Code中完美使用Jupyter Notebooks

Python Indent

纠正vscode里对python的自动缩进