用异常处理改编猜数游戏程序

用异常处理改编猜数游戏程序,功能是:允许用户反复输入数,直至猜中程序选定的数(假定为100)。输入的数如果大于选定的数,则提示"larger than expected";如果小于选定的数,则提示"less than expected";如果用户输入的不是整数,则提示"input error";如果等于选定的数,则输出"you have tried N times, you win"并结束程序。
【输入形式】

一次或多次输入整数
【输出形式】

对于每一次输入,新起一行输出对于猜数结果的提示。

【样例输入】

50

150

E

100

【样例输出】

less than expected

larger than expected

input error

you have tried 4 times, you win

【说明】

被猜的数设定为100。

a=100

b=1
count = 0
while True:

    try:
        count += 1
        d=int(input())

    except ValueError:
        print("input error")
    else:

        if a==d:
            print("you have tried %d times, you win"%(count))
            break
        elif a<d:
            print("larger than expected")
        else:
            print("less than expected")
        b+=1

a=100

b=1
count = 0
while True:

    try:
        #count += 1
        d=int(input())
        count +=1#错误写法
    except ValueError:
        print("input error")
    else:

        if a==d:
            print("you have tried %d times, you win"%(count))
            break
        elif a<d:
            print("larger than expected")
        else:
            print("less than expected")
        b+=1

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值