-2

I'm new to Yython programming. I create a simple program with random module, that ask for number, and person need to guess an number. I got problem with getting the answer. Even if I give the correct answer, program isn't stopping, here's the code:

import random

run = True
answer = random.randint(1,9)
guess = input("Give me an number in 1 to 9: ")
print(answer)

while run:
    if guess == answer:
        print("Congratulations, you won!\n" * 5)
        run = False
    else:
        guess = input("Try again: ")
        print(answer)

The print(answer) line is for me to know what is the answer, and even if I write it down, program isn't stopping.

ruohola
  • 21,987
  • 6
  • 62
  • 97
jzielins
  • 3
  • 2
  • 1
    change to `guess = int(input("Give me an number in 1 to 9: "))` – eyllanesc Nov 26 '19 at 18:26
  • If you search in your browser for "Python input tutorial", you'll find references that can explain this much better than we can manage here. You're comparing an integer to a string; those can never be equal. – Prune Nov 26 '19 at 18:26

2 Answers2

4

answer is always an integer:

answer = random.randint(1,9)

and guess is always a string:

guess = input("Give me an number in 1 to 9: ")

thus they can never be equal.

You need to conver the inputted string to an integer:

guess = int(input("Give me an number in 1 to 9: "))

Or better yet, convert the generated random number to a string, to avoid the issue of the program crashing when the user inputs a non digit:

answer = str(random.randint(1,9))
ruohola
  • 21,987
  • 6
  • 62
  • 97
1

The random function will return an integer and the input function will return a string in python, "1" is not equal to 1. To be able to check if the input is the same, convert the random number to a string by doing guess == str(answer) instead

Hippolippo
  • 803
  • 1
  • 5
  • 28