You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何判断输入为整数、浮点数或字符串并输出对应类型

输入内容类型判断解决方案

你当前代码的问题在于:int()、float()传入不符合转换规则的内容时会直接抛出错误终止程序,不会返回非对应类型的结果供type()判断。

由于转换失败会直接报错,你可以用Python基础异常捕获逻辑处理分支(异常捕获属于基础控制流,不属于高阶函数,符合作业要求),修改后代码如下:

x = input("Enter a number: ")

try:
    int(x)
    print(x, "is an integer")
except ValueError:
    try:
        float(x)
        print(x, "is a float")
    except ValueError:
        print(x, "is a string")

验证效果

  • 输入10,输出:10 is an integer
  • 输入10.0,输出:10.0 is a float
  • 输入Ten,输出:Ten is a string

内容的提问来源于stack exchange,提问作者yungCalculator

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.22 03:45:04