mercredi 5 mars 2014

Identifying the data type of an input


Vote count:

0




Hi I am trying to print the data type of a user input and produce a table like following:



ABCDEFGH = String, 1.09 = float, 0 = int, true = bool



, etc. I'm using python 3.2.3 and I know I could use type() to get the type of the data but in python all user inputs are taken as strings and I don't know how to determine whether the input is a string or Boolean or integer or float. Here is that part of the code:



user_var = input("Please enter something: ")
print("you entered " + user_var)
print(type(user_var))


which always returns str for string. Appreciate any help



asked 2 mins ago


1 Answer



Vote count:

1




input() will always return a string. If you want to see if it is possible to be converted to an integer, you should do:



try:
int_user_var = int(user_var)
except ValueError:
pass # this is not an integer


answered 51 secs ago

Tom Leese

3,828




Aucun commentaire:

Enregistrer un commentaire