The user will input the chemical formula. For example CO2OHC5H18COO
, or something like that. Then, the output would be the molecular weight given that C = 12.01
, H = 1.008
, O = 16
. I have this so far:
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)
But I don't get why I can't use (i-1)
to get the previous element in the for loop so I can multiply it to the number. Is there any other way to get the previous element of the string? Or maybe is there a different way to approach this problem?