函数,将一段代码,封装起来,可以在任何区域进行调用执行
# 定义函数
def eat():
print '中午该吃饭了'
# 调用函数
eat()
# 带参数的函数
def sleep(hour):
print '天冷该睡觉了~,睡了%s小时'%hour
# 调用带参数的函数
sleep(8)
# 带有两个或者多个参数时,每个参数之间用,逗号隔开
def buy_water(money,name):
print '给你%s块钱,我要买%s'%(money,name)
# 调用多个参数的函数
buy_water(10,'康师傅矿泉水')
# 买水需要两个参数,钱,水名称
# 买水函数执行完成之后,返回执行的结果
def buy_water(money,name):
# 执行一定的业务代码之后,返回一个或者多个结果
print '买了%s,消费1元。'%name
money = money - 1
# return 返回执行函数的结果
return money
money = buy_water(20,'康师傅矿泉水~')
解析json数据
从API中获取想要的数据接口
在线格式化json
导入 python 内置的包 import json
把json字符串转换成python中的字典或列表
url地址(统一资源定位符)
在python中发送请求:
下载requests包,使用requests发请求
pip install requests 下载包
pip list 查看已经安装的包
天气预报
# coding:utf-8
import requests
import json
# 1.准备url地址
url = 'http://api.map.baidu.com/telematics/v3/weather?location=%s&output=json&ak=TueGDhCvwI6fOrQnLM0qmXxY9N0OkOiQ&callback=?'%city
# 2.发送一个get请求,获取url地址下的资源内容
# get(url) 需要将url地址作为参数进行传递
# response 接受服务器返回的响应数据
response = requests.get(url)
# 3.把json字符串转换成python中的字典或列表
weather_dict = json.loads(response.content)
# 根据key取出字典中对应的值
date = weather_dict.get('date')
print 'date',date
# 取出result列表
results = weather_dict['results']
#取出results中的字典
detail_dict = results[0]
# 取出当前城市
currentCity =detail_dict['currentCity']
print u'当前城市为:%s'%currentCity
pm25 = detail_dict['pm25']
# 把取出的pm25字符串转化成数字,再进行比较
pm25 = int(pm25)
if pm25 <= 50:
print 'pm值%s,优'%pm25
elif pm25 <= 100:
print 'pm值%s,良'%pm25
elif pm25 <= 150:
print 'pm值%s,轻度污染'%pm25
elif pm25 <= 200:
print 'pm值%s,中度污染' % pm25
elif pm25 <= 300:
print 'pm值%s,重度污染'%pm25
else:
print 'pm值%s,严重污染' % pm25
print currentCity,pm25
indexs = detail_dict['index']
# for循环遍历index列表,取出小字典
for index in indexs:
title = index['title']
zs = index['zs']
tipt = index['tipt']
des = index['des']
print u'标题:%s 指数:%s 提示:%s 建议:%s'%(title,zs,tipt,des)
# 取出天气情况列表
weather_data = detail_dict['weather_data']
#取出weather_data中的字典
for weather_dict in weather_data:
date = weather_dict['date']
weather = weather_dict['weather']
wind = weather_dict['wind']
temperature = weather_dict['temperature']
print u'日期:%s 天气:%s 风级:%s温度:%s'%(date,weather,wind,temperature)