python-猜数字游戏

猜数字游戏
if , while(for), break
1. 系统随机生成一个1~100的数字;
** 如何随机生成整型数, 导入模块random, 执行random.randint(1,100);
2. 用户总共有5次猜数字的机会;
3. 如果用户猜测的数字大于系统给出的数字,打印“too big”;
4. 如果用户猜测的数字小于系统给出的数字,打印"too small";
5. 如果用户猜测的数字等于系统给出的数字,打印"恭喜中奖100万",并且退出循环;

while:

import random						#导入random模块
x = random.randint(1,100)				#电脑随机出一个1-100的整数
print(x)

trycount = 0
while trycount < 5:					#五次机会
    tk = int(input('请输入你猜测的数字:'))			#输入一个整数
    if tk == x:						#当电脑生成的数=猜的数字,中奖100万
        print('恭喜中奖100万')
        break						#退出循环
    elif tk < x:					#当猜的数字<电脑生成的数
        print('too small')
        trycount += 1					#机会减少一次
    else:
        print('too big')				#当猜的数字>电脑生成的数
        trycount += 1					#机会减少一次

else:
    print('机会已经用完了~')				#第五次猜错,退出循环

for:

trycount = 0
for trycount in range(5):
    tk = int(input('请输入你猜测的数字:'))
    if tk == x:
        print('恭喜中奖100万')
        break
    elif tk < x:
        print('too small')
    else:
        print('too big')
else:
    print('机会已经用完了~')

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_43067754/article/details/84316091