加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

用python写一个猜数字的小游戏

(2013-07-12 23:52:25)
标签:

python

it

经常会有人玩猜数字游戏,就是我选一个数字看谁能猜到,玩法简单男女老少皆宜。那么用python怎么来玩这个呢?今天就简单写一个小脚本,让你跟电脑玩猜数字游戏,一看就是屌丝啊!
1.电脑先选定一个数字,然后你在输入一个数字,如果猜中数字比设定的数字要大输出'too big',要是小的话输出‘too small’,要是猜中的话输出‘yes,you are right answer!’
 
computer = 25
you = int(raw_input('please input a number:'))
if you > computer:
    print 'too big'
elif you < computer:
    print 'too small'
else:
    print'yes,you are right answer!'
PS:这个用到了简单的IF语句来判断。
输入我用了int(raw_input),因为raw_input默认输入的都是字符串,加上int表示输出的数字,或者可以直接用input也可以的。
2.上面是我们只能猜一次游戏就结束了,现在改进下只有你猜中数字了猜数字游戏才结束。
computer = 25
while True:
     you = int(raw_input('please input a number:'))
    if you > computer:
        print '%d is too big' %you
    elif you < computer:
        print '%d is too small'%you
    else:
        print'yes,you are right ,the answer is %d!' %you
        break
PS:用到了while循环,设置为真,直到符合条件了即猜中数字了就break,跳出程序。
3.前面两个都是我们事先给定了一个数字,这还不是真正的猜数字,那么我们事先不知道电脑选了是什么数字改怎么猜呢?其实也很简单就是加一个随机选择模块,让电脑自己随机选择一个数字。
from random import randint
computer = randint(1,100)
while True:
you = int(raw_input('please input a number in 1-100:'))
if you > computer:
    print '%d is too big' %you
elif you < computer:
    print '%d is too small'%you
else:
    print'yes,you are right ,the answer is %d!' %you
    break
OK,整个程序结束。
random随机选择模块
random.randint(a,b)随机选择整数,a是下限,b是上限。
这样一个猜数字游戏小程序就基本完形了,跟平时玩的差不多了。其实猜100以内的数字最多只要7步就能猜出,只要是按照对半去猜就可以了!
嗯,其实这些很多都是在网上跟别人学的,初学还是有很多不知道。

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有