Note that there are some explanatory texts on larger screens.

plurals
  1. POIndex Error: List Index out of range
    text
    copied!<p>This is my first time posting in stackoverflow, so I hope I'm doing everything right in terms of site etiquette. I am in a beginning programming class (Python), and my current assignment is to calculate the molecular weight of a compound of Carbon, Hydrogen, and Oxygen, given a user input. It can be anything from C2 to C8H19O2, and so on. </p> <p>I have my code and I keep getting an error I am unfamiliar with. Essentially what I am trying to do is have the code read the input compound character by character determining if it is a molecule or not. Then, it reads the character to the right of the previous character to determine if that is a number of another compound. If it is a different compound, then the previous single compound is added to a running tally of whichever molecule it was' total. if it is a number, then it will read the next character to the right to once again determine if it is a number or character. If it is a number, it multiplies the previous character number by 10 and then adds the next one, and so on, until it reaches the next character(C123H2 would be 10*1 + 2 followed by 10*12 + 3, and then it would add 123 Carbons to the running tally). Once our runny tallies are complete, then that number is multiplied by the molecular weight of one of each. I keep getting an index error that says my list index is out of range. Any help is greatly appreciated!</p> <p>def main():</p> <pre><code>C1 = 0 H1 = 0 O1 = 0 num = 0 chemicalFormula = (input("Enter the chemical formula, or enter key to quit: ")) while True: cformula = list(chemicalFormula) for index, x in enumerate(cformula): if x == 'C': if cformula[index + 1] == 'H' or cformula[index + 1] == 'O': C1 += 1 else: for index, y in enumerate(range(index + 1, 1000000000)): if cformula[index + 1] != 'H' or cformula[index + 1] != 'O': num = int(y) num = num*10 + int(cformula[index + 1]) else: C1 += num break elif x == 'H': if cformula[index + 1] == 'C' or cformula[index + 1] == 'O': H1 += 1 else: for y in range(index + 1, 1000000000): if cformula[index + 1] != 'C' or cformula[index + 1] != 'O': num = int(y) num = num*10 + cformula[index + 1] else: H1 += num break elif x == 'O': if cformula[index + 1] == 'C' or cformula[index + 1] == 'H': O1 += 1 else: for y in range(index + 1, 1000000000): if cformula[index + 1] != 'C' or cformula[index + 1] != 'H': num = int(y) num = num*10 + cformula[index + 1] else: O1 += num break else: break weightC = 15.994*C1 weightH = 1.0079*H1 weightO = 12.011*O1 sumWeight = weightC + weightH + weightO print("The molecular weight is ", sumWeight) </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload