A function like float('.') would normally result in a ValueError. However, if I place conditions properly, I can avoid the ValueError exception. Is this considered bad practice?
Example of checking for the decimal point first, then digit
a = '1.2'
if a[1] != '.':
if float(a[1]) != 0:
print('is a digit and non zero')
Example of using 'and' operator to do the same thing
a = '1.2'
if a[1] != '.' and float(a[1]) != 0:
print('is a digit and non zero')
Flipping the conditions of the 'and' operator results in an error
a = '1.2'
if float(a[1]) != 0 and a[1] != '.':
print('is a digit and non zero')
Technically the first and second example are the same, however flipping the second example's conditions would result in an error. So once again, is this bad practice and should I use it to save a line?
Bad practice from what I know of comes down to how many times someone else would ask themselves “what is going on here?” or is surprised by the results. You want to minimize how often that happens.
I’d suggest a try
and except
block catching the ValueError
because you know it’s a possible issue.
I think it would be best to do the following. I’m assuming you are taking user input.
number_entered = input("Enter number: ")
try:
x = float(number_entered)
except ValueError as e:
print(f"{x} is not a valid number. Pease enter a valid number.")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With