'How to calculate molecular weight in python
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?
Solution 1:[1]
You must iterate over index not over element, done as the example below:
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)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Netwave |
