As mentioned in other answers, an int operation will fail if a string input is not converted to an int (e.g. float or characters). What you can do is use a small helper method to try and interpret the line for you:
def interpret_string(s): if not isinstance(s, basestring): return str(s) if s.isdigit(): return int(s) try: return float(s) except ValueError: return s
So, this will take a string and try to convert it to int, then float and otherwise return the string. This is a more general example of considering convertible types. It would be a mistake for your value to be returned from this function, which is still the string that you would like to tell the user and request a new input.
There may be an option that returns None if its neither float nor int:
def interpret_string(s): if not isinstance(s, basestring): return None if s.isdigit(): return int(s) try: return float(s) except ValueError: return None val=raw_input("> ") how_much=interpret_string(val) if how_much is None:
jdi
source share