Conversion to int


#1



https://www.codecademy.com/courses/python-beginner-en-4XuFm/0/8?curriculum_id=4f89dab3d788890003000096#


Why do we need to convert the raw input to int?
Why do we need to write int(raw_input("Guess Row: ")) and not raw_input("Guess Row: ") ?


Replace this line with your code.


#2

raw_input returns Unicode which does not compute well in a number construct. Convert to int and you have a counting number that can be used as a list index.


#3

Could you explain the meaning of 'Unicode which does not compute well in a number construct' ?


#4

unicode_string = raw_input("Enter your input").decode('utf8')
Enter your input 55

 > type(unicode_string)
=> <type 'unicode'>
 > unicode_string
=> u'55'
 > as_int = int(unicode_string)
 > as_int
=> 55

However, that's not the whole picture. The value is mapped to a str type provided there are no characters out of ordinal range, which I believe caps out at around character code 127 for UTF-8. So inputing a number from the keyboard will fall in the correct range to be mapped to the string value.

Nonetheless, it is still not a number, and string types cannot be used as numbers.

Looking at the error messages confirms the above.

 > a =[]
 > b = raw_input("...")
... 0
 > a[b]
...
TypeError: list indices must be integers, not str

 > a[int(b)]
...
IndexError: list index out of range

 > a[int(b)] = b
...
IndexError: list assignment index out of range

 > a.append(b)
 > a
=> ['0']
 > a[int(b)]
=> '0'
 > a.append(int(b))
 > a
=> ['0', 0]