Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good practice to use 'and' when the second condition would normally result in an error if evaluated first

Tags:

python

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?

like image 648
CodeOfSanctity Avatar asked Mar 05 '23 02:03

CodeOfSanctity


1 Answers

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.")
like image 63
Daniel Butler Avatar answered Apr 27 '23 04:04

Daniel Butler