Wednesday, February 8, 2012

type() and input()

Playing around with type(), a handy function that shows the type of data stored, and input():

using python's type() to see what sort of data is in a variable. input()'s behavior is different to that of the interpreter, data is always a string where the interpreter can figure out the data type.

The interpreter teaches the concept that data types will be recognised at input. When using the input() function, however, all data is treated as a string. This is documented, but it's not apparently consistent to new users.

The fix is simple, but this also assumes the input data can be converted.

I'm new to this, there may be some other function that accepts and validates only numeric input data.


  1. its only on python3 tha input does conversation magic

    what is input in python3 was raw_input in python2 did

    the old input is gone, since it only did eval(raw_input()), which is usually a worse idea than trying to convert to the right type

    there are various other types for dealing with numbers that are not integers

    1. Thanks!

      As I learn more about Python (Python 3, in particular), I see that considerable thought has gone into the way things work, so I pretty well accept it as it is.

      The main disconnect is between the way things are learned in the interactive shell (where numbers are recognised) and doing something similar with input() that returns a string even on numeric input.

      It hung up a few of my students in class yesterday, but it was also an opportunity to teach about what a function returns.