【问题描述】
用异常处理改写猜数游戏程序,功能是:允许用户反复输入数,直至猜中程序选定的数(假定为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。
【完整代码】
target = 100
cnt = 0
while True:
cnt += 1
try:
n = int(input()) #判断输入有效
if n > target:
print("larger than expected")
elif n < target:
print("less than expected")
else:
print(f"you have tried {cnt} times, you win")
break
except ValueError:
print("input error")
【代码讲解】
try语句捕获异常,int(str)只能够转化纯数字的字符串,像是1.0虽然也是整数,但也会抛出异常,不过这题不需要考虑这么多。