Search code examples
pythonbit-shift

Python: How does one print bitshifted inputs as an integer?


I am trying to create a bitshifting tutorial script that takes a users input and prints the result, but it keeps returning the below error

DATASET NUMBER: 0
Traceback (most recent call last):
  File "./prog.py", line 21, in <module>
TypeError: unsupported operand type(s) for >>: 'str' and 'int'

Here is my code I am currenly using:

import sys

input = []
for line in sys.stdin:
    input.append(line)
a = input[0]
b = input[1]
c = input[2]

a >> 4
print(a)

b << 2
print(b)

c << 1
print(c) 

It is the printing part that is not working properly. I believe it is either a syntax error or an error with integer conversion, which I am not 100% confident in doing. Is my syntax wrong or am I missing something simple?


Solution

  • input = []
    for line in sys.stdin:
        input.append(line)
    

    So input contains variables of type str, right? You can't byteshift a string, you have to cast it to an integer first:

    input = list(map(int, input)) # This converts all the elements to integers
    

    I would suggest an ending underscore to prevent your program from overwriting the built-in function input.


    You should also be aware that you're not assigning the shifted value back to the variable, so you are printing the same value found in the input.

    a = a >> 4 # Do this...
    a >>= 4 # ...maybe this...
    a >> 4 # ...but for sure not this