有一个猜字游戏,现在的情况是,计算机随机生成一个整数,这个整数的区间我们事先给定,这里假定数在0到100之间,然后我们猜字,当猜的数大于生成的整数时,输出“Your answer is too large.”,当猜的数小于生成的整数时,输出“Your answer is too small.”,猜中数字输出“BINGO!!”,结束游戏,下面是python的脚本,以及测试情况:
def main():
import random
a=random.randint(0,100)
print('Guess what i think?')
b=int(input('Enter a number:'))
while(b!=a):
if(b<a):
print('Your answer is too small.')
elif(b>a):
print('Your answer is too large.')
b=int(input('Enter a number:'))
print('BINGO!!')
测试结果:
>>> main()
Guess what i think?
Enter a number:0
Your answer is too small.
Enter a number:100
Your answer is too large.
Enter a number:50
Your answer is too large.
Enter a number:25
Your answer is too small.
Enter a number:37
Your answer is too small.
Enter a number:43
Your answer is too large.
Enter a number:40
Your answer is too small.
Enter a number:42
Your answer is too large.
Enter a number:41
BINGO!!