0

In Python 3.x, in an if condition, should I convert an int into a bool if I want to do something only when the int is zero, or is it just sufficient to use the int as-is?

# Option 1 - convert i to a bool in the if condition
def fun(i)
    if bool(i):
        # do something

# Option 2 - just use i in the if condition
def fun(i)
    if i:
        # do something

i = 0
fun(i)

i = int(some_mathematical_operation(i))
fun(i)
khelwood
  • 55,782
  • 14
  • 81
  • 108
Enterprise
  • 179
  • 7
  • 2
    There is no need to convert the int to a bool, 0 is considered false, and every other value is true. – riquefr Dec 07 '21 at 15:22
  • 4
    `if bool(i):` is equivalent to `if i:`. There is no need for an explicit conversion. – khelwood Dec 07 '21 at 15:22
  • 2
    Arguably, if you logically mean "if not zero", then you could use `if i != 0:` to be more explicit, but never use `if bool(i):` which is both needlessly slow and adds no information to the logical intent of the test over `if i:`. – ShadowRanger Dec 07 '21 at 15:25

0 Answers0