python-3.x - 使用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!")
如果您能纠正我的工作,请随意,我将不胜感激。谢谢!
解决方案
- 你可能
float or int
不是说float and int
- 你不能使用和/或那样你需要说
type(eval(data)) == float or type(eval(data)) == int
否则你会得到奇怪的行为,因为 or 运算符将something == something
(这是一个布尔值)与另一个不是布尔值的类型进行比较。 - 如果您使用 elif ( if int ... elif float ... else ),则此处不需要嵌套 if 语句
推荐阅读
- amazon-web-services - Terraform 不支持括号中的 shell 变量?
- google-cloud-platform - GCP API 请求而不使用它们
- python - 如何根据用户选择调用 CallbackQueryHandler 中的函数?
- c# - 列表中最长的序列(包括重叠)?
- php - 数组插入数据库从“0”开始
- html - Horizontal alignments getting messed when trying to add bootstrap cards horizontally
- reactjs - 尝试在 Reactjs 中过滤列表中的字符串
- html - 如何防止表格单元格边框“渗入”彼此
- pine-script - Pine Editor 不执行 strategy.close 命令,即使它应该执行
- reactjs - 状态未在 componentWillMount 中更新