11. The Man Behind the Bit Mask


#1



https://www.codecademy.com/courses/python-intermediate-en-KE1UJ/2/1?curriculum_id=4f89dab3d788890003000096#


Why does the mask variable have to be outside the function? If i try that same code but define mask inside the function it doesn't work, spitting out errors such as 0b0 returning "on".

The last line was just a check for myself.


mask = 0b1000

def check_bit4(input):
    inpt = input
    desired = inpt & mask
    if desired > 0:
        return "on"
    else:
        return "off"
print check_bit4(0b0100)


#2

You can put mask = 0b1000 in the function. It just has to be before the variable call which is desired = inpt & mask. You can have it as:

def check_bit4(input):
    mask = 0b1000
    inpt = input
    desired = inpt & mask
    if desired > 0:
        return "on"
    else:
        return "off"
print check_bit4(0b0100)

or

def check_bit4(input):
    inpt = input
    mask = 0b1000
    desired = inpt & mask
    if desired > 0:
        return "on"
    else:
        return "off"
print check_bit4(0b0100)

Perhaps the error comes from a spelling/mistyping error.


#3

Hmm perhaps I was making some other error.

Anyway, good to know it can be in either spot.

Thanks!


#4

No problem! Have fun with the other lessons :slight_smile:


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.