如何在输入非int类型时触发自定义错误提示?
问题解决:处理非整数输入的错误提示
修正后的代码
import os # 定义跨平台清屏命令 clear = 'cls' if os.name == 'nt' else 'clear' def rating_system(): rate = input("\nWould you like to rate your experience with MealMatcher? (y/n) ") if rate.lower() in ["yes", "y", "yeah"]: try: star = int(input("How would you rate our service on a scale of 1 to 10? ")) except ValueError: # 捕获非整数输入异常 os.system(clear) print("Answer not Recognised.") rating_system() return if 1 <= star <= 10: os.system(clear) confirmation = input(f"Thank you for your rating! | You gave our service {star} stars out of 10, is that correct? (y/n) ") if confirmation.lower() in ["yes", "y", "yeah"]: os.system(clear) close = input("Thank you for using MealMatcher! Would you like to close? (y/n)") if close.lower() in ["yes", "y", "yeah"]: os.system(clear) print("Closing Application... | Thank you for using MealMatcher" * 3) raise SystemExit elif close.lower() in ["no", "n", "nope"]: os.system(clear) print("Well you have to...") print("*kicks out*") print("\x1B[3m" + "User in your channel was banned from the server." + "\x1B[0m") raise SystemExit else: os.system(clear) print("Answer Invalid") rating_system() elif confirmation.lower() in ["no", "n", "nope"]: os.system(clear) print("Retrying Statement... \n") rating_system() else: os.system(clear) print("Answer Invalid") rating_system() else: os.system(clear) print("That is not a valid answer | Try again: \n") rating_system() elif rate.lower() in ["no", "n", "nope"]: os.system(clear) print("Closing Application | Thank you for your time. \n" * 3) raise SystemExit else: os.system(clear) print("Answer Invalid \n") rating_system()
关键修改说明
- 捕获非整数输入:用
try-except块包裹整数转换操作,当输入无法转为int时触发ValueError,直接输出目标错误提示并重新调用函数。 - 修复语法错误:原代码中
else块缩进混乱,调整后让条件分支逻辑清晰,避免语法报错。 - 优化范围判断:将
star in range(0,11)改为1 <= star <=10,贴合“1到10分”的业务需求(原逻辑包含0,不符合评分场景)。 - 提升输入兼容性:添加
.lower()让输入不区分大小写,减少用户输入失误。 - 补充清屏变量:原代码未定义
clear变量,补充跨平台的清屏命令,避免运行报错。
内容的提问来源于stack exchange,提问作者user19574555
相关产品推荐
相关产品推荐

