1  
 

下载软件

1.1 下载python最新版本并安装

下载地址:百度搜索python官网。Welcome to Python.org

 

1.2 官网学习网页:Python Tutorials – Real Python  

 

1.3 也可以下载集成环境软件Anaconda。 Anaconda 软件商城 官方正版 免费下载 (msc23.cn)

 2  
 

在python安装路径下安装pip

本机安装python312后再子目录script文件下已经安装有pip\pip3。如没有可以参考百度的介绍。

 

Windows中
(1)打开命令提示符(CMD)。
(2)输入以下命令:
curl https://bootstrap.pypa.io/get-pip.py -o get-pip.py
python get-pip.py

 3  
3

安装常用的库(包)

 

# 包名称
版本号
构建号
频道
_ipyw_jlab_
0.1.0
py36_0
-
_libgcc_mut
0.1
main
-
aioeasywebd
2.4.0
py36_1000
conda-forge
aiohttp
3.6.2
py36h7b6447c_0
-
anaconda-cl
1.7.2
py36_0
-
anaconda-na
1.9.12
py36_1
-
appdirs
1.4.3
py36h28b3542_0
-
async-timeo
3.0.1
py36_0
-
attrs
19.3.0
py_0
-
backcall
0.2.0
py_0
-
backports
1.0
py_2
-
backports.fche
1.6.1
py_0
-
backports.t
1.0
py_1
-
backports.w
1.0.post1
py_1
-
bcrypt
3.1.7
py36h7b6447c_1
-
beautifulso
4.9.1
py36_0
-
blas
1.0
mkl
-
bleach
3.1.5
py_0
-
boto3
1.9.66
py36_0
-
botocore
1.12.189
py_0
-
brotlipy
0.7.0
py36h7b6447c_100
-
bzip2
1.0.8
h7b6447c_0
-
ca-certific
2020.6.240
-
-
cachetools
4.1.0
py_1
-
cairo
1.14.12
h8948797_3
-
certifi
2020.6.20
py36_0
-
cffi
1.14.0
py36h2e261b9_0
-
chardet
3.0.4
py36_1003
-
click
7.1.2
py_0
-
clyent
1.2.2
py36_1
-
conda
4.8.3
py36_0
-
conda-build
3.18.11
py36_0
-
conda-env
2.6.0
1
-
conda-packa
1.6.1
py36h7b6447c_0
-
conda-verif
3.4.2
py_1
-
configargpa
1.2.3
py_0
-
cryptograph
2.9.2
py36h1ba5d50_0
-
cycler
0.10.0
py36_0
-
dataclasses
0.7
py36_0
-
datrie
0.8.2
py36h7b6447c_0
-
dbus
1.13.6
h746ee38_0
-
dcm2niix
1.0.20181114
h6bb024c_1000
conda-forge
decorator
4.4.2
py_0
-
defusedxml
0.6.0
py_0
-
docutils
0.16
py36_1
-
dropbox
10.2.0
py36_0
-
entrypoints
0.3
py36_0
-
expat
2.2.9
he6710b0_2
-
filechunkio
1.6
py36_0
bioconda
filelock
3.0.12
py_0
-
fontconfig
2.13.0
h9420a91_0
-
freeglut
3.0.0
hf484d3e_5
-
freetype
2.10.2
h5ab3b9f_0
-
fribidi
1.0.9
h7b6447c_0
-
fsleyes
0.32.0
py36_0
conda-forge
fsleyes-pro
1.6.7
py_0
conda-forge
fsleyes-wid
0.8.4
py_0
conda-forge
fslpy
3.2.1
pyh5ca1d4c_0
conda-forge
ftputil
3.2
py36_0
bioconda
future
0.18.2
py36_1
-
gettext
0.19.8.1
hd7bead4_3
-
gitdb
4.0.5
py_0
-
gitpython
3.1.3
py_1
-
glib
2.56.2
hd408876_0
-
glob2
0.7
py_0
-
google-api-
1.17.0
py36_0
-
google-auth
1.17.2
py_0
-
google-clou
1.3.0
py_0
-
google-clou
1.28.1
py_0
-
google-resu
0.5.1
py_0
-
googleapis-
1.51.0
py36_2
-
graphite2
1.3.14
h23475e2_0
-
graphviz
2.40.1
h21bd128_2
-
gst-plugins
1.14.0
hbbd80ab_1
-
gstreamer
1.14.0
hb453b48_1
-
h5py
2.10.0
py36hd6299e0_1
-
harfbuzz
1.8.8
hffaf4a1_0
-
hdf5
1.10.6
hb1b8bf9_0
-
icu
58.2
he6710b0_3
-
idna
2.10
py_0
-
idna_ssl
1.1.0
py36_0
-
importlib-m
1.7.0
py36_0
-
importlib_m
1.7.0
0
-
indexed_gzi
1.3.2
py36hfaf6566_0
conda-forge
intel-openm
2020.1
217
-
ipykernel
5.3.4
py36h5ca1d4c_0
-
ipython
7.16.1
py36h5ca1d4c_0
-
ipython_gen
0.2.0
py36_0
-
ipywidgets
7.5.1
py_0
-
isodate
0.6.0
py_1
-
jedi
0.17.1
py36_0
-
jinja2
2.11.2
py_0
-
jmespath
0.10.0
py_0
-
jpeg
9b
h024ee3a_2
-
json5
0.9.5
py_0
-
jsonschema
3.2.0
py36_0
-
jupyter_cli
6.1.6
py_0
-
jupyter_cor
4.6.3
py36_0
-
jupyterlab
2.1.5
py_0
-
jupyterlab_
1.2.0
py_0
-
kiwisolver
1.2.0
py36hfd86e86_0
-
lcms2
2.11
h396b838_0
-
ld_impl_lin
2.33.1
h53a641e_7
-
libarchive
3.4.2
h62408e4_0
-
libedit
3.1.20191231
h14c3975_1
-
libffi
3.2.1
hd88cf55_4
-
libgcc-ng
9.1.0
hdf63c60_0
-
libgfortran
7.3.0
hdf63c60_0
-
libglu
9.0.0
hf484d3e_1
-
liblief
0.10.1
he6710b0_0
-
libpng
1.6.37
hbc83047_0
-
libprotobuf
3.12.3
hd408876_0
-
libsodium
1.0.18
h7b6447c_0
-
libspatiali
1.9.3
he6710b0_0
-
libssh2
1.9.0
h1ba5d50_1
-
libstdcxx-n
9.1.0
hdf63c60_0
-
libtiff
4.1.0
h2733197_1
-
libuuid
1.0.3
h1bed415_2
-
libxcb
1.14
h7b6447c_0
-
libxml2
2.9.10
he19cac6_1
-
lz4-c
1.9.2
he6710b0_1
-
markupsafe
1.1.1
py36h7b6447c_0
-
matplotlib
3.2.2
0
-
matplotlib-
3.2.2
py36hef1b27d_0
-
mistune
0.8.4
py36h7b6447c_0
-
mkl
2020.1217
-
-
mkl-service
2.3.0
py36he904b0f_0
-
mkl_fft
1.1.0
py36h23d657b_0
-
mkl_random
1.1.1
py36h0573a6f_0
-
more-iterto
8.4.0
py_0
-
multidict
4.7.3
py36h7b6447c_0
-
navigator-u
0.2.1
py36_0
-
nbconvert
5.6.1
py36_0
-
nbformat
5.0.7
py_0
-
ncurses
6.2
he6710b0_1
-
networkx
2.4
py_1
-
nibabel
3.1.1
py_0
conda-forge
notebook
6.0.3
py36_0
-
numpy
1.19.1
py36hbc911f0_0
-
numpy-base
1.19.1
py36hfa32c7d_0
-
olefile
0.46
py36_0
-
openssl
1.1.1g
h7b6447c_0
-
packaging
20.4
py_0
-
pandas
1.0.5
py36h0573a6f_0
-
pandoc
2.10
0
-
pandocfilte
1.4.2
py36_1
-
pango
1.42.4
h049681c_0
-
paramiko
2.7.1
py_0
-
parso
0.7.0
py_0
-
patchelf
0.11
he6710b0_0
-
pcre
8.44
he6710b0_0
-
pexpect
4.8.0
py36_0
-
pickleshare
0.7.5
py36_0
-
pillow
7.2.0
py36hb39fc2d_0
-
pip
20.1.1
py36_1
-
pixman
0.40.0
h7b6447c_0
-
pkginfo
1.5.0.1
py36_0
-
pluggy
0.13.1
py36_0
-
prettytable
0.7.2
py_3
conda-forge
progressbar
3.37.1
py36_0
-
prometheus_
0.8.0
py_0
-
prompt-tool
3.0.5
py_0
-
protobuf
3.12.3
py36he6710b0_0
-
psutil
5.7.0
py36h7b6447c_0
-
ptyprocess
0.6.0
py36_0
-
py
1.9.0
py_0
-
py-lief
0.10.1
py36h403a769_0
-
pyasn1
0.4.8
py_0
-
pyasn1-modu
0.2.7
py_0
-
pycosat
0.6.3
py36h7b6447c_0
-
pycparser
2.20
py_2
-
pydicom
2.0.0
pyh9f0ad1d_0
conda-forge
pygments
2.6.1
py_0
-
pygraphviz
1.3
py36h14c3975_1
-
pyinstaller
   
打包程序包
pymesh2
0.2.1
py36_0
conda-forge
pynacl
1.4.0
py36h7b6447c_1
-
pyopengl
3.1.1a1
py36_0
-
pyopenssl
19.1.0
py_1
-
pyparsing
2.4.7
py_0
-
pyperclip
   
剪切板库
pyqt
5.9.2 py36h05f
1152_2
-
pyrsistent
0.16.0 py36h7b6
447c_0
-
pysftp
0.2.9
py_1
-
pysocks
1.7.1
py36_0
-
pytest
5.4.3
py36_0
-
pytest-runn
5.2
py_0
-
python
3.6.10 hcf3
2534_1
-
python-date
2.8.1
py_0
-
python-irod
0.7.0
py_0
conda-forge
python-liba
2.9
py_0
-
python-util
2.3.0
py36_0
-
python_abi
3.6
1_cp36m
conda-forge
pytz
2020.1
py_0
-
pyyaml
5.3.1
py36h7b6447c_1
-
pyzmq
19.0.1
py36he6710b0_1
-
qt
5.9.7
h5867ecd_1
-
qtpy
1.9.0
py_0
-
ratelimiter
1.2.0
py36_1000
conda-forge
readline
8.0
h7b6447c_0
-
requests
2.24.0
py_0
-
ripgrep
11.0.2
he32d670_0
-
rsa
4.0
py_0
-
rtree
0.8.3
py36h7b0cdae_10
03 conda-forge
ruamel_yaml
0.15.87
py36h7b6447c_1
-
s3transfer
0.1.13
py36_0
-
scipy
1.5.0
py36h0b6359f_0
-
send2trash
1.5.0
py36_0
-
setuptools
49.2.0
py36_0
-
sip
4.19.8
py36hf484d3e_0
-
six
1.15.0
py_0
-
smmap
3.0.2
py_0
-
snakemake
5.3.0
py36_1
bioconda
snakemake-m
5.3.0
py36_1
bioconda
soupsieve
2.0.1
py_0
-
sphinx_rtd_
0.4.3
py_0
-
sqlite
3.32.3
h62c20be_0
-
terminado
0.8.3
py36_0
-
testpath
0.4.4
py_0
-
tk
8.6.10
hbc83047_0
-
tornado
6.0.4
py36h7b6447c_1
-
tqdm
4.47.0
py_0
-
traitlets
4.3.3
py36_0
-
trimesh
3.7.7
pyh9f0ad1d_0
conda-forge
typing_exte
3.7.4.2
py_0
-
urllib3
1.25.9
py_0
-
wcwidth
0.2.5
py_0
-
webencoding
0.5.1
py36_1
-
wheel
0.34.2
py36_0
-
widgetsnbex
3.5.1
py36_0
-
wrapt
1.12.1
py36h7b6447c_1
-
wxnatpy
0.3.2
py_0
conda-forge
wxpython
4.0.4
py36hc99224d_0
-
xmlrunner
1.7.7
py_0
conda-forge
xmltodict
0.12.0
py_0
-
xnat
0.3.22
py_0
conda-forge
xz
5.2.5
h7b6447c_0
-
yaml
0.2.5
h7b6447c_0
-
yarl
1.4.2
py36h7b6447c_0
-
zeromq
4.3.2
he6710b0_2
-
zipp
3.1.0
py_0
-
zlib
1.2.11
h7b6447c_3
-
zstd
1.4.5
h9ceee32_0
-
 4  
 

基本入门脚本文件——可以下载EditPlus阅读代码软件,设置字体为18方便阅读。

 

#小乌龟画图-文件名spiral.py
import turtle      #导入turtle模块
p = turtle.Turtle()  #创建海龟对象
p.speed(0)        #定义绘图的速度(“fastest”或者0均表示最快)
colors = ["red", "blue", "green", "yellow"] #红、蓝、绿、黄四种颜色
for i in range(100):         #i=0~99
    p.pencolor(colors[i%4]) #设置画笔颜色(红或蓝或绿或黄)
    p.circle(i)            #画圆
    p.left(91)             #向左旋转91度
小乌龟画图

 

#area
import math
a = float(input("请输入三角形的边长a:"))
b = float(input("请输入三角形的边长b:"))
c = float(input("请输入三角形的边长c:"))
h = (a + b + c) / 2                #三角形周长的一半
area = math.sqrt(h*(h-a)*(h-b)*(h-c));#三角形面积
print(str.format("三角形三边分别为:a={0},b={1},c={2}", a, b, c))
print(str.format("三角形的面积 = {0}", area))
输入边长求面积

 

#getValue.py

def getValue(b,r,n):          #创建函数对象getValue
    v = b*((1+r)**n)         #计算最终收益v
    return v                       #使用return返回值

total = getValue(1000,0.05,5)  #调用函数getValue()
print(total) 
定义函数并调用函数

 

#导入需要的库包并进行字体设置使能正确显示中文
import matplotlib.pyplot as plt
plt.rcParams['font.sans-serif']='SimHei' # 设置字体,避免中文乱码


# 准备待绘制图形的数据
x=range(1,13) # 生成1至12共12个值的整数列表,表示月份
y1=[34,35,36.5,37,36.8,37,36.8,38,37,40,45,37]# 营业收入
y2=[25.5,26,27.3,27.7,27,27.7,27.6,28.5,27.7,29,31,28]# 成本
xticksLabel=[str(x)+'' for x in x] # x轴刻度对应的标签

#绘制图形,1中设置途中两个坐标系排列方式为2行1列
# 1、创建四个子图(坐标系)。返回画板和子图列表
fig,axes=plt.subplots(2,1)

# 2 获取每个子图对象,并绘制图形
# 在第一个子图上绘图
axes1=axes[0]
print(type(axes1))
axes1.plot(x,y1)
axes1.set_title('营业收入曲线')# 设置标题
axes1.set_xlabel('月份') # 设置x轴名称
axes1.set_ylim(0,60) # 设置y轴的范围
axes1.set_ylabel('金额') # 设置y轴名称
axes1.set_xticks(x) # 设置x轴的显示刻度
axes1.set_xticklabels(xticksLabel,rotation=45) # 设置x轴刻度标签

# 在第二个子图上绘图
axes2=axes[1]
axes2.bar(x,y1)
axes2.set_title('营业收入柱形图')
axes2.set_ylabel('金额') # 设置y轴名称
axes2.set_xticks(x) # 设置x轴的显示刻度
axes2.set_xticklabels(xticksLabel) # 设置x轴刻度标签

#设置紧凑布局并显示图形
plt.tight_layout()
plt.show()
绘制折线图和条状图

 

#!usr/bin/env python3
#-*- coding:utf-8 -*-
word = input("请输入或者拷贝含有敏感词的宣传文字:\n")
sensitive = ['第一','交通','一流','国家级','顶级','核工业']
sensitive_find=[]
newword = word
for item in sensitive:
    if word.count(item)>0:
        sensitive_find.append(item+':\t'+str(word.count(item))+'')
        newword=newword.replace(item, '\033[1;41m'+item+'\033[0m')
print('发现敏感词如下:')
mark='='*12
print(mark)
for item in sensitive_find:
    print(item)
print(mark)
print('敏感词已经标注为红色:\n',newword)

#输入文字示例:国民经济支柱产业处在第一位的是轨道交通、核工业、航空航天、能源等;四川是交通大省和核工业研发中心。
输入一段文字将其中的敏感词语标红色

  

#基于字典的算法
#==============================================准备数据
d_date1={'鲫鱼':[17,10.5],'鲤鱼':[8,6.2],'鲢鱼':[7,4.7]}     #1月1日钓鱼记录
d_date2={'草鱼':[2,7.2],'鲫鱼':[3,12],'黑鱼':[6,15]}         #1月2日钓鱼记录
d_date3={'乌龟':[1,78.10],'鲫鱼':[1,10.78],'草鱼':[5,7.92]}        #1月3日钓鱼记录
fish_records={'1月1日':d_date1,'1月2日':d_date2,'1月3日':d_date3}  #所有钓鱼记录 
#==============================================相关变元对象
nums=0          #钓鱼总数量初始化定义
amount=0        #钓鱼总金额初始化定义
day=''          #日期记录变量初始化定义
day_record={}   #钓鱼每天记录字典变量初始化定义
stat_record={}  #统计记录变量初始化定义
name_n=''       #最大数量的鱼
max_nums=0      #最大数量
name_a=''       #最大金额的鱼
max_amount=0    #最大金额
#==============================================按鱼名进行数量,金额累计
print('=========每日钓鱼记录==========')
for day,day_record in fish_records.items():   #循环获取每天记录(元组形式)
    print('%s钓鱼记录为:'%(day))              #打印当天的日期
    #循环获取当天鱼与数量,单价关系的记录
    for name,sub_recods in day_record.items(): 
        nums+=sub_recods[0]                    #数量累加
        amount+=sub_recods[0]*sub_recods[1]    #金额累加
        #打印名称,数量,单价
        print('    %s数量%d,单价%.2f元'%(name,sub_recods[0],sub_recods[1]))
        #判断鱼是否在统计字典里,在,则做累计处理
        if name in stat_record:                
            stat_record[name][0]+=sub_recods[0]#每种鱼数量累计
            stat_record[name][1]+=sub_recods[0]*sub_recods[1]#每种鱼金额累计
        else:#第一次累计,直接在字典里赋值
            stat_record[name]=[sub_recods[0],sub_recods[0]*sub_recods[1]]
#==============================================在统计记录字典变量里找最大值
print('=====按鱼进行数量,金额统计=====')
for name1,get_L in stat_record.items():
    print('%s的总数量%d,金额为%.2f元'%(name1,get_L[0],get_L[1]))
    get_nums_d={name1:get_L[0]}
    if get_L[0]>max_nums:                      #寻找最大数量的鱼
        name_n=name1
        max_nums=get_L[0]
    get_amount_d={name1:get_L[1]}        
    if get_L[1]>max_amount:                    #寻找最大金额的鱼
        name_a=name1
        max_amount=get_L[1]
#==============================================统计结果打印
print('====最大值,总数量,总金额统计====')
print('最大数量的鱼是%s,%d条'%(name_n,max_nums))
print('最大金额的鱼是%s,%.2f元'%(name_a,max_amount))
print('钓鱼总数量为%d,总金额为%.2f元'%(nums,amount)) #打印总数量,总金额
















#以下为运行输出结果

=========每日钓鱼记录==========
1月1日钓鱼记录为:
    鲫鱼数量17,单价10.50元
    鲤鱼数量8,单价6.20元
    鲢鱼数量7,单价4.70元
1月2日钓鱼记录为:
    草鱼数量2,单价7.20元
    鲫鱼数量3,单价12.00元
    黑鱼数量6,单价15.00元
1月3日钓鱼记录为:
    乌龟数量1,单价78.10元
    鲫鱼数量1,单价10.78元
    草鱼数量5,单价7.92元
=====按鱼进行数量,金额统计=====
鲫鱼的总数量21,金额为225.28元
鲤鱼的总数量8,金额为49.60元
鲢鱼的总数量7,金额为32.90元
草鱼的总数量7,金额为54.00元
黑鱼的总数量6,金额为90.00元
乌龟的总数量1,金额为78.10元
====最大值,总数量,总金额统计====
最大数量的鱼是鲫鱼,21条
最大金额的鱼是鲫鱼,225.28元
钓鱼总数量为50,总金额为529.88元
字典的应用-统计钓鱼信息

 

 

可命名为:insecurePasswordBox.py

"""简易口令保管箱程序"""
import os
import json
import pyperclip
import collections

def clipGetPassword(curPS):
    pyperclip.copy(curPS)
    print("该账户对应密码已拷贝至剪切板,供粘贴使用")


ab = {}   #口令保存在字典中


#从JSON文件中读取账户与对应密码
if os.path.exists("passwordbook.json"):
    with open(r'passwordbook.json', 'r', encoding='utf-8') as f:
        ab = json.load(f)



while True:
    print('')
    print("|====欢迎使用口令保管箱程序====|")
    print("|---- 1: 显示账号密码清单 ----|")
    print("|---- 2: 查询修改账号资料 ----|")
    print("|---- 3: 插入新账号和密码 ----|")
    print("|---- 4: 删除账号对应密码 ----|")
    print("|---- 0:----退  出---------|")
    print("|==========================|")

    choice = input('请选择功能菜单(0-4):')
    if choice == '1':
        if(len(ab)==0):
            print("账号薄为空")
        else:
            for k, v in ab.items():
                print("账号={},对应密码={}".format(k, v))
    elif choice == '2':
        name = input("请输入账号名称:")
        if(name not in ab):
            ask = input("账号不存在,是否增加账号资料(Y/N)")
            if ask in ["Y", "y"]:  
                pw = input("请输入账号对应密码:")
                ab[name] = pw
                clipGetPassword(pw)
        else:
            print("账号信息:{} {}".format(name, ab[name]))
            clipGetPassword(ab[name])
            ask = input("是否修改账号资料(Y/N)")
            if ask in ["Y", "y"]:
                pw = input("请输入账号对应的密码字符串:")
                ab[name] = pw
                clipGetPassword(pw)

    elif choice == '3':
        name=input("请输入新增账号名称:")
        if(name in ab):  
            print("已存在账号名称:{} 对应密码:{}".format(name, ab[name]))
            clipGetPassword(ab[name])
        else:  
            pw = input("请输入新增账号对应的密码字符串:")
            ab[name] = pw
            clipGetPassword(pw)
    elif choice == '4':
        name = input("请输入账户名称:")
        if(name not in ab):  
            print("该账户不存在:{}".format(name))
        else:
            pw = ab.pop(name)
            print("删除  账号:{} 及其对应的密码:{}".format(name, pw))
    elif choice == '0': #保存到JSON文件并退出循环
        with open(r'passwordbook.json', 'w', encoding='utf-8') as f:
            json.dump(ab, f)        
        break
密码保管箱

 

 

 

补充示例:

data_sort = []
i = 0

data ="莱科宁 236,汉密尔顿 358, 魏泰尔 294, 维斯塔潘 216, 博塔斯 227"
newlist = data.split(',')

for item in newlist:
    opendata = item.split(' ')
    data_sort.append([opendata[1], opendata[0]])

data_sort.sort(reverse = True)

print("\033[1;34m=" * 35)
print("输出F1大奖赛车手积分".center(25))
print('='*35 + '\033[0m')
print('排名     车手     积分')

for item in data_sort:
    i = i + 1
    print('\033[1;32;41m' + str(i).zfill(2) + '\033[0m',   item[1].ljust(14) + '\t',    item[0].ljust(6) + '\t')
    print()
字符冲分解并显示柱状图
import random

# 定义一个列表用来保存3个办公室
offices = [[], [], []]
# 定义一个列表用来存储8位老师的名字
names = ['张老师', '李老师', '赵老师', '高老师',
         '刘老师', '周老师', '王老师', '吴老师']
for name in names:
    # 将8位老师按照索引为0、1、2进行分组
    index = random.randint(0, 2)
    # print(index)
    # 将8位老师放在不同列表中
    offices[index].append(name)
flag = 1
for tempNames in offices:
    print('办公室%d的人数为:%d' % (flag, len(tempNames)))
    flag += 1
    for name in tempNames:
        print("%s" % name, end=' ')
    print(" ")
随机分配办公室
chart = [ ['alibaba',4580],['amazon',9628],['apple',11331],['oracle',2053]]

hchartall = 300
color = '43m'

for item in chart:
    hchartwid =  int(item[1]/hchartall)
    print(item[0].ljust(8) + '\033[1;32;' + color + ' '.ljust(hchartwid) + '\033[0m')
    print('')
列表操作-股票指数柱状图

 

# 实际案例中,将删除查找联系人功能(index方法没有涉及)
person_info = []
print("=" * 20)
print('欢迎使用通讯录:')
print("1.添加联系人")
print("2.查看通讯录")
print("3.删除联系人")
print("4.修改联系人信息")
print("5.查找联系人")
print("6.退出")
print("=" * 20)
while True:
    per_dict = {}
    fun_num = input('请输入功能序号:')
    if fun_num == '1':
        per_name = input('请输入联系人的姓名:')
        phone_num = input('请输入联系人的手机号:')
        per_email = input('请输入联系人的邮箱:')
        per_address = input('请输入联系人的地址:')
        # 判断输入的是否为空
        if per_name.strip() == '':
            print('请输入正确信息')
            continue
        else:
            per_dict.update({'姓名': per_name,
                             '手机号': phone_num,
                             '电子邮箱': per_email,
                             '联系地址': per_address})
            person_info.append(per_dict)  # 保存到列表中
            print('保存成功')
    elif fun_num == '2':
        if len(person_info) == 0:
            print('通讯录无信息')
        for i in person_info:
            for title, info in i.items():
                print(title + ':' + info)
    elif fun_num == '3':  # 删除
        if len(person_info) != 0:
            del_name = input('请输入要删除的联系人姓名:')
            for i in person_info:
                if del_name in i.values():
                    person_info.remove(i)
                    print(person_info)
                    print('删除成功')
                else:
                    print('该联系人不在通讯录中')
        else:
            print('通讯录无信息')
    elif fun_num == '4':  # 修改
        if len(person_info) != 0:
            modi_info = input('请输入要修改联系人姓名:')
            for i in person_info:
                if modi_info in i.values():
                    # 获取所在元组在列表中的索引位置
                    index_num = person_info.index(i)
                    dict_cur_perinfo = person_info[index_num]
                    for title, info in dict_cur_perinfo.items():
                        print(title + ':' + info)
                    modi_name = input('请输入新的姓名:')
                    modi_phone = input('请输入新的手机号:')
                    modi_email = input('请输入新的邮箱:')
                    modi_address = input('请输入新的地址:')
                    dict_cur_perinfo.update(姓名= modi_name)
                    dict_cur_perinfo.update(手机号= modi_phone)
                    dict_cur_perinfo.update(电子邮箱= modi_email)
                    dict_cur_perinfo.update(联系地址= modi_address)
                    print(person_info)
        else:
            print('通讯录无信息')
    elif fun_num == '5':  # 查找
        if len(person_info) != 0:
            query_name = input('请输入要查找的联系人姓名:')
            for i in person_info:
                if query_name in i.values():
                    index_num = person_info.index(i)
                    for title, info in person_info[index_num].items():
                        print(title + ':' + info)
                    break
            else:
                print('该联系人不在通讯录中')
        else:
            print('通讯录无信息')

    elif fun_num == '6':  # 退出
        break

 

 

 

5  
 

现实生活中数据组织方式与python基本类型

 

 

 

#基于字典的算法
#==============================================准备数据
d_date1={'鲫鱼':[17,10.5],'鲤鱼':[8,6.2],'鲢鱼':[7,4.7]}     #1月1日钓鱼记录
d_date2={'草鱼':[2,7.2],'鲫鱼':[3,12],'黑鱼':[6,15]}         #1月2日钓鱼记录
d_date3={'乌龟':[1,78.10],'鲫鱼':[1,10.78],'草鱼':[5,7.92]}        #1月3日钓鱼记录
fish_records={'1月1日':d_date1,'1月2日':d_date2,'1月3日':d_date3}  #所有钓鱼记录 
#==============================================相关变元对象
nums=0          #钓鱼总数量初始化定义
amount=0        #钓鱼总金额初始化定义
day=''          #日期记录变量初始化定义
day_record={}   #钓鱼每天记录字典变量初始化定义
stat_record={}  #统计记录变量初始化定义
name_n=''       #最大数量的鱼
max_nums=0      #最大数量
name_a=''       #最大金额的鱼
max_amount=0    #最大金额
#==============================================按鱼名进行数量,金额累计
print('=========每日钓鱼记录==========')
for day,day_record in fish_records.items():   #循环获取每天记录(元组形式)
    print('%s钓鱼记录为:'%(day))              #打印当天的日期
    #循环获取当天鱼与数量,单价关系的记录
    for name,sub_recods in day_record.items(): 
        nums+=sub_recods[0]                    #数量累加
        amount+=sub_recods[0]*sub_recods[1]    #金额累加
        #打印名称,数量,单价
        print('    %s数量%d,单价%.2f元'%(name,sub_recods[0],sub_recods[1]))
        #判断鱼是否在统计字典里,在,则做累计处理
        if name in stat_record:                
            stat_record[name][0]+=sub_recods[0]#每种鱼数量累计
            stat_record[name][1]+=sub_recods[0]*sub_recods[1]#每种鱼金额累计
        else:#第一次累计,直接在字典里赋值
            stat_record[name]=[sub_recods[0],sub_recods[0]*sub_recods[1]]
#==============================================在统计记录字典变量里找最大值
print('=====按鱼进行数量,金额统计=====')
for name1,get_L in stat_record.items():
    print('%s的总数量%d,金额为%.2f元'%(name1,get_L[0],get_L[1]))
    get_nums_d={name1:get_L[0]}
    if get_L[0]>max_nums:                      #寻找最大数量的鱼
        name_n=name1
        max_nums=get_L[0]
    get_amount_d={name1:get_L[1]}        
    if get_L[1]>max_amount:                    #寻找最大金额的鱼
        name_a=name1
        max_amount=get_L[1]
#==============================================统计结果打印
print('====最大值,总数量,总金额统计====')
print('最大数量的鱼是%s,%d条'%(name_n,max_nums))
print('最大金额的鱼是%s,%.2f元'%(name_a,max_amount))
print('钓鱼总数量为%d,总金额为%.2f元'%(nums,amount)) #打印总数量,总金额
钓鱼统计

 

 

 6  
 

 关于python文件系列的组织方式:脚本、函数、模块、库(包)

         脚本 .py

        多个函数 写在一个 .py文件里, 模块

        多个 .py文件组成的文件夹 库

 

 7  
 

 

如果jupyter运行时缺少指定模块,需要在anaconda中增加安装模块,可以在Qt控制台中安装。

 

   
8 常用的需要熟练掌握的代码
 

常用的需要熟练掌握的代码:

(0)

# coding = utf-8
#!/usr/bin/python

 

if "__name__" == "__main__":
     pass

 

(1)

import numpy as np

import matplotlib.pyplot as plt;     plt.rcParams['font.sans-serif'] = ['SimHei'] #解决中文乱码

import pandas an pd 

(2) 读入文件

df = pd.read_excel('filename.xlsx')

df = pd.read_excel('filename.xlsx',sheet_name='sheet01')  #导入指定sheet01页的数据

df = pd.read_excel('filename.xlsx',sheet_name='sheet01',usecols = [0])  #导入指定sheet01页指定列[0,3]的数据

df = pd.read_excel('filename.xlsx',sheet_name='sheet01',usecols = [''会员名,'地址'])  #导入指定sheet01页指定列[0,3]的数据

 

 

读入文件时指定行索引、列标题

df = pd.read_excel('filename.xlsx',header=1)                   #导入文件并指定第1行作为类索引

df = pd.read_excel('filename.xlsx',index_col=0)                #导入文件并指定0列作为行索引

 

 

(3) pd属性设置

pd.set_option('display.unicode.east_asian _width', True)   #解决出现列不对齐的问题  

pd.set_option('display.unicode.ambiguous_as', True)   #解决出现列不对齐的问题  

 

pd.set_option('display.max_columns', 1000,'display.max_rows', 1000)   #设置print(df.head())显示多行多列`

df.head(), df.head(10), df.tail(), df.tail(10)

df.shape[行索引], df.shape[列索引]

df.info  #查看索引、数据类型和内存信息

 

df.values,  df.index,  df.index[1,2,3],  df.columns,  df.columns['语文','外语','数学']

 

df.describe()   #查看每一列的汇总信息

df.count()     #返回每一列中的非空值个数

df.sum()    # 返回每一列的和,如果无法计算返回空值

df.max()    #返回每一列的最大值

df.argmax()    #返回最大值所在的自动索引位置,       df.argmin()

df.idxmax()    #返回最大值所在的自定义索引位置   ,df.idxmin()

 

df.mean()    #返回每一列的平均值

df.median()   #返回每一列的中位数

df.var()    #返回每一列的方差

df.std()    #放回每一列的标准差

 

df.isnull()    #检查df中的空值,空值为Ttue;否则为False; 返回布尔型数组。

df.notnull()            #检查df中的空值,非空值为True;否则为False;返回布尔型数组。

 

 

 

 

(3) #解决中文乱码问题的代码

 

 

 9  
 

Pandas速查表·——摘自明日科技编著的《python 数据分析从入门到实践》吉林大学出版社。

1 Pandas模块速查表

 

 

 

2 Pandas模块速查表——Series对象

 

 

 

 

 

4 Matplotlib模块速查表——图表绘制专属函数

 

 

 

 

5 Matplotlib模块速查表——图表设置函数

 

 

 

 

 

6 图表颜色值速查表

 

 

 

 

 

 

 

 

 10  
 

程序打包


1. 首先安装打包库 pyinstaller.   安装命令 pip install pyinstaller
2. 准备好程序log图标
  利用在线图标制作程序制作ico格式图标。 myLog.ico
  网址:https://tool.520101.com/diannao/ico/
3. 将需要打包的xxx.py文件及其相关文件(如读写的文档)和myLog.icl放在同一个路径下(全英文路径)
4. 使用以下一条命令打包:

  pyinstaller -F xxx.py  打包exe

  pyinstaller -F -w xxx.py  不带控制台的打包 ——注:此时程序源码中不应该有input语句

  pyinstaller -F -w -i yyy.ico xxx.py 打包指定exe图标打包

  pyinstaller -F  -i yyy.ico xxx.py 打包指定exe图标打包

 

备注:

(1)需要先在集成环境中已经能够运行,确保现有环境中已经包含相关的依赖包。如pyperclip;

(2)安装python3之后在安装路径下Script文件夹内安装有pip.exe,如果需要更新,更新命令为: python.exe -m pip install --upgrade pip

(3) 如果使用打包-w 选项已经屏蔽了控制台,因此程序中不应该input语句,否则会报错“RuntimeError: input(): lost sys.stdin” 。

   
posted on 2024-07-26 10:29  海阔凭鱼跃越  阅读(5)  评论(0编辑  收藏  举报