Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 15 Online
OpenStudy (anonymous):

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 http://pastebin.com/5WWnfmzE

OpenStudy (anonymous):

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.

OpenStudy (anonymous):

That was a great way to illustrate my problem! Thanks @msmithhnova .

OpenStudy (anonymous):

yep, it is a bad idea to modify a variable that you are using as a parameter of a for statement.

OpenStudy (anonymous):

Yes, bwCA, that is how i coded mine, using 'in'.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!