user3246349 user3246349 - 6 months ago 48
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


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.