Python实现的猜数字小游戏练习

初学Python,用Python实现简单的猜数字游戏,具体如下:

"""
随机生成一个1-100之间的数字,让用户来猜,当猜错时,会提示猜的数字是大还是小了,直到用户猜对,游戏结束。
"""
#随机生成一个整数(1-100import random

answer=random.randint(1,100)
#玩家输入数字
num=int(input("Please input the num(1-100):"))

#游戏是否继续确认
quit = True

while quit:
    #进行对比
    while num!=answer:
        if num>answer:
            num=int(input("The number is more, please input another num :"))
        else:
            num=int(input("The number is less, please input another num :"))
    #答案正确,游戏结束
    print("The random randint is %d and you get it .\nYou win this game !" %num)

    #判定是否循环游戏
    to_continue = input("Whether to continue, if you don't want to continue, please type Q.")
    if to_continue.lower() == 'q':
        quit = False
        print('End!')
    else:
        num = int(input("Please input the num(1-100):"))
        answer = random.randint(1,100)

运行结果:
运行结果

如何实现自动给出确切的数字范围?

"""
	Date:2018/12/28
	Version:2.0
	功能:自动给出确切的数字范围
"""
#随机生成一个整数(1-100import random

answer = random.randint(1,100)
num_list = [1, 100]
#玩家输入数字
num = int(input("Please input the num(1-100):"))
#游戏是否继续确认
quit = True

while quit:
    #进行对比
    while num != answer:
        if num > answer:
            num_list[1] = num
            num = int(input("The number is more, please input another num({},{}):".format(num_list[0],num_list[1])))
        else:
            num_list[0] = num
            num = int(input("The number is less, please input another num({},{}):".format(num_list[0], num_list[1])))
    #答案正确,游戏结束
    print("The random randint is %d and you get it .\nYou win this game !" %num)

    #判定是否循环游戏
    to_continue = input("Whether to continue, if you don't want to continue, please type Q.")
    if to_continue.lower() == 'q':
        quit = False
        print('End!')
    else:
        num = int(input("Please input the num(1-100):"))
        answer = random.randint(1,100)
        num_list = [1,100]

运行结果:
运行结果2

菜鸟共勉。

  • 4
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值