程序无法读取整数值

时间:2017-11-04 17:43:21

标签: python string variables types int

以下代码用于检查变量并输出(打印)值。尽管变量类型为One value is a stringintfloat,但在anaconda 3.6上运行时,我获得的唯一输出是str。然而,它在Programiz.com上的DataCamp平台上运行完美。请问哪里出错了。以下是代码:

essa1 = input("please enter essa1")
essa2 = input("please enter essa2")
if type(essa1) == str and  type(essa2) != str:
    print("One value is a string")
elif type(essa1) == int and type(essa2) == int:
    if essa1 == essa2:
        print("the two variables are equal")
    elif essa1 < essa2:
        print("essa1 is bigger")
    else:
        print("essa1 is now smaller")
else:
    print("One value is a string")

1 个答案:

答案 0 :(得分:1)

这是因为input()始终被视为str

如果您阅读了值42,则实际上是在阅读"42"类型的值str。只有将其投放到intfloat等时,值才会更改类型。

i = input('enter an int') # type 42 and press enter
# i now contains the string value "42"
i = int(i) # cast value to type int
# i now contains the int value 42

如果要在尝试强制转换之前检查字符串值是否包含int,可以尝试i.isdigit()如果字符串只包含数字,则返回true。