Python'除了'条款不起作用

时间:2016-09-08 08:56:30

标签: python nameerror except

Hello Stack Overflow社区。

我目前正在尝试学习如何使用Python(3.5)进行编程,而且我的转换程序存在问题。总而言之,似乎Python忽略了源代码中的except子句。

try:
    print("Welcome to CONVERSION. Choose an option.")
    print("1. Convert CELSIUS to FAHRENHEIT.")
    print("2. Convert FAHRENHEIT to CELSIUS.")
    Option = int(input("OPTION: "))
except NameError:
    print(Option, " is not a valid input.")
except ValueError:
    print(Option, " is not a valid input.")
except KeyboardInterrupt:
    print("Don't do that!")
else:
    if (Option != 1) or (Option != 2):
        print("Please input a valid option!")
    elif (Option == 1):
        try:
            Celsius = float(input("Enter value in Celsius: "))
        except ValueError:
            print(Celsius, " is not a valid input.")
        except KeyboardInterrupt:
            print("Don't do that!")
        else:
            Fahrenheit = Celsius * 1.8 + 32
        print(Celsius, "C = ", Fahrenheit, "F.")
    elif (Option == 2):
        try:
            Fahrenheit = float(input("Enter value in Fahrenheit: "))
        except ValueError:
            print(Celsius, " is not a valid input.")
        except KeyboardInterrupt:
            print("Don't do that!")
            Celsius = (Fahrenheit - 32) * ( 5 / 9 )
            print(Fahrenheit, "F = ", Celsius, "C.")
        else:
            print("That value is invalid. Try again.")

完整的追溯,当输入值" wad"在第一个屏幕中:

Traceback (most recent call last):
File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 7, in <module>
Option = int(input("OPTION: "))
ValueError: invalid literal for int() with base 10: 'wad'

 During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\user\Documents\Visual Studio 2015\Projects\TempConversion\TempConversion\TempConversion.py", line 11, in <module>
print(Option, " is not a valid input.")
NameError: name 'Option' is not defined

3 个答案:

答案 0 :(得分:4)

捕获异常后抛出异常。这基本上将它置于try catch场景之外。

如果您在Option = None之前添加try,则代码应该正确执行。

原因是int(input(...))在定义Option之前引发异常。因此,处理初始异常的代码会引发新的异常。

您还需要更改异常处理中的print语句,以正确处理来自None的潜在Options值。你可以用类似的东西来实现这一点。

Option = None
try:
    Option = int(input("OPTION: "))
except (NameError, ValueError):
    if Option:
        print(Option, " is not a valid input.")
    else:
        print("No valid input.")
except KeyboardInterrupt:
     print("Don't do that!")
else:
   .....

这也适用于您对Celsius和Fahrenheit的类似代码。

[编辑]现在不确定您有什么问题,理想情况下您应该创建一个新问题,因为您的新问题超出了原始问题的范围,但我根据您的代码准备了一个快速,结构稍微有点的示例

import sys


def get_input(text, convert_to='int'):
    result = None
    try:
        if convert_to == 'int':
            result = int(input(text))
        else:
            result = float(input(text))
    except (NameError, ValueError):
        if result:
            print(result, " is not a valid input.")
        else:
            print("No valid input.")
        sys.exit(1)

    return result


def handle_celsius_to_fahrenheit():
    celsius = get_input('Enter value in Celsius: ', convert_to='float')
    fahrenheit = celsius * 1.8 + 32
    print("C = %s, F %s." % (celsius, fahrenheit))


def handle_fahrenheit_to_celsius():
    fahrenheit = get_input('Enter value in Fahrenheit: ', convert_to='float')
    celsius = (fahrenheit - 32) * (5 / 9)
    print('F = %s , C %s.' % (fahrenheit, celsius))


def get_option():
    option = get_input('OPTION: ')
    if option == 1:
        handle_celsius_to_fahrenheit()
    elif option == 2:
        handle_fahrenheit_to_celsius()
    else:
        print("Please input a valid option!")
        sys.exit(1)

if __name__ == '__main__':
    print("Welcome to CONVERSION. Choose an option.")
    print("1. Convert CELSIUS to FAHRENHEIT.")
    print("2. Convert FAHRENHEIT to CELSIUS.")
    get_option()

答案 1 :(得分:2)

您尝试在字符串中使用变量Option但错误,但该变量不存在,因为它是错误的原因。尝试在Option = input()之前发起try并将其转换为try中的int

答案 2 :(得分:0)

它可以正常工作。当您处理ValueError例外时,您会尝试阅读尚未设置的Option。这导致另一个例外。你不会再抓到了。

相关问题