Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing second condition when first false

Tags:

python

I have a simple program

temp='abc12a'
ver = 1
print(temp[-1].isdigit())
if temp[-1].isdigit() & int(temp[-1])!=ver:
    print(temp[:-1]+t)

which gives the output

False
Traceback (most recent call last):
  File "python", line 3, in <module>
  ValueError: invalid literal for int() with base 10: 'a'

Why does the second condition even get checked when the first is false? Is there a way to only do the second if the first is true that is cleaner than two ifs?

like image 317
depperm Avatar asked Dec 01 '25 23:12

depperm


1 Answers

The & operator in Python checks as a bitwise and. It does not short circuit. The and operator properly short circuits, which is the behavior you are looking for.

like image 99
Brien Avatar answered Dec 04 '25 12:12

Brien



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!