Python 3 if, else help?

I am going through a udemy course for python. There was a challenge question that I answered correctly (yay me). The instructor answered it a bit differently, meaning he didn't have redundant lines of code. When I put typed in his solution I had an error, of sorts.

It is a number guessing game.

There was originally for line 12 (under the print("Please guess higher") another guess = int(input()) but I removed it so my code would match the instructors. When I ran the program to test the outcome, well, you can see that instead of getting two guesses, I was only allowed 1 when I guessed under the answer number.

It took me a while to realize line 14's guess = int(input()) was supposed to be directly under the else instead of directly under line 12's else instead of line 13's print function. 

I removed a tab from line 14 (not seen in the photo. The photo shows line 14 tabbed over once too far), ran the program again, and that seemed to fix the problem. 

My question is, why did that allow me to have a second guess?


husoski, you are right about line 8. I don't know why I put it in there but after running it through the debugger it seems like the code isn't even run at all (or rather it is pointless code since if I guess the answer the first time there would be no need to guess again). Also, thank you so much! Your explanation really helped a lot :) Hope you get to see this update.

Attachment image

1 Answer

  • 1 month ago
    Favourite answer

    The reason to "unindent" line 14 is so that it is not part of the else: block above it.  It will run after the preceding if/else, no matter which part of that statement (the if block or the else block) actually ran. 

    In that way, the input() function call will get the next guess after a wrong guess, no matter whether the old guess was too high or too low.

    There's another issue with the code in the image.  Getting another guess on line 8 seems wrong, since line only runs when the user has already guessed correctly.

Still have questions? Get answers by asking now.