How to calculate molecular weight in python -


the user input chemical formula. example co2ohc5h18coo. or that. output molecular weight given c = 12.01, h = 1.008, o = 16. have far...

while(true):      chemical_formula = input("enter chemical formula, or enter quit: ")      length = len(chemical_formula)     if chemical_formula == "":         break     else:         char = list(chemical_formula)         length = len(char)         in char:             if == "c":                 c = 12.0107             elif == "h":                 h = 1.00794             elif == "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) 

but dont why cant use (i-1) previous element in loop can multiply number. there other way previous element of string? or maybe there different way approach problem? appreciated. in advanced!

you must iterate on index not on element, done example below:

chemical_formula = input("enter chemical formula, or enter quit: ")  length = len(chemical_formula) if chemical_formula == "":     break else:     char = list(chemical_formula)     length = len(char)     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) 

Comments

Popular posts from this blog

python - How to create a legend for 3D bar in matplotlib? -

java - Multi-Label Document Classification -

php - Dynamic url re-writing using htaccess -