Python try-except执行异常:转换结果与错误信息同时输出问题
你的代码有两个关键问题导致了转换结果和错误提示同时打印的现象:
- 所有分支里都调用了未定义的
usercontinue()函数,执行完转换逻辑后触发NameError,被外层的try-except捕获,所以转换结果和错误提示会同时输出。 - 选项3中存在变量名拼写错误:
GllnstoLtrs(InptGlls)里的InptGlls应该是InptGllns,否则选择选项3时会直接触发NameError进入except块。
另外,原代码的try块范围过大且使用裸except,会捕获所有异常,不利于精准处理错误和调试。
下面是修正后的代码:
def main(): print('What would you like to convert?') print('1. Miles to Kilometers') print('2. Fahrenheit to Celcius') print('3. Gallons to Liters') print('4. Pounds to Kilograms') print('5. Inches to Centimeters') try: option = int(input('Menu Option:')) if option not in range(1, 6): print('Invalid option, please choose between 1-5') return if option == 1: Inptmiles = float(input('Enter number of miles to convert:')) milestokm(Inptmiles) elif option == 2: InptFrnht = float(input('Enter degrees that you would like to convert:')) FrnhttoClcs(InptFrnht) elif option == 3: InptGllns = float(input('Enter number of Gallons you would like to convert:')) GllnstoLtrs(InptGllns) elif option == 4: InptLbs = float(input('Enter number of pounds you would like to convert:')) LbstoKgs(InptLbs) elif option == 5: InptInches = float(input('Enter number of Inches you would like to convert:')) InchestoCm(InptInches) except ValueError: print('Sorry, please enter a valid number for input') def milestokm(miles): convkm = miles * 1.6 print(f'{miles} Miles is equal to {convkm:.2f} Kilometers') def FrnhttoClcs(Fahrenheit): convClcs = (Fahrenheit - 32) * 5/9 print(f'{Fahrenheit} Degrees Fahrenheit is equal to {convClcs:.2f} Degrees Celcius') def GllnstoLtrs(Gallons): convLtrs = Gallons * 3.9 print(f'{Gallons} Gallons is equal to {convLtrs:.2f} Liters') def LbstoKgs(Pounds): convKgs = Pounds * 0.45 print(f'{Pounds} Pounds is equal to {convKgs:.2f} Kilograms') def InchestoCm(Inches): convCm = Inches * 2.54 print(f'{Inches} Inches is equal to {convCm:.2f} Centimeters') main()
修改说明:
- 移除了未定义的
usercontinue()调用,如果你需要实现继续转换的功能,可以添加如下函数并在每个分支末尾调用:
def usercontinue(): choice = input('Would you like to perform another conversion? (y/n): ').lower() if choice == 'y': main() else: print('Goodbye!')
- 修正了选项3中的变量名拼写错误,将
InptGlls改为InptGllns。 - 将多个
if改为elif,减少不必要的条件判断,提升代码效率。 - 添加了对1-5之外无效选项的处理,直接提示并返回。
- 把裸
except改为捕获特定的ValueError,只处理输入非数值的情况,其他错误会正常抛出,便于调试。
内容的提问来源于stack exchange,提问作者Chris William
相关产品推荐
相关产品推荐

