0

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?

1 Answer 1

0

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)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.