0

I want the user to provide input for a program such that if the user gives the wrong input the code should prompt them to enter a correct value.

I tried this code but because of the continue statements it runs the loop from the very start. I want the code to return to its respective try block. Please help.

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()
Dheeraj
  • 1,102
  • 3
  • 14
  • 29
  • Put a while around each `try` statement instead? Also `break` only applies to the very last try catch. – Torxed Jan 13 '17 at 09:48

1 Answers1

1

Does this do what you want?

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()

Example Run

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
Tagc
  • 8,736
  • 7
  • 61
  • 114
  • @Dheeraj Why? What inputs were you providing that resulted in other types of exceptions? – Tagc Jan 13 '17 at 10:21
  • I gave a string value. NameError exception raised. Like- NameError: name 'g' is not defined. Is there any solution for that? – Dheeraj Jan 13 '17 at 10:26
  • @Dheeraj Yes there is - use Python 3 ;) (alternatively, replace `input` with `raw_input`) – Tagc Jan 13 '17 at 10:27