title: How to get molecular weight of a compound in python?
body: <p>User inputs a formula, for example: <code>C12H2COOH</code></p>
  
  <p>We have to calculate its molecular weight given that C = 12.01, H = 1.008 and O = 16.
  We were told to be careful of elements with double digits after it and elements with no numbers after it. The program also keeps asking for a chemical formula and exits when you press enter.</p>
  
  <p>I've tried using dictionaries, for loops and while loops. I've gotten to calculate compounds with single digits after the elements like <code>C2H2</code> but if I put double digits or put no numbers next to the element, it fails. I was also looking at how to separate strings without deleting delimiters as a possible route? How would you guys approach this problem? Any help would be appreciated, thank you!</p>
  
  <p>Here is what I have so far. It's very messy.</p>
  
  <pre><code>xxx = ["H", "C", "O"]
  elements = set(xxx)
  while(True):
      chemical_formula = input("Enter chemical formula, or enter to quit: ")
      if chemical_formula == "":
          break
      else:
          characters = list(chemical_formula)
          n = 0
          print(characters)
          for i in characters:
              if characters[n] == "C":
                  c = 12.0107
                  if elements.intersection(set(characters[n+1])):
                      print(c)
                  else:
                      number = int(characters[n+1])
                      print(number*c)
  
              elif characters[n] == "H":
                  h = 1.00794
                  if elements.intersection(set(characters[n+1])):
                      print(h)
                  else:
                      number = int(characters[n+1])
                      print(number*h)
  
              elif characters[n] == "O":
                  o = 15.9994
                  if elements.intersection(set(characters[n+1])):
                      print(c)
                  else:
                      number = int(characters[n+1])
                      print(number*o) 
              else:
                  numero = int(i)
                  print(i*0)
  
              n = n+1
  </code></pre>