将循环返回到特定的多个try / except子句

时间:2017-01-13 09:45:39

标签: python exception-handling try-catch

我希望用户为程序提供输入,这样如果用户输入错误的代码,代码应该提示他们输入正确的值。

我尝试了这段代码,但由于continue语句,它从一开始就运行循环。我希望代码返回其各自的try块。请帮忙。

def boiler():
    while True:

        try:
            capacity =float(input("Capacity of Boiler:"))
        except:
            print ("Enter correct value!!")
            continue
        try:
            steam_temp =float(input("Operating Steam Temperature:"))
        except:
            print ("Enter correct value!!")
            continue
        try:
            steam_pre =float(input("Operating Steam Pressure:"))
        except:
            print ("Enter correct value!!")
            continue
        try:
            enthalpy =float(input("Enthalpy:"))
        except:
            print ("Enter correct value!!")
            continue
        else:
            break
boiler()

1 个答案:

答案 0 :(得分:1)

这样做你想要的吗?

def query_user_for_setting(query_message):
    while True:
        try:
            return float(input(query_message))
        except ValueError:
            print('Please enter a valid floating value')


def boiler():
    capacity = query_user_for_setting('Capacity of Boiler: ')
    steam_temp = query_user_for_setting('Operating Steam Temperature: ')
    steam_pre = query_user_for_setting('Operating Steam Pressure: ')
    enthalpy = query_user_for_setting('Enthalpy: ')

    print('Configured boiler with capacity {}, steam temp {}, steam pressure {} and enthalpy {}'.format(
        capacity, steam_temp, steam_pre, enthalpy))


if __name__ == '__main__':
    boiler()

运行示例

Capacity of Boiler: foo
Please enter a valid floating value
Capacity of Boiler: bar
Please enter a valid floating value
Capacity of Boiler: 100.25
Operating Steam Temperature: baz
Please enter a valid floating value
Operating Steam Temperature: 200
Operating Steam Pressure: 350.6
Enthalpy: foo
Please enter a valid floating value
Enthalpy: 25.5
Configured boiler with capacity 100.25, steam temp 200.0, steam pressure 350.6 and enthalpy 25.5