2017-01-13 60 views
0

我希望用戶爲程序提供輸入,以便如果用戶給出錯誤的輸入,代碼應該提示他們輸入正確的值。返回循環到特定的多個嘗試/除外子句

我試過這段代碼,但由於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() 
+0

放了,而周圍的每個'try'語句來代替?另外'break'只適用於最後一次嘗試。 – Torxed

+0

[Loop直到輸入爲特定類型]的可能重複(http://stackoverflow.com/questions/19542883/loop-until-an-input-is-of-a-specific-type) –

回答

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 
+0

謝謝。它通過刪除ValueError工作。 – Dheeraj

+0

@Dheeraj爲什麼?你提供了哪些輸入,導致了其他類型的異常? – Tagc

+0

我給了一個字符串值。引發NameError異常。 Like- NameError:名稱'g'未定義。有沒有解決方案? – Dheeraj