python编程初学者入门案例-猜数游戏和天气查询

来源:互联网 发布:mac字体库里灰色字体 编辑:程序博客网 时间:2024/06/07 08:46

python基本功练习案例,涉及流程控制、文件I/O、模块使用(保存代码为game.py,在装有python3解释器的系统相应目录下运行python game.py)

# -*- coding: UTF-8 -*-'''一个python编程基本功案例-猜数游戏Created on 2015年9月4日@author: yxkj'''from random import randintimport osimport datetimegame_times=0#游戏次数min_times=0#历次游戏最小多少轮猜对total_times=0#历次游戏总共猜的轮数game_save_file="d:"+os.sep+"game.txt"scores={}#用字典保存不同玩家的记录if os.path.exists(game_save_file):    print("请输入您的玩家名称:")    player=input()    f=open(game_save_file,'r')    lines=f.readlines()[1:]#文件第一行是时间    f.close()    for line in lines:        s=line.split()        scores[s[0]]=s[1:]    score=scores.get(player)    if score is None:        score=[0,0,0]    game_times=int(score[0])    min_times=int(score[1])    total_times=int(score[2])else:    print("游戏文件已丢失!请先创建游戏记录保存文件"+game_save_file)    exit(0)    if game_times>0:    avg_times=float(total_times)/game_times#平均猜对的轮数else:    avg_times=0print("**********猜数游戏(1-100)*********")print("%s,您已经玩了%d次,最少%d轮猜出答案,平均%.2f轮猜出答案"%(player,game_times,min_times,avg_times))starttime=datetime.datetime.now()timelabel=starttime.strftime("%Y-%m-%d %H:%M:%S %p\n")num=randint(1,100)#电脑随机产生一个数times=0#记录本次游戏猜的轮数print("Guess what I think?")bingo=Falsewhile  not bingo:    times+=1    ans=int(input())    if ans<num:        print("too small!")    elif ans>num:        print("too big!")    else:        print("Bingo!")        bingo=True#猜对即退出游戏,并保存游戏记录到本地if game_times==0 or times<min_times:#如果是第一次玩或者是times小于历史记录则更新    min_times=timestotal_times+=times#游戏总轮数增加game_times+=1#游戏总次数增加scores[player]=[str(game_times),str(min_times),str(total_times)]res=""#本例的做法是把全部玩家的记录覆盖一遍for i in scores:    line=i+" "+" ".join(scores[i])+"\n"    res+=lineres=timelabel+resf=open(game_save_file,'w')f.write(res)f.close()

利用中国天气网提供的查询接口查询天气(city.py请百度之)

# -*- coding: UTF-8 -*-'''Created on 2015年9月4日查天气小程序@author: Mr.ZHOU'''import urllib.requestimport jsonimport timefrom city import city#从city.py里导入的城市代码exit=Falsewhile not exit:    #输入城市    cityname=input('输入你想要查询的城市(按Q退出):')    #退出功能    if cityname=="q" or cityname=="Q":        print("退出程序!")        exit=True    else:        citycode=city.get(cityname)        #print(citycode)        if citycode:            try:                url='http://www.weather.com.cn/data/cityinfo/%s.html'%citycode                #print(url)                content=urllib.request.urlopen(url)                content=content.read().decode('utf-8')                #print("content:"+str(content))                #把json转换成字典格式                data=json.loads(content)                result=data['weatherinfo']                #print("type(result)"+str(type(result)))                #print("result:"+str(result))                str_temp=('%s\n%s~%s')%(result['weather'],result['temp2'],result['temp1'])                timenow=time.strftime('%Y-%m-%d',time.localtime(time.time()))                print(timenow+"  "+result['city']+"\n"+str_temp)            except:                print("查询出错,稍后再试!")        else:             print('没有找到您输入的城市!')                        


1 0
原创粉丝点击