将输入转换为浮点数

问题描述 投票:0回答:1

我正在制作一个项目,该项目从元素中获取某些内容的输入,然后返回所有必要的信息。例如,碳可以用 C、12.011 或 6 来标识。 我正在制作的程序列出了其他详细信息。

目前我正在尝试将列表中的结果归档到它们自己的变量中。我可以让系统读取数字的输入,然后使用它将输入设置为 int。我如何用浮动来做到这一点?我尝试添加另一行代码,但它使用第三个 if 语句返回一个空列表。

代码如下:

from periodicTable import elements

givenInfo = input("please enter an the information you were given about the element, and I will enter the info for it:") #prompt for what they were provided


#makes an entry of 2 characters or less capitalized
if len(givenInfo) <= 2:
    givenInfo = givenInfo.capitalize()
if len(givenInfo) <= 3 and givenInfo.isdigit() == True:
    givenInfo = int(givenInfo)

#elif len(givenInfo) > 3 and givenInfo.isdigit() == True:
#    givenInfo = float(givenInfo)



#The proper designations for the data, for the start, it is all empty
name = ""
symbol = ""
atomNum = 0
atomMass = 0


#Loop to run through elements dictionry and make list of the values there
result = []
for element, element_dict in elements.items(): #for (new variable made in for loop), () in (dictionary elements, but .items() designates just the values)
    if (givenInfo in element_dict):
        result = list(element_dict)
        break
print(result)


#Loop to assign each value to its proper designation
i=0
while i < len(result):
    if type(result[i]) is int:
        atomNum = result[i]
        print("The atomic number is:", atomNum)
        i+=1
    elif type(result[i]) is float:
        atomMass = result[i]
        print("The atomic mass is:", atomMass)
        i+=1
    elif type(result[i]) is str and len(result[i]) > 2:
        name = result[i]
        print("The element name:", name)
        i+=1
    elif type(result[i]) is str and len(result[i]) <= 2:
        symbol = result[i]
        print("The symbol for the element:", symbol)
        i+=1
    else:
        print(type(result[i]))
        i+=1

这就是我的字典中元素的样子:

elements = {
    'hydrogen': {'hydrogen', 'H', 1, 1.0080}, 
    'helium': {'helium', 'He', 2, 4.0026},  
    'lithium': {'lithium', 'Li', 3, 7.0000}, 
    'beryllium': {'beryllium', 'Be',  4, 9.0121}, 
    'boron': {'boron', 'B', 5, 10.81}, 
    'carbon': {'carbon', 'C', 6, 12.011}, 
    'nitrogen': {'nitrogen', 'N', 7, 14.007}
}
list dictionary if-statement casting
1个回答
0
投票

由于您只是在寻找正整数或浮点数,因此您可以通过以下方式检查浮点数:

if givenInfo.isdigit():
    givenInfo = int(givenInfo)
elif givenInfo.find('.') > -1 and givenInfo.replace('.', '', 1).isdecimal():
    givenInfo = float(givenInfo)
else:
    givenInfo = givenInfo.capitalize()

要检查浮动,我们将替换第一个“.”用空字符串并检查它是否是数字。

© www.soinside.com 2019 - 2024. All rights reserved.