如何定义内部嵌套while循环与try-except结构的Python输入校验函数
问题分析
原有代码的核心错误如下:
- 循环逻辑错误:
while ValueError直接用异常类作为循环判断条件,虽然恒为True可进入循环,但属于逻辑写法错误,应该通过是否获取到合法输入控制循环结束。 - 变量和内置函数使用错误:将Python内置的
input函数作为参数传递、尝试为input()调用结果赋值的写法均不符合语法规则,且校验函数没有返回合法输入值,无法给后续业务逻辑使用。 - 异常捕获逻辑不完整:except分支中直接调用
int(input())没有做二次异常捕获,只要第二次输入仍然非法就会直接抛出异常终止程序,无法实现循环校验效果。 - 业务逻辑变量赋值错误:原代码中
times_table = input是将函数本身赋值给变量,而非获取用户输入结果,后续传入range函数时会直接抛出类型错误。
修正后的实现方案
可复用输入校验函数
def trytrytryagain(prompt: str) -> int: while True: try: user_input = input(prompt) return int(user_input) except ValueError: print("You must enter a number")
修正后的完整乘法表代码
from time import sleep def trytrytryagain(prompt: str) -> int: while True: try: user_input = input(prompt) return int(user_input) except ValueError: print("You must enter a number") def validate_yes_no(prompt: str) -> str: while True: user_input = input(prompt).lower() if user_input in ("yes", "no"): return user_input print("You must enter either yes or no") # 主业务逻辑 times_table = trytrytryagain("Please input the times table you wish to complete (1, 2, 3, etc.): ") othertables = validate_yes_no("Would you like to go up to another times table (do the 1 to 12 times tables)? yes/no: ") if othertables == "yes": other_times_table = trytrytryagain("Enter which time table you want to go up to: ") max_value = trytrytryagain("Enter the maximum table you would like to go up to. (if you do the 3 to 5 times tables, what times table would you like to finish on - type 12 for 5 x 12, 13 for 5 x 13, etc.): ") for x2 in range(times_table, other_times_table + 1): for x in range(max_value + 1): print(f"{x} x {x2} =") input() sleep(0.1) else: print("Okay.") max_value = trytrytryagain("Enter the maximum table you would like to go up to. (if you do the 3 to 5 times tables, what times table would you like to finish on (type 12 for 5 x 12, etc.)): ") for x in range(times_table, max_value + 1): answer = x * times_table print(f"{x} times {times_table} is {answer}") sleep(0.1)
内容的提问来源于stack exchange,提问作者Zayn Merchant Dar
相关产品推荐
相关产品推荐

