Error calling function

Asked

Viewed 81 times

0

When I call this function:

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

This error appears:

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

I searched, but I couldn’t find a solution to the error

  • The statement asks to verify the second least significant bit? What does 4 mean in the function name check_bit4?

  • Ask for the fourth bit, the wrong 1 position, I already switched

2 answers

1


Is trying to do a bitwise operation with inteiro and with a string? That makes no sense, agree?

I think what you want is something like:

def check_bit4(input):
  mask = 0b010

  desired = input & mask

  if desired > 0:
    return "on"
  else:
    return "off"

print(check_bit4(0b1))    # off
print(check_bit4(0b1111)) # on
print(check_bit4(0b1010)) # on
  • In the Codecademy exercise it says "Define a Function, check_bit4, with one argument, input, an integer", when testing they are passing an int

  • @lipesmile the int All right, the error is in using operation BITWISE & with a string, that’s string mask = "0b010", that is not string mask = 0b010, do you understand? ---> https://pt.wikipedia.org/wiki/Lógica_binary

  • Ata, got it, obg, worked here

0

By the way, a suggestion: make functions a little more generic. Example - a function that gives the bit value n of a number: (Python3)

def bit(n,input):
   n=n-1
   return (input & 2**n) // 2**n

bit(1,3)   # 1
bit(2,3)   # 1
bit(3,3)   # 0

Browser other questions tagged

You are not signed in. Login or sign up in order to post.