0

I am new to python, sorry about a basic one.

The code works fine but it guesses same number twice or maybe more number of times. I want to guess an unique number every time.

import random

print("Hey human guess a number between 1 to 50 and i will try guessing what it is ! \n ")
input("Press enter when you have done the first step \n")
print("after my guess if its correct then hit y, if i need to guess higher than hit g and if i need to guess lower then hit l\n")

answer = ""
m = 1
n = 50

while(answer!='y'):

    guess = random.randint(m,n)
    print(guess)
    reply = input("Is my guess correct ?")

    if reply  ==  'y':
        print("GG")
        answer  = 'y'

    elif reply  ==  'l':
        n = guess
        print("\n Okay let me try again")

    elif reply  ==  'g':
        m = guess
        print("\n aaah let me try again please \n")

    else:
        print("\n Seriously man what did i tell you before ?")

Thank you in advance.

kouty
  • 320
  • 8
  • 17
Vineeth Sai
  • 3,389
  • 7
  • 23
  • 34

3 Answers3

1

As stated in the docstring of random.randint, this method "returns a random integer in range [a, b], including both end points". That means that when you assign the guess to either m or n the guess is going to be included for the range of the random.

Thus, to fix your code you could modify the following lines:

m = 0
n = 51

guess = random.randint(m+1,n-1)

In this way, you never include the guess in the range of the random. Hope this helps.

José Sánchez
  • 1,126
  • 2
  • 11
  • 20
0

Create a list of guessed numbers guessed_numbers = []

Then whenever save the guess guessed_numbers.append(guess)

And before setting guess, check that guess is not in guessed numbers.

So you wind up with:

n = 50
guessed_numbers = []

while (answer != 'y'):

    guess = random.randint(m, n)
    while (guess in guessed_numbers):
        guess = random.randint(m, n)
    guessed_numbers.append(guess)
    print(guess)
Anthony Manning-Franklin
  • 4,408
  • 1
  • 18
  • 23
-1

The problem is likely that random.randint produces a number between m and n inclusive. If the range is 1-50, and the program guesses 50, it sets the upper bound to 50 again, which means it could guess that number twice. It will be more likely to happen as the range narrows.

I think if you change the line

n=guess

to read

n=guess-1

and similarly add one for m when it guesses too low, you'll get the result you're looking for.

TPDMarchHare
  • 135
  • 1
  • 8