Python计算器遇ValueError时,如何仅重输第二个变量而非重启程序
问题:让计算器程序仅重新输入错误的第二个变量
刚接触编程,刚学会用try和except处理ValueError。写了个计算器程序,但当第二个输入不是整数时,整个程序会重启,得重新输入第一个变量。想改成只要求重新输入第二个变量,不用重新输第一个,该怎么改?
原代码:
while True: try: first = int(input("First: ")) second = int(input("Second: ")) sum = first + second print(f"Sum: {sum}") break except ValueError: print("I didn't understand that")
尝试的修改(无效):
while True: try: first = int(input("First: ")) second = int(input("Second: ")) sum = first + second print(f"Sum: {sum}") break except ValueError: print("I didn't understand that") int(input("Second: "))
解决方案
你原来的代码把两个输入逻辑包在同一个try块里,只要其中一个输入出错,就会触发except并重启整个循环,导致第一个变量也得重新输入。后来的修改里,except块里的int(input("Second: "))没有把输入值赋值给second,而且循环还是会回到开头重新执行,所以没用。
正确的思路是把两个变量的输入逻辑分开处理:先确保第一个变量输入正确,再单独循环处理第二个变量的输入,直到其正确为止。
代码示例1:分步循环处理
# 先获取第一个有效整数,输入正确才退出循环 while True: try: first = int(input("First: ")) break except ValueError: print("请输入有效的整数!") # 再单独获取第二个有效整数,错误时仅重输第二个 while True: try: second = int(input("Second: ")) break except ValueError: print("请输入有效的整数!") # 计算并输出结果 sum_result = first + second print(f"Sum: {sum_result}")
代码示例2:更紧凑的写法
first = None while first is None: try: first = int(input("First: ")) except ValueError: print("请输入有效的整数!") second = None while second is None: try: second = int(input("Second: ")) except ValueError: print("请输入有效的整数!") print(f"Sum: {first + second}")
两种写法都能实现:第一个变量输入正确后不再要求重输,只有第二个变量出错时,仅循环要求重新输入第二个值。
内容的提问来源于stack exchange,提问作者sebas assaf
相关产品推荐
相关产品推荐

