How can I set a random value during my code?

Is there any way to save a random value when the code is re-run?

For example, let’s say I wanted to write some code in which the computer picks a random number from 1-100, and the user has to guess it. Each time the user guesses a number, the computer tells them whether it’s too high or too low until they get it.

The issue I’ve been running into is that the code re-runs each time the user guesses a number; maybe the number is 50 and they guess 25, but then when they hit enter on their guess the whole code reruns, including the random.randint(1, 100) part, and a new number is chosen. I can’t see how a user could interact with a randomly chosen value without the value changing every time they try.

Surely there’s some way to deal with this. Thanks!

Welcome to the forums, @chip0021917487.

There is a way to deal with it. Define the computer’s number once, before the loop in which the user enters their guesses.

computer = random.randint(1, 100)
user = None
while user != computer:
    user = int(input("Enter your guess: "))
    if user < computer: print ("Too low")
    elif user > computer: print ("Too high")
print ("You guessed it!")