一、理论先行
安装环境
安装python3.10版本及pycharm社区版(注:pycharm是编写代码的工具,just like写一份文档可以选word或txt,写代码可以选pycharm或vscode等)
回顾其他语言一些基础指令;
数据类型①:支持int整数、float小数、complex复数
a=3
b=3.14
c=3+j
print(type(a),type(b),type(c))
输出结果:<class 'int'> <class 'float'> <class 'complex'>
数据类型②:字符串处理简单
(C语言中字符串连接要用strcat/strncat;字符串截取通过在所需字符串后一个字符先置0,再加引用,再恢复来实现的)
a="pycharm"
b="python"
print(a+b)
#print(a[1:5])
输出pycharmpython
输出ycha
加号拼接、可截取;左闭右开!
数据类型③:列表list[ ],可反向索引
list=[25,'world',50,'python']
print(list[1:3])
newlist=[12,'ab']
print(list+newlist)
输出['world', 50]
[25, 'world', 50, 'python', 12, 'ab']
加号拼接
数据类型④:元组tuple( )
(‘tuple’ object does not support item assignment元组中的元素不能修改)
数字
①math模块:ceil、floor、fabs、sqrt、exp等等
②随机数:random.random() #随机生成(0,1)内的实数,random.seed()种子可控制随机数相同
randint() #生成一个随机整数
字符串
①“+”连接
②“*”重复输出字符串
③“[]”获取字符串里的字符
④“[:]”截取
⑤“in\not in”判断字符串是否包含给定的字符
⑥"append\extend\insert"添加列表元素
库
numpy是Python科学计算库的基础。包含了强大的N维数组对象和向量运算。
创建数组:创建数组最简单的办法就是使用array函数。它接受一切序列型的对象(包括其他数组),然后产生一个新的含有传入数据的numpy数组。
注:a = np.array([1,2,3,4]),可以是列表、元组
a = np.array(1,2,3,4),错误
数组计算:(注:声明dtype=np.int64使元素为整数,否则是浮点型)
import numpy as np
arr1 = np.array([[1,2,3],[4,5,6]])
arr2 = np.ones([2,3],dtype=np.int64)
print(arr1 + arr2)
print(arr1 - arr2)
print(arr1 * arr2)
print(arr1 / arr2)
print(arr1 ** 2)
输出[[2 3 4]
[5 6 7]]
[[0 1 2]
[3 4 5]]
[[1 2 3]
[4 5 6]]
[[1. 2. 3.]
[4. 5. 6.]]
[[ 1 4 9]
[16 25 36]]
pandas是建立在numpy基础上的高效数据分析处理库,是Python的重要数据分析库
pandas基于numpy实现,常与numpy和matplotlib一同使用,核心数据结构为Series和Dataframe
Matplotlib是一个主要用于绘制二维图形的Python库。用途:绘图、可视化
PIL库是一个具有强大图像处理能力的第三方库。用途:图像处理
二、实践操作
eg.【实现九九乘法表】
思路:循环,每个因数都是1-9循环,简单嵌套循环
语法:①range函数:range()左闭右开,range(0,5)=range(5)表示0,1,2,3,4
②format函数:{}.format(),{}大括号里的内容是被替换的内容
注:有一点和c中不一样的就是冒号,在python中for之后是有冒号的
for i in range(1,10):
for j in range(1,i+1):
print('{}*{}={}'.format(j,i,i*j),end=' ')
print()
输出
1*1=1
1*2=2 2*2=4
1*3=3 2*3=6 3*3=9
1*4=4 2*4=8 3*4=12 4*4=16
1*5=5 2*5=10 3*5=15 4*5=20 5*5=25
1*6=6 2*6=12 3*6=18 4*6=24 5*6=30 6*6=36
1*7=7 2*7=14 3*7=21 4*7=28 5*7=35 6*7=42 7*7=49
1*8=8 2*8=16 3*8=24 4*8=32 5*8=40 6*8=48 7*8=56 8*8=64
1*9=9 2*9=18 3*9=27 4*9=36 5*9=45 6*9=54 7*9=63 8*9=72 9*9=81
eg.【生成10个不同的整数并存至列表中】
语法:①random.randint() #1~20随机生成整数
②append() #添加列表元素
注:i+=1是必须的,生成一个添加一个,否则遇到重复的数不会往列表里添加
import random
random_list = []
i = 0
while i < 10:
ran = random.randint(1,20)
if ran not in random_list:
random_list.append(ran)
i+=1
print(random_list)
输出[11, 4, 13, 5, 18, 17, 15, 8, 7, 16]
eg.【水仙花数/自恋数】