【问题标题】:Python 3.9 check if input is INT or FLOAT [duplicate]Python 3.9检查输入是INT还是FLOAT [重复]
【发布时间】:2020-11-11 03:52:24
【问题描述】:

我正在逐步学习 Python,使用 3.9 版本。

我想检查 input() 是 INT 还是 FLOAT,我有以下脚本,但无论我输入第一个 IF 总是运行。

i = input("Please enter a value: ")


if not isinstance(i, int) or not isinstance(i, float):
    print("THis is NOT an Integer or FLOAT")

elif isinstance(i, int) or isinstance(i, float):
    print("THis is an Integer or FLOAT")

谁能解释一下我做错了什么

【问题讨论】:

  • i 始终是字符串。
  • input() 总是返回一个字符串,它既不是整数也不是浮点数。即使它是 int 或 float,您也总是会进入第一个 if,因为如果 xy 为真,则 x or y 为真。
  • 所以有没有办法检查输入值是 INT 还是 FLOAT ? EG 像 TryConvert ??

标签: python python-3.x


【解决方案1】:

你可以用这样的东西来检查。如果引发值错误,则获取输入并将其转换为浮动,那么它不是float/int。然后使用floatis_integer()方法判断是int还是float

测试用例

-22.0 -> INT
22.1 -> FLOAT
ab -> STRING
-22 -> INT

代码:

i = input("Please enter a value: ")       
try:
    if float(i).is_integer():
        print("integer")
    else:
        print("float")
except ValueError:
    print("not integer or float")

【讨论】:

  • 你解释了为什么它在评论上不起作用所以添加了代码解释。
  • 请注意,检查没有正确地将整数值浮点文字与整数文字分开(即 Python 本身会做什么)。将float("1").is_integer()float("1.0").is_integer()type(1)type(1.0) 进行比较。
猜你喜欢
  • 2011-05-31
  • 2020-09-03
  • 1970-01-01
  • 2018-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-10-11
相关资源
最近更新 更多