Jesh Kundem Jesh Kundem - 1 month ago 14
Python Question

Tricky Simple Python

Can any one please explain me why the if condition is working.

x = 0xA5

if x == 0xAA or 0x5A or 0xA0 or 0xAB:
print "Host Address is Correct"



0xAA or 0x5A or 0xA0 or 0xAB binary operation is not equal to 0xA5 either

Answer

Python isn't doing what you think it is - when you say

if x == 0xAA or 0x5A or 0xA0 or 0xAB:

it's checking if x==0xAA or 0x5a is "truthy" - wherein a non-empty string, for example, is considered True - and so on. The error you are getting suggests one of 0x5A, 0xA0, 0xAB is "truthy". What you would need to do is

if x == 0xAA or x == 0x5A or x == 0xA0 or x == 0xAB:

Which can be expressed more easily as

if x in [0xAA, 0x5A, 0xA0, 0xAB]:

Though it should be noted that if 0xAA etc are strings, they need to be written as '0xAA' etc.