4

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?

  • 1
    i cannot speak for whether it is good practice or not, but syntax wise you can rely on the `and` conditional to short circuit. I personally have used it to check if a variable exists, and then apply a condition on it, in the same line. I think the rest of it may just be subjective. – Paritosh Singh Apr 21 '19 at 18:51
  • 4
    It is better practice to handle the exception, since your condition handles one case only. – Klaus D. Apr 21 '19 at 18:52
  • This is primarily opinion-based and therefore off-topic. Please read about what's on-topic in the [help/on-topic]. – ChrisGPT was on strike Apr 21 '19 at 19:05
  • 1
    It is simply that the short-circuiting `and` is not commutative. – Dan D. Apr 23 '19 at 03:59

3 Answers3

5

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.")
Daniel Butler
  • 3,239
  • 2
  • 24
  • 37
2

As has been answered try and except are the preferred methods in Python according to the EAFP principle.

Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.

Since I assume your question is simplified from what you are actually doing, I'm going to link this answer as well which talks about try: except: timing in comparison to checking value existence (or other if statements).

The author primarily concludes:

So, whereas an if statement always costs you, it's nearly free to set up a try/except block. But when an Exception actually occurs, the cost is much higher.

Moral:

It's perfectly OK (and "pythonic") to use try/except for flow control, but it makes sense most when Exceptions are actually exceptional.

In most cases, being clear and readable is best practice over anything else.

Community
  • 1
  • 1
MyNameIsCaleb
  • 4,409
  • 1
  • 13
  • 31
0

First of all It doesn't seems like global logic to me since you are checking a[1] in this case only you get it '.' but consider a scenario a = '11.1' then you will get a[1] as 1 which is not '.' and coming to your question in and operation it first check 1st condition if that is false then it will not check 2nd condition but if 1 become true then only it will check for 2nd condition in your case a[1] = '.' but it is not recommended if you don't have better exception handling code and if you want to check for float value then you can directly do try : float(a) except ValueError : # handle Value Error

Akash Kumar
  • 182
  • 2
  • 12
  • hi, I simplified the code as an example. In the original, the program would loop through every character in the the string. But yeah, I'll use the try and except instead. – CodeOfSanctity Apr 21 '19 at 19:14
  • yes you are right if you use try and except instead, it will reduce unnecessary loop complexity – Akash Kumar Apr 24 '19 at 05:17