Question on PS2, Hangman. Why do I need a break on the line after "string = string[0:a] + string[a+1:len(string)]"?
"string = string[0:a]...." is towards the bottom of the code under the while loop. My code is in an attached link.
If I don't put a break in, the error message is:
IndexError: string index out of range
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga.
Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus.
Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
I place this line of code in before your if attempt == string[a]: ..... print 'a is', a ,'and attempt is', attempt, 'and string[a] is', string[a]
You will notice 2 odd things, the letter after the one you chose is skipped and the last one is blank. This is because you are removing a letter from the string in your code causing the string to get shorter than what it was when the for loop initiated and therefore the for loop is now going one past the end of the string where it is one shorter. The break allows you to break out of the for loop after you have found the right character, eliminating the problem and also giving the program less to do since it doesn't have to search the rest of the letters even though it already found it's answer.
Hope this helps.
That was a great way to illustrate my problem! Thanks @msmithhnova .
yep, it is a bad idea to modify a variable that you are using as a parameter of a for statement.
Not the answer you are looking for? Search for more explanations.
you may be able to rework your code using the 'in' operator