Computer always says I'm wrong - random.randint question

Viewed 64

I'm trying to make a random Guess the Number game with a simple points system. The thing is I'm going through the code again and again and I don't see what the problem is. The thing is the computer always says I'm wrong, I never win and I even tried using random.randint(1,2) but nothing. I usually have bad luck but I'm pretty sure it's the code not working.

import random

print("Guess the number from 1 to 10")

while True:
    number = random.randint(1, 2)
    number = int(number)
    guess = input("Enter number: ")
    points = 0
    if number == guess:
        print("You guessed right!")
        points += 1
    else:
        print("Sorry, wrong guess")

print("You have: " + str(points) + " points.")

print("Wanna try again? ")
tryagain = input("Y or N: ")
if tryagain == "Y" or "y":
    continue
else:
    break
2 Answers

It is because your "guess" variable is still recognized as a string and will not be recognized as equal to your integer "number" variable.

Change your if number == guess: to if number == int(guess):

After you change that it should work just fine!

As others have mentioned, you forgot to change the guess to an int. You also made it so that the points reset to zero every round; the points=0 statement should occur outside of the loop.

Here's a working version of your script:

import random 

print("Guess the number from 1 to 10")
points = 0

while True:
    number = random.randint(1, 2)   # no need for "int"
#     print(number) # uncomment to cheat 
    guess = input("Enter number: ")
    if int(guess) == number:
        print("You guessed right!")
        points += 1
    else:
        print("Sorry, wrong guess")

    print("You have: " + str(points) + " points.")

    print("Wanna try again? ")
    tryagain = input("Y or N: ")
    if tryagain.upper() == "N": # you only do something *different* in the N case
        break

You can also shorten the code a bit further since you don't need to use the user input outside of the if statements.

import random


print("Guess the number from 1 to 10")
points = 0

while True:
    number = random.randint(1, 2)   # no need for "int"
#     print(number) # uncomment to cheat 
    if int(input("Enter number: ")) == number:
        print("You guessed right!")
        points += 1
    else:
        print("Sorry, wrong guess")

    print("You have: %s points."%points)

    print("Wanna try again? ") 
    if input("Y or N: ").upper() == "N": # you only do something *different* in the N case
        break
Related