【发布时间】:2017-03-04 06:17:45
【问题描述】:
这里是 Python 初学者。我正在编写一个使用无限循环并允许用户输入关键术语来访问不同“工具”或“模块”的程序。
在这些“模块”之一中,用户可以输入一个值并将其转换为二进制。我想:
- 允许程序识别值是 int 还是 浮动,然后运行将值转换为二进制的代码
- 允许程序识别输入的值是否为 str 并且 str 表示“返回”,此时将退出当前循环。
据我所知,这个问题正在发生,因为 input() 会自动将输入的内容转换为 str (由于:http://anh.cs.luc.edu/python/hands-on/3.1/handsonHtml/io.html“首先它会打印您作为参数提供的字符串”)。
如何让下面的代码识别输入是 str、float 还是 int,然后执行相关的 if 语句?目前,我的这部分代码可以接受“返回”以退出循环,但会将任何 int 或 float 值作为 str,使程序提示用户再次输入十进制值。
#decimal to binary
while search == "d2b":
dec2bin = input("\nDecimal Value: ")
if type(dec2bin) == int:
print("Binary Value: " + "{0:b}".format(dec2bin))
elif type (dec2bin) == str:
if dec2bin == "back":
search = 0
elif type (dec2bin) == float:
#code for float to binary goes here
编辑:与此线程 (Python: Analyzing input to see if its an integer, float, or string) 不同,因为在 input() 上使用了列表 E2:似乎无法使用建议的副本作为问题的解决方案。但是,Francisco 在此线程中的评论有解决方案
【问题讨论】:
-
标记为重复的问题不是真的。这就是如何在列表中找到对象的类型——而不是字符串可以转换成的类型。
标签: python python-3.x