gpt4 book ai didi

python - 程序无法读取整数值

转载 作者:太空宇宙 更新时间:2023-11-03 14:33:36 24 4
gpt4 key购买 nike

下面的代码是检查变量并输出(打印)一个值。我得到的唯一输出是 One value is a string当在 anaconda 3.6 上运行时,尽管有变量类型( intfloatstr )。但是它在 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")

最佳答案

这是因为 input() 始终被读取为 str

如果您读取值42,您实际上读取的是str类型的值"42"。仅当您将其转换为 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。

关于python - 程序无法读取整数值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47113652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com