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

【问题描述】

用异常处理改写猜数游戏程序,功能是:允许用户反复输入数,直至猜中程序选定的数(假定为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
i = 0
while True:
    i += 1
    try:
        b = eval(input())
    except NameError:
        print('input error')
        continue
    if b > a:
        print("larger than expected")
    elif b < a:
        print("less than expected")
    else:
        print("you have tried {} times, you win".format(i))
        break

说明: try—except的部分的范围不好确定,因为抛出异常之后,抛出的这一部分就结束了,中间的语句都会跳过。加上会有多次判断,抛出异常之后还要继续猜数,所以try后面跟输入语句,只是对输入部分进行异常判断。

猜你喜欢

转载自blog.csdn.net/qq_51222650/article/details/123908933