1

I create a function that compare with x and y variable. Inside the function has a lots of nested elif to compare the x and y then return integer. The problem is right now, when it runs at the certain elif statement, it didn't execute the statement although the statement is correct.

def convertTo(self, x, y):
    if( x == 0 & y == 0):
        return 0
    if( x == 0 & y == 1):
        return 1
    if( x == 0 & y == 2):
        return 2
    if( x == 0 & y == 3):
        return 3
    if( x == 1 & y == 0): 
        return 4 # Didn't return this line even though x = 1 and y = 0
    else
        return None

def main():
    self.convertTo(0,0)
    self.convertTo(0,1)
    self.convertTo(0,2)
    self.convertTo(0,3)
    self.convertTo(1,0) # return None? Why?
SudoBrew
  • 33
  • 4

3 Answers3

9

You're performing a chained equality comparison which is not doing what you think it does. The bitwise & is performed first as it has a higher priority than ==.

Replace:

x == 1 & y == 0
# 1 == 1 & 0 == 0
# 1 == 0 == 0  False!

With:

x == 1 and y == 0

See: Operator precedence

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

In Python, "&" and "and" do two different things. "and" is what you should be using, "&" is a binary operator.

if a = 0011 1100

and

b = 0000 1101

then

a&b = 0000 1100

See http://www.tutorialspoint.com/python/python_basic_operators.htm

Douglas
  • 1,304
  • 10
  • 26
0

You should use and instead of &, as & is a bitwise and.

Chaining multiple conditions in Python is generally done with an if-elif-else statement like below:

if a and b:
   # a and b both was true
elif a and not b:
   # a was true, but b wasn't
else:
   # none of the conditions matched

In your code, if it wasn't for the return statement in each if, and the fact that you are checking the same two variables, it would be possible for two if statements to evaluate to true.

if a:
   # this will run if a was true
if b:
   # regardless of a this will run if b was true
else:
   # regardless of a this will only run if b was false

Also, take a look at this: https://docs.python.org/3/tutorial/controlflow.html

Peter Szabo
  • 1,056
  • 2
  • 14
  • 30