返回循环到特定的多个try/except claus

2024-06-07 23:03:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望用户为一个程序提供输入,这样如果用户输入错误,代码就会提示他们输入正确的值。你知道吗

我尝试了这段代码,但由于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()

Tags: 代码用户boilerinputvalueoperatingfloatsteam
1条回答
网友
1楼 · 发布于 2024-06-07 23:03:25

这是你想要的吗?你知道吗

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

相关问题 更多 >

    热门问题