程序无法读取整数值 [英] Program can't read integer values
问题描述
以下代码用于检查变量并输出(打印)一个值.尽管在变量类型( int
, float
或 str
).但是,它可以在Programiz.com上的DataCamp平台上完美运行.请问我哪里出错了.下面是代码:
The following code is to check variables and output(print) a value. The only output I get is One value is a string
when run on anaconda 3.6 despite the variable type (int
, float
or str
). However it runs perfectly on DataCamp platform on Programiz.com Please where did I go wrong. Below is the code:
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
.
This is because input()
is always read as a str
.
如果读取值 42
,则实际上是在读取类型为 str
的值"42"
.仅当将其强制转换为 int
或 float
等时,值才会更改类型.
If you read the value 42
, you are actually reading the value "42"
of type str
. Only if you cast it to an int
or float
etc. will the value change types.
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.
If you want to check that your string value contains an int before attempting to cast it, you might try i.isdigit()
which will return true if the string contains only digits.
这篇关于程序无法读取整数值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!