Python的type()函数及其"if"相关问题

Nic*_*son 2 python if-statement function python-2.7

所以我有以下代码:

user_input = raw_input("Enter an integer, string or float:")
input_type = type(user_input)

if input_type == "str":
    print "Your string was %s." % user_input

elif input_type == "int":
    input_type = int(input_type)
    print "Your integer was %d." % user_input

elif input_type == "float":
    input_type = int(input_value)
    print "Your float was %d." % user_input

else:
    print "You did not enter an acceptable input."
Run Code Online (Sandbox Code Playgroud)

不起作用 - 我相信因为if- 所以我把它改为:

if "str" in input_type
Run Code Online (Sandbox Code Playgroud)

"int"为浮点数和整数,但得到一个错误:

Traceback (most recent call last):
File "types.py", line 4, in <module>
if "str" in input_type:
TypeError: argument of type 'type' is not iterable
Run Code Online (Sandbox Code Playgroud)

为什么我会得到这个,我该如何解决?

aba*_*ert 14

这里有很多问题.


user_input = raw_input("Enter an integer, string or float:")
input_type = type(user_input)
Run Code Online (Sandbox Code Playgroud)

因为raw_input总是返回一个字符串,所以input_type总会在str这里.


if input_type == "str":
    print "Your string was %s." % user_input
Run Code Online (Sandbox Code Playgroud)

input_type将是str- 也就是说,表示字符串类型的实际对象 - 不是"str",它只是一个字符串.所以,这永远不会是真的,你的任何其他测试都不会.


将此更改为:

if "str" in input_type:
Run Code Online (Sandbox Code Playgroud)

...不可能有任何帮助,除非你期望input_type成为字符串的集合,或者"str"在某个地方的中间有一个更长的字符串.而且我无法想象你为什么会这么想.


这些线:

input_type = int(input_type)
Run Code Online (Sandbox Code Playgroud)

...正在尝试转换input_type-which,记住,是一个类型,str或者int,不是值 - 整数.那可能不是你想要的.


这些线:

print "Your integer was %d." % user_input
Run Code Online (Sandbox Code Playgroud)

是打印从用户收到的原始字符串,而不是您转换为的字符串int.如果您使用%s而不是%d,这将有效,但它可能不是您想要做的.


print "Your float was %d." % user_input
Run Code Online (Sandbox Code Playgroud)

即使您修复了上一个问题,也无法使用%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
Run Code Online (Sandbox Code Playgroud)