先放上迭代后的代码
#coding=utf-8
import platform,codecs
def getWeatherInfo():
'''函数功能:从文本查询天气信息'''
with open ('weather_info.txt', 'r', encoding='utf-8') as f:
city_weather={}
for lines in f.readlines():
line=lines.strip().split(',')
city_weather[line[0]] = line [1]
return city_weather
def exitQuery():
'''函数功能:退出查询'''
print ('感谢您的使用,再见!')
exit(0)
def getHelpInfo():
'''函数功能:打印帮助信息'''
print('''
- 输入城市名,获取该城市的天气情况;
- 输入 ?/help,获取本帮助信息;
- 输入 h/history,获取历史查询信息;
- 输入 q/quit,退出天气查询系统。''')
def printErrorInfo():
'''函数功能:打印错误信息'''
print ('''你输入的指令错误或者城市名称不存在,请重新输入。
- 如果不清楚指令,可以输入 help,获取帮助。
''')
def getHistory(history):
'''函数功能:打印历史查询信息
调用格式:getHistory(history)
需要输入历史查询记录'''
if history:
print ()
print ('你查询过以下城市的天气情况:')
for i in range(history.__len__()):
print (i+1,history[i])
else:
print ('并无查询历史记录')
def printWeatherInfo(city,history):
print (city, city_weather[city])
str=city+' '+city_weather[city]
history.append(str)
return history
if __name__=='__main__':
#打印运行版本
print ('Python version:',platform.python_version())
#读取城市天气信息,每次程序运行只读取一次
city_weather=getWeatherInfo()
#定义查询历史
queryHistory=[]
while True:
user_input=input('\n请输入指令或您要查询的城市名:')
#将输入转换为小写
user_input=user_input.lower()
if user_input=="quit" or user_input=="q":
getHistory(queryHistory)
exitQuery()
elif user_input=="help" or user_input=="?":
getHelpInfo()
elif user_input=="h" or user_input=="history":
getHistory(queryHistory)
elif user_input in city_weather:
queryHistory=printWeatherInfo(user_input,queryHistory)
else:
printErrorInfo()
优化1:函数封装 之前写的代码都是直接书写语句,现在重新写成代码,可读性更强。 主函数中只有各个函数的调用,非常简洁,并且代码更易于重用。
在教练的点评中,在函数头加入了函数的帮助文档,方便打印和查看。以后编写的代码中也要加入这部分。
def printErrorInfo(): '''函数功能:打印错误信息'''这样用ipython可以查看到:
In [2]: from CheckWeather2 import getHistory
In [3]: from CheckWeather2 import printErrorInfo
In [4]: help(getHistory)
Help on function getHistory in module CheckWeather2:
getHistory(history)
函数功能:打印历史查询信息,输出查询序号、时间和结果
调用格式:getHistory(history)
需要输入历史查询记录
In [5]: help (printErrorInfo)
Help on function printErrorInfo in module CheckWeather2:
printErrorInfo()
函数功能:打印错误信息
优化2:用with open ... as x 来打开文件,代码更优雅 用with打开文件,可以保证文件的正常关闭
参考文章:理解Python中的with…as…语法
优化3:运用name=='main' 用name来判断是否是main的好处是:让你写的脚本模块既可以导入到别的模块中用,另外该模块自己也可执行。
参考文章:知乎链接