Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading