user3246349 user3246349 - 1 year ago 223
Python Question

Python3 except ValueError: if/else

I want to make a try/except to ensure that the inputted value is a float variable. However i want to make an exception if the inputted value is 'g' then i want to redefine the variable to '9.8' instead of telling me that it must be a number. Below is my try but there seems to be a problem with it.
PS ignore my mistake of printing "must be an integer"

enter image description here

Answer Source

Your example won't work because if ValueError actually occured, the variable a doesn't exist. Python interpreter tried to create variable a but it could not be done so it raised an error. Therefore you cannot use a inside the except block.

You should first save input("A:") to a variable and test if it's value is "g". If it is, you set it to "9.8". Next step would be to transform this variable to a float.

All this should be done inside the try block.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download