The Man Behind the Bit Mask. TypeError: Anyone?


#1



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


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'
    
check_bit4(input())


#2

@oonyx,
You might try to use

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

#3

: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?


#4

@oonyx,
rtfs

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

From
https://docs.python.org/2/library/functions.html
read
https://docs.python.org/2/library/functions.html#bin

Try to print your bin(bin(input))
and determine the type uisng
https://docs.python.org/2/library/functions.html#type


#5

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.


#6

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