首页 > 解决方案 > 使用python检测输入数据的数据类型时,如何使用嵌套的if-else进行这项工作

问题描述

我想知道在使用 if else 语句并检测输入的数据是哪种数据类型时如何使 python 程序工作。

这是我根据我的知识输入的代码(对不起,我是新手):

FullName = input("Enter your Full Name: ")
data = input("Enter a data: ")
if type(eval(data)) == float and int:
    if type(eval(data)) == float:
        print("Hello,", FullName + ". Your inputted data", data, "is a type of Float!")
    else:
        print("Hello,", FullName + ". Your inputted data", data, "is a type of Integer!")
else:
    print("Hello,", FullName + ". Your inputted data", data, "is a type of String!")

如果您能纠正我的工作,请随意,我将不胜感激。谢谢!

标签: python-3.xtypesnested-if

解决方案


  1. 你可能float or int不是说float and int
  2. 你不能使用和/或那样你需要说type(eval(data)) == float or type(eval(data)) == int否则你会得到奇怪的行为,因为 or 运算符将something == something(这是一个布尔值)与另一个不是布尔值的类型进行比较。
  3. 如果您使用 elif ( if int ... elif float ... else ),则此处不需要嵌套 if 语句

推荐阅读