2013-05-22 113 views
0

用戶將輸入化學分子式。例如CO 2 OHC 5 H 18 COO。或類似的東西。然後輸出將被給予C = 12.01,H = 1.008,O = 16我有這樣的分子量那麼遠,如何計算python中的分子量

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循環中獲得前一個元素,這樣我就可以將它乘以數字。有沒有其他的方法來獲得字符串的前一個元素?或者有沒有不同的方法來解決這個問題?任何幫助將不勝感激。先謝謝了!

回答

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)