如何使用if for python3

Pen*_*ter -1 python python-3.4

我最近切换到Python 3,并且通常与Python 2一起使用的常规内容不适用于Python 3.我已经能够修复其余的但我正在努力解决这个问题.我无法检查什么是"类型"的东西.

raw = input("Please give me a number, string\
 or decimal: ")
if type(raw) == int:
    print("You entered a number")
elif type(raw) == float:
    print("You entered a decimal")
elif type(raw) == str:
    print("You entered a string")
else:
    print("error please try again")
Run Code Online (Sandbox Code Playgroud)

`

mgi*_*son 5

在python3.x中,input始终返回一个类型的对象str.相当于python2.x eval(input('...')).与eval在任何时候使用一样,请确保您完全相信输入不会对您的程序或计算机执行恶意操作...

一个更好的办法是使用类似ast.literal_eval(这将安全地评估你的文字),或者做检查自己...

def is_int_str(s):
    """Checks if a string (s) represents a python integer."""
    try:
        int(s)
    except ValueError:
        return False
    return True
Run Code Online (Sandbox Code Playgroud)

然后编写类似的float版本是微不足道的......