Python的type()函数及其与“ if”相关的问题

所以我有以下代码:


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."

我认为这是行不通的if,因此我将其更改为:


if "str" in input_type

和"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

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


哔哔one
浏览 297回答 3
3回答

湖上湖

首先,“不起作用”是没有用的。将来请确切说明它不起作用,您的期望以及所获得的令人满意的结果。现在解决您的问题:raw_input将始终返回一个字符串。由您决定该字符串的内容是否符合看起来像整数或浮点数的内容,然后进行相应的转换。你知道如何转换;合格性测试通常是通过正则表达式完成的。

呼唤远方

虽然我不认为这是真正的重复,但是python中的isinstance()和type()之间的差异包含一个非常相关的答案,很容易阅读。您最终将希望编写一个try/except可以适当处理数据的。if isinstance(user_input, str): #or basestring, if you prefer, but Python 3 apparently doesn't use it&nbsp; &nbsp; useThisLikeAString(user_input)try:&nbsp; &nbsp; intInput = int(user_input)&nbsp; &nbsp; useThisLikeAnInt(user_input)except TypeError:&nbsp; &nbsp; useThisLikeSomethingElse(user_input)换句话说,被接受的答案是完全正确的,但是与该讨论的链接是值得的。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python