如何为多个需用户输入的变量使用try/except块?代码问题求解
解决思路
核心是让每个输入逻辑独立成循环,直到获取合法值后再进入下一个输入,避免错误时直接跳到下一个输入流程。
问题分析
你现有代码的两处关键问题:
- 第一个
while True循环里,无论输入是否合法,最后都会执行break,导致循环仅运行一次,错误后直接进入下一个输入块 - 第二个
while True里的except ValueError直接raise异常,会终止程序,无法让用户重新输入
实现方案
把每个输入封装成单独的函数,函数内部用while循环持续请求输入,直到得到合法值后返回。这样能保证前一个变量获取成功后,才会执行下一个变量的输入逻辑。
示例代码
def get_valid_age(): while True: try: age = int(input("Enter your age: ")) if age <= 0: print("Enter a number greater than zero") continue return age except ValueError: print("Invalid age. Must be a number.") except Exception: print('Invalid input') def get_valid_height(): while True: try: height = float(input('Enter your height in inches: ')) if height <= 0: print("Enter a number greater than 0") continue return height except ValueError: print("Height must be a number.") def get_valid_weight(): while True: try: weight = float(input('Enter your weight in pounds: ')) if weight <= 0: print("Enter a number greater than 0") continue return weight except ValueError: print("Weight must be a number.") # 按顺序获取变量,前一个合法才会执行下一个 age = get_valid_age() height = get_valid_height() weight = get_valid_weight() # 后续程序逻辑示例 print(f"Age: {age}, Height: {height}, Weight: {weight}")
关键逻辑说明
- 每个函数内部通过
while True循环持续请求输入,只有当输入合法时才用return退出循环 - 输入不合法时,打印提示后继续循环,重新请求输入
- 主程序按顺序调用函数,只有前一个函数返回合法值后,才会执行下一个函数的调用,完美实现“满足前一条件再执行下一代码块”的需求
内容的提问来源于stack exchange,提问作者ak.
相关产品推荐
相关产品推荐

