这里有很多问题。user_input = raw_input("Enter an integer, string or float:")
input_type = type(user_input)
因为raw_input总是返回一个字符串,所以input_type在这里总是str。if input_type == "str":
print "Your string was %s." % user_input
input_type将是str-也就是说,表示字符串类型的实际对象不是"str",它只是一个字符串。所以,这永远不会是真的,你的其他测试也不会是真的。
将此更改为:if "str" in input_type:
…可能帮不上什么忙,除非您希望input_type是字符串的集合,或者是中间有"str"的较长字符串。我也无法想象你为什么会这样期待。
这些行:input_type = int(input_type)
…正在尝试将input_type-记住,它是一个类型,类似于str或int,而不是将值转换为整数。那不可能是你想要的。
这些行:print "Your integer was %d." % user_input
正在打印从用户收到的原始字符串,而不是转换为int的内容。如果您使用%s而不是%d,这将起作用,但这可能不是您要做的。print "Your float was %d." % user_input
即使修复了前面的问题,也不能使用%d来打印浮动。
接下来,通过比较类型来测试几乎总是一个坏主意。
如果您真的需要这样做,那么最好使用isinstance(user_input, str)而不是type(user_input) == str。
但你不需要这么做。
事实上,总的来说“请求原谅比允许好”。找出某个东西是否可以转换为整数的正确方法是尝试将其转换为整数,如果不能,则处理异常:try:
int_value = int(user_input)
print "Your integer was %d." % int_value
except ValueError:
# it's not an int