【问题标题】:Return loop to particular multiple try/except clause将循环返回到特定的多个 try/except 子句
【发布时间】:2017-01-13 09:45:39
【问题描述】:

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

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

【问题讨论】:

标签: python exception-handling try-catch


【解决方案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

【讨论】:

  • @Dheeraj 为什么?您提供的哪些输入会导致其他类型的异常?
  • 我给了一个字符串值。引发 NameError 异常。 Like- NameError: 名称 'g' 未定义。有什么解决办法吗?
  • @Dheeraj 是的 - 使用 Python 3 ;)(或者,将 input 替换为 raw_input
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-06
相关资源
最近更新 更多