Hello! I am a newbe to python and apologize in advance for this question, because I am sure it is an easy fix that I am oblivious too -
I wrote this simple program for a guessing game- very basic, which is fine - but when you get to the end of the game, and guess the correct number, the number of tries is off by ONE - it is driving me mad! here is what the code consists of (runs fine aside from that flaw)

count = 0
secret = random.randint (1, 100)

print ("Guessing game - Guess my secret number - number between 1-100")
guess = int(input("Your Guess?"))
while (guess != secret):


    if (guess > secret):
        print ("Your guess is higher")
        guess = int(input("Guess again:"))

    elif (guess < secret):
        print ("Your guess is lower")
        guess = int(input("Guess again:"))

else:
    print ("You Guessed it!It took you", count, "tries.")

Recommended Answers

All 6 Replies

line 7 should have the indented
count = count + 1
not sure why it didn't show up

You want to increment count after every input. You do not increment it after the first input statement. Also the final else is not necessary.

import random

count = 0
secret = random.randint (1, 100)

print ("Guessing game - Guess my secret number - number between 1-100")
guess = int(input("Your Guess? "))
count +=1     ## <----------------- or count=1
while (guess != secret):
    count += 1

    if (guess > secret):
        print ("Your guess is higher")
        guess = int(input("Guess again:"))

    elif (guess < secret):
        print ("Your guess is lower")
        guess = int(input("Guess again:"))

print ("You Guessed it!It took you", count, "tries.")

Awesome! Thank you for your help!

When you have received answer, you mark thread solved.
You can of course also upvote and even add comment and give/take reputation if you have power to do so.

You may want to help the user in case of an invalid integer entry.

The line
guess = int(input("Your Guess? "))
in essence appears 3 times, see if you can use it just once.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.