2017-01-13 2 views
0

ユーザが誤った入力をした場合、コードに正しい値を入力するように指示するようにユーザにプログラムの入力を要求します。特定の複数のtry/except節へのループを返す

私はこのコードを試しましたが、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'は最後のtry catchにのみ適用されます。 – Torxed

+0

[入力が特定のタイプになるまでループする]の可能な複製(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

関連する問題