Search code examples
pythonpython-2.7raw-input

Python: Strange behaviour of raw_input


The code below provides an unexpected answer when I use raw_input. Can anyone explain me what is happening and how to solve it?

import numpy as np
response = raw_input("What is your move? ")
response=np.array(response)
changingPositions=np.flatnonzero(response)
print changingPositions

response=np.array([0,1,0])
changingPositions=np.flatnonzero(response)
print changingPositions

The execution is:

What is your move? [0,1,0]
[0]
[1]

The expected answer is

[1]

Solution

  • raw_input returns a string, in fact np.flatnonzero(np.array('adfsgh')) produces array([0]) too. So just make a list of ints:

    In [1]: import numpy as np
    
    In [2]: response = raw_input("What is your move? ")
    What is your move? 0,1,0
    
    In [3]: positions = np.array(map(int, response.split(',')))
    
    In [4]: changing_positions = np.flatnonzero(positions)
    
    In [5]: changing_positions
    Out[5]: array([1])