一. 将函数存储在模块中
1.首先打开IDLE,然后新建File
2.以.py保存在某一路径下(此处为pizza.py)
def make_pizza(size,*toppings):
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"-{topping}")
3.再重新建一个File,与(2)保存在同一路径下。
import pizza
pizza.make_pizza(16,'pepperoni')
pizza.make_pizza(12,'mushrooms','green peppers','extra cheese')
或者
from pizza import make_pizza
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
使用as给函数指定别名
from pizza import make_pizza as mp
mp(16,'pepperoni')
mp(12,'mushrooms','green peppers','extra cheese')
使用as给模块指定别名
import pizza as p
p.make_pizza(16,'pepperoni')
p.make_pizza(12,'mushrooms','green peppers','extra cheese')
导入模块中的所有函数
from pizza import*
make_pizza(16,'pepperoni')
make_pizza(12,'mushrooms','green peppers','extra cheese')
4.运行(3),的结果
5.绘制随机漫步图
6.*****
7.掷骰子
8.读取csv
#成交量的汇总
import csv
import matplotlib.pyplot as plt
from datetime import datetime
filename='shuju.csv'
with open(filename) as f:
reader=csv.reader(f)
header_row=next(reader)#读取下一行
dates,highs,lows=[],[],[]
for row in reader:
current_date=datetime.strptime(row[0],' %Y/%m/%d')
try:
high=float(row[2])#如果缺失某一天的数据,要确保仍能继续画
low=float(row[3])
except ValueError:
print(f"Missing data for {current_date}")
else:
dates.append(current_date)
high=float(row[2])
low=float(row[3])
highs.append(high)
lows.append(low)
plt.style.use('seaborn')
fig,ax=plt.subplots()
ax.plot(dates,highs,c='red',alpha=0.5)
ax.plot(dates,lows,c='blue',alpha=0.5)
ax.fill_between(dates,highs,lows,facecolor='blue',alpha=0.5)#填充蓝色,透明度为0.1
plt.rcParams['font.sans-serif'] = ['SimHei']#显示汉字
plt.rcParams['axes.unicode_minus'] = False #显示汉字
plt.title("开盘最高及最低",fontsize=24)
plt.xlabel("",fontsize=16)
fig.autofmt_xdate()#使得日期倾斜
plt.ylabel("成交量",fontsize=16)
plt.tick_params(axis='both',which='major',labelsize=16)
plt.show()
9.由于缺少json文件,只是大体写了代码,无图
#地震,查看json数据
import json
filename='core.json'
with open(filename) as f:
all_eq_data=json.load(f)
all_eq_dicts=all_eq_data['features']
#print(len(all_eq_dicts))
mags,titles,lons,lats=[],[],[],[]
for eq_dict in all_eq_dicts:
mag=eq_dict['properties']['mag']
title=eq_dict['properties']['title']
lon=eq_dict['geometry']['coordinates'][0]
lat=eq_dict['geometry']['coordinates'][1]
mags.append(mag)
titles.append(title)
lons.append(lon)
lats.append(lat)
#print(mags[:5])
'''下面三行和labels的功能一样'''
"""
data=pd.DataFrame(
data=zip(lons,lats,titles,mags),columns=['经度','维度','位置','震级'])
data.head()
"""
fig=px.scatter(#scatter散点图
#data
x=lons,
y=lats,
# x='经度', 对应上面注释掉的三行
# y='维度',
labels={'x':'经度','y':'纬度'},
range_x=[-200,200],
range_y=[-90,90],
width=800,#像素
height=800,
title='全球地震散点图'
#size='震级',
#size_max=10,
#color='震级'
#coloe_continuous_scale='jet'#渐变色
#hover_name='位置'
)
fig.write_html('global_earthquakes.html')
fig.show()