-2

I have set the guess_limit to 6 and random.randint(0, 6), even if I guess 1,2,3,4,5,6, it will always return "Out of guesses!" So my question is does random.randint() is calling the function or there is no random number if the function is not called. Please help

import random


guess = ""
guess_limit = 6
guess_count = 0
out_of_guesses = False
hiden_number = random.randint(1, 6)


while guess != hiden_number and not (out_of_guesses):
    if guess_count < guess_limit:
        guess = input("Enter the number: ")
        guess_count += 1
    else:
        out_of_guesses = True

if out_of_guesses:
    print("Out of guesses!")
else:
    print("You Win")


Enter the number: 1
Enter the number: 2
Enter the number: 3
Enter the number: 4
Enter the number: 5
Enter the number: 6
Out of guesses!

"If the random.randint(1, 6) range is 1 to 6 how is it possible that I am missing to guess the random number"

2 Answers2

1

You were comparing a string(guess) with an integer(hiden_numer). I changed the type of guess to integer. This run:

guess = None
guess_limit = 6
guess_count = 0
out_of_guesses = False
hiden_number = random.randint(1, 6)


while guess != hiden_number and not (out_of_guesses):
    if guess_count < guess_limit:
        guess = int(input("Enter the number: "))
        guess_count += 1
    else:
        out_of_guesses = True

if out_of_guesses:
    print("Out of guesses!")
else:
    print("You Win")
Massifox
  • 4,369
  • 11
  • 31
0

As @user23457112 mentioned, strings and ints are not equal.

You compare them in your while loop statement:

while guess != hiden_number and not (out_of_guesses):

but you can fix them by simply casting guess to int, like so:

while int(guess) != hiden_number and not (out_of_guesses):

You may also need to modify your guess = "" line to be something like guess = "-1" so that the while loop doesn't break immediately.

As @Massifox does, it's better to convert the input string into an int on your input sign so that the while compares two ints. You can do that by changing your input line, to 'cast' it into an 'int', like so:

guess = int(input("Enter the number: "))

and make sure your guess line is initialized as 0, so Python knows it is an int:

guess = 0

Your final code should look like this:

import random


guess = 0
guess_limit = 6
guess_count = 0
out_of_guesses = False
hiden_number = random.randint(1, 6)


while guess != hiden_number and not (out_of_guesses):
    if guess_count < guess_limit:
        guess = int(input("Enter the number: "))
        guess_count += 1
    else:
        out_of_guesses = True

if out_of_guesses:
    print("Out of guesses!")
else:
    print("You Win")
Enthus3d
  • 1,727
  • 12
  • 26