shoesoles
shoesoles

Reputation: 21

Numbers game in Python

I am getting started with Python, and I have tried to make a "number guessing game". You have 6 guesses between 1 and 100.

The program will tell you of you are way to high, way to lo or close.

My issue is with the end of the game. I can only get my system to deliver a single message.

So the same message appears if you win or loose the game. Please finde the entire below. I appreciate your help.

import random
guesses = 6
number = random.randint(0,100)
win = True

while guesses > 0:
    guess = int(input("guess: "))

    guesses -= 1

    if guess == number:
        win == True
        guesses = 0
    elif abs(guess - number) < 4:
        print("You are very close..", guesses, "guesses remaining")
    elif guess > number:
        print("Your guess is too high!", guesses, "guesses remaining")
    elif guess < number:
        print("Your guess is too low!", guesses, "guesses remaining")

if win == True:
    print("Sorry loser!")
else:
    print("Great. You won. Big deal.")

Upvotes: 0

Views: 369

Answers (1)

Olivier Melan&#231;on
Olivier Melan&#231;on

Reputation: 22324

You set win to True initially, it should be set ot False before the loop starts.

win = False # line 4

Although, you do not need a win flag at all. In Python, you can use while-else and for-else statements. The else being executed only if you did not break out of your loop, you can run the losing code there.

Is is more natural to use break to get out of a loop than to manually set the condition to a falsy state.

import random
number = random.randint(0, 100)

for guesses in range(6, 0, -1):
    guess = int(input("guess: "))

    if guess == number:
        print("Great. You won. Big deal.")
        break
    elif abs(guess - number) < 4:
        print("You are very close..", guesses - 1, "guesses remaining")
    elif guess > number:
        print("Your guess is too high!", guesses - 1, "guesses remaining")
    elif guess < number:
        print("Your guess is too low!", guesses - 1, "guesses remaining")
else:
    print("Sorry loser!")

Upvotes: 1

Related Questions