用异常处理改写猜数游戏程序,功能是:允许用户反复输入数,直至猜中程序选定的数(假定为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
count=0
while True:try:count += 1num=int(input())except ValueError:print('input error')else:if num>a:print('larger than expected')if num <a:print('less than expected')if num==a:print('you have tried {:d} times, you win'.format(count))break
本文发布于:2024-02-04 08:20:04,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170702952153897.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |