8/19: Question regarding the logic used?


#1

Hello Everyone!

The correct code to complete the exercise is:

from random import randint

# Generates a number from 1 through 10 inclusive
random_number = randint(1, 10)

guesses_left = 3
# Start your game!
while guesses_left > 0:
  guess = int(raw_input("Your guess: "))
  if guess == random_number:
    print "You win!"
    break
  guesses_left -= 1
else:
  print "You lose."

 

Now I’m a little thrown off by the logic. If you’re going to break the while loop after a correct answer anyway, then why do you decrement the ‘guesses_left’ variable afterwards? As a noobie, I’m looking at it like like this; there’s no need to keep count after guessing correctly since the loops will break anyway.

Why wouldn’t it make more sense to decrement after an incorrect guess, like so:

from random import randint

random_number = randint(1, 10)

guesses_left = 3

while guesses_left > 0:
    guess = int(raw_input("Your guess: "))
    if guess == random_number:
        print "You win!"
        break
    else:
        print "Sorry, guess again!"
        guesses_left -= 1

#2

well, if the user guesses incorrectly, we need to decrease the guesses_left. If the user guesses correctly, the loop will break immediately, so any code in the loop after the break keyword doesn’t get executed. So we are decreasing the loop only after an incorrect guess.

sure, you can also use else, but you don’t have to.

but in either case, you should keep your while/else to inform the user when they lost (when they run out of guesses without guessing correctly)


#3

Yes! But my question is why would you put that in the block of code that responds to a correct guess? Instead of decrementing in the ‘else’ statement?


#4

you don’t, look:

  if guess == random_number: # correct guess
    print "You win!"
    break
  guesses_left -= 1

look at the indent of guesses_left, its placed outside the if clause which handles correct guess by user.


#5

Ahhh and that’s why I’m the student lol I completely missed that indentation! It makes a lot more sense now, thank you!!


#6

if guesses_left reduction would be placed inside the if clause, the user could guess endless (well, until right number is guessed)


#7

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.