python猜数游戏和天气查询

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

# -*- coding: UTF-8 -*-
'''
一个python编程基本功案例-猜数游戏
Created on 2015年9月4日
@author: yxkj
'''
from random import randint
import os
import datetime

game_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=0
print("**********猜数游戏(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=False
while  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=times
total_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+=line
res=timelabel+res

f=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.request
import json
import time
from city import city#从city.py里导入的城市代码

exit=False
while 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('没有找到您输入的城市!')
    
    
    
    
    
    


  • 3
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程猿薇茑

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值