cheslijones
cheslijones

Reputation: 9194

Why us Python code is evaluating to false when it is true?

So I have used the below code and it keeps evaluating to False, but it True. Being a Python 2.7 noob, I am not sure why.

s = 'Z_15'

if s.startswith('Z_') & int(s[2:]) >= 15:
    new_format = True
else:
    new_format = False

print new_format

Also this variation:

s = 'Z_15'
sYr = int(s[2:])

if s.startswith('Z_') & sYr >= 15:
    new_format = True
else:
    new_format = False

print new_format

I have evaluated both parts of the conjunction and they evaluate to True, so not sure what I am doing wrong.

Upvotes: 0

Views: 81

Answers (3)

mgilson
mgilson

Reputation: 309929

& is the bitwise operator and it has higher precedence than normal logical operators. So, your expression is being parsed as:

if (s.startswith('Z_') & int(s[2:])) >= 15:

Which (in this case) is:

if (True & 15) >= 15:

That simplifies to:

if 1 >= 15:

which is an obviously false condition.


To fix the problem, use the and operator which does a logical and and has the correct precedence.

Upvotes: 7

m0bi5
m0bi5

Reputation: 9452

You will get true as the answer when you use the logical and operator , not bitwise and operator

Modify your code to :

s = 'Z_15'

if s.startswith('Z_') and int(s[2:]) >= 15:
    new_format = True
else:
    new_format = False

print new_format

You can read this article for more information

Upvotes: 2

OneCricketeer
OneCricketeer

Reputation: 191743

Along with the other answers, you can do this

s = 'Z_15'
new_format = s.startswith('Z_') and int(s[2:]) >= 15
print new_format

Upvotes: 1

Related Questions