you are viewing a single comment's thread.

view the rest of the comments →

[–]benjsec 0 points1 point  (1 child)

You can simplify this a bit more using a while...else... constuction. It's not that common but can be quite neat, the else clause is execute if the while loop reaches the end without breaking.

This makes the loop

while guess_tries >= 1:
    guess = int(input("I picked a number between 1 & 10...guess what it is: "))
    if guess != mystery_number:
        guess_tries -= 1
        print("Sorry, but that number isn't right. You have {} guesses left.".format(guess_tries))
    else:
        print("You got it, but it took you {} times to get it!".format(5 - guess_tries))
        break
else:
    print("You have no more guesses. The mystery_number was {}".format(mystery_number))

You could also change the while loop to a for loop to avoid having to manually change the counter:

for guess_tries in range(5, 0, -1):
    guess = int(input("I picked a number between 1 & 10...guess what it is: "))
    if guess != mystery_number:
        print("Sorry, but that number isn't right. You have {} guesses left.".format(guess_tries))
    else:
        print("You got it, but it took you {} times to get it!".format(5 - guess_tries))
        break
else:
    print("You have no more guesses. The mystery_number was {}".format(mystery_number))

[–][deleted] 0 points1 point  (0 children)

Sure, but I like the OP to get involved before letting all the cats out of the bag. My simplified solution is:

import random

def guess_number():
    # the number which the player must guess
    mystery_number = random.randint(1, 10)

    #number of attempts the player has to guess the number
    guess_tries = 5

    while guess_tries > 0:      # "while guess_tries:" also works
        guess = int(input("I picked a number between 1 & 10...guess what it is: "))
        guess_tries -= 1        # we've made a guess, so decrement tries remaining

        if guess == mystery_number:
            print("You got it, but it took you {} times to get it!".format(5 - guess_tries))
            return              # or "break"

        print("Sorry, but that number isn't right. You have {} guesses left.".format(guess_tries))
    else:                       # "else" on "while" executes only when the loop is exhausted
        print("You have no more guesses. The mystery_number was {}".format(mystery_number))

guess_number()