0

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.")
2
  • Welcome to Stackoverflow! Please post your actual code, not a picture of it, and please review how to ask a questions: stackoverflow.com/help/how-to-ask Commented Sep 4, 2018 at 17:58
  • 1
    Thanks @GerryMcBride Will do! Commented Sep 4, 2018 at 18:06

1 Answer 1

1

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!")
Sign up to request clarification or add additional context in comments.

1 Comment

This is Amazing. Thank you so very much for the great and detailed feedback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.