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

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