ErikB26 ErikB26 - 14 days ago 6
Python Question

Random number being changed within Python script

I'm working on a Python script where a user has to guess a random number, selected by the script. This is my code:

import random
while True:
number = random.randint(1, 3)
print("Can you guess the right number?")
antwoord = input("Enter a number between 1 and 3: ")
if antwoord == number:
print ("Dang, that's the correct number!")
print (" ")
else:
print ("Not the same!")
print ("The correct answer is:")
print (number)

while True:
answer = input('Try again? (y/n): ')
print (" ")
if answer in ('y', 'n'):
break
print("You can only answer with y or n!")
if answer == 'y':
continue
else:
print("Better next time!")
break


It works... Sort of... I was trying it and came across this:
User enters 2, it says it's incorrect, but then displays the same number!

I have the feeling that, every time I call the variable 'number', it changes the random number again. How can I force the script to hold the random number picked at the beginning, and not keep changing it within the script?

Answer

As far as I understand it, you want to pick a new random integer in every loop step. I guess you are using python 3 and so input returns a string. Since you cannot perform comparisson between a string and an int, you need to convert the input string to an int first.

import random
while True:
    number = random.randint(1, 3)
    print("Can you guess the right number?")
    antwoord = input("Enter a number between 1 and 3: ")
    try:
        antwoord = int(antwoord)
    except:
        print ("You need to type in a number")
    if antwoord == number:
        print ("Dang, that's the correct number!")
        print (" ")
    else:
       print ("Not the same!")
       print ("The correct answer is:")
       print (number)

    while True:
        answer = input('Try again? (y/n): ')
        print (" ")
        if answer in ('y', 'n'):
            break
        print("You can only answer with y or n!")
    if answer == 'y':
        continue
    else:
        print("Better next time!")
        break