User inputs a formula, for example: C12H2COOH
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.
I've tried using dictionaries, for loops and while loops. I've gotten to calculate compounds with single digits after the elements like C2H2
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!
Here is what I have so far. It's very messy.
xxx = ["H", "C", "O"]
elements = set(xxx)
while(True):chemical_formula = input("Enter chemical formula, or enter to quit: ")if chemical_formula == "":breakelse:characters = list(chemical_formula)n = 0print(characters)for i in characters:if characters[n] == "C":c = 12.0107if elements.intersection(set(characters[n+1])):print(c)else:number = int(characters[n+1])print(number*c)elif characters[n] == "H":h = 1.00794if elements.intersection(set(characters[n+1])):print(h)else:number = int(characters[n+1])print(number*h)elif characters[n] == "O":o = 15.9994if 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