如何计算python中的分子量

时间:2013-05-22 08:53:52

标签: python-3.x

用户将输入化学式。例如CO2OHC5H18COO。或类似的东西。然后输出将是分子量,给定C = 12.01,H = 1.008,O = 16.我到目前为止有这个......

while(True):

    chemical_formula = input("Enter chemical formula, or enter to quit: ")

    length = len(chemical_formula)
    if chemical_formula == "":
        break
    else:
        char = list(chemical_formula)
        length = len(char)
        for i in char:
            if i == "C":
                c = 12.0107
            elif i == "H":
                h = 1.00794
            elif i == "O":
                o = 15.9994
            else:
                if char[i-1] == "C":
                    print(float(i)*c)
                elif char[i-1] == "H":
                    print(float(i)*h)
                elif char[i-1] == "O":
                    print(float(i)*o)

但我不明白为什么我不能使用(i-1)来获取for循环中的前一个元素,所以我可以将它乘以数字。有没有其他方法来获取字符串的前一个元素?或者可能有不同的方法来解决这个问题?任何帮助将不胜感激。先谢谢!

1 个答案:

答案 0 :(得分:0)

您必须迭代索引而不是元素,如下例所示:

chemical_formula = input("Enter chemical formula, or enter to quit: ")

length = len(chemical_formula)
if chemical_formula == "":
    break
else:
    char = list(chemical_formula)
    length = len(char)
    for i in range(length):
        if char[i] == "C":
            c = 12.0107
        elif char[i] == "H":
            h = 1.00794
        elif char[i] == "O":
            o = 15.9994
        else:
            if char[i-1] == "C":
                print(float(i)*c)
            elif char[i-1] == "H":
                print(float(i)*h)
            elif char[i-1] == "O":
                print(float(i)*o)