The Man Behind the Bit Mask. TypeError: Anyone?


Traceback (most recent call last):
File "python", line 7, in
File "python", line 3, in check_bit4
TypeError: unsupported operand type(s) for &: 'str' and 'int'

I expected it to run fine.. @mtf @leonhard.wettengmx.n

def check_bit4(input):
    if bin(bin(input) & 0b1000):
        return 'on'
    return 'off'


You might try to use

def check_bit4(input):
    if input & 0b1000:
        return 'on'
    return 'off'
print check_bit4(input())


:cold_sweat: Yeah, it worked.. But how?
Logically my code is correct.. No?
How does your code compares to mine? Why does your code pass but my code gives error?



unsupported operand type(s) for &: 'str' and 'int'


Try to print your bin(bin(input))
and determine the type uisng


I just went through this example and wanted to shed some light on what you specifically got wrong

When you use bin(), you are creating a string with the integer's bit notation.

eg. bin(4) will generate "0b100"

when you are doing the & comparison, you need to be comparing two integers.

mask = 8
mask = 0b1000

These are both the exact same thing, where the 0b1000 is just another way of writing the number 8.

if 'bin(bin(input) & 0b1000):

in this section of the code, the "bin(input)" is turning the value of the "input" into a string of the bitwise value i.e. "0bx"

when you run the comparison of "bin(input) & 0b1000" you are now actually comparing a string with an integer.

Hope this clarifies the error.


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