'Is there a way to make a random variable into one that isn't random?
I am experimenting and studying a lot about programming lately. I want to write a guessing game in python, where the pc guesses a number in a range defined by the user. The way I have written this part is like so:
low = int(input("Choose the smaller number: "))
high = int(input("Choose the higher number: "))
num = random.randint(low, high)
pc_guess = input("Is this number correct: "+ str(num)+ "?")
If the answer isn't correct the computer will ask if their guess was high or low. What I wanted to do, was set a new range based on the computer's guess (for example, if the guess was too high, the new ceiling would be the guess minus 1). The guessing game concept isn't new to me, I wanted to try and write it more dynamically, test myself. But I realized I didn't know the answer to this question, is there any way to take the value of a previous random number, and assign it to a variable that isn't random?
Solution 1:[1]
For each randomized guess, adjust the corresponding limit e.g. low if the guess was lower than the number to guess and high otherwise.
import random
low = 0
high = 20
num = random.randint(low, high)
print(f"Number to guess: {num}")
while True:
pc_guess = random.randint(low, high)
print(f"Is this number correct: {pc_guess}?")
if pc_guess == num:
print("\tYes!")
break
elif pc_guess < num:
print("\tNo. Higher")
low = pc_guess + 1
elif pc_guess > num:
print("\tNo. Lower")
high = pc_guess - 1
Output
Number to guess: 13
Is this number correct: 16?
No. Lower
Is this number correct: 3?
No. Higher
Is this number correct: 5?
No. Higher
Is this number correct: 14?
No. Lower
Is this number correct: 8?
No. Higher
Is this number correct: 12?
No. Higher
Is this number correct: 13?
Yes!
Solution 2:[2]
This is how I see it work out:
low = int(input("Choose the smaller number: "))
high = int(input("Choose the higher number: "))
pc_guess = 'n'
while pc_guess == 'n':
num = random.randint(low, high)
pc_guess = input("Is this number correct: "+ str(num)+ "? (y/n)")
if pc_guess == 'n':
new = input("Is it higher or lower? (h/l)")
if new == 'h':
low = num + 1
elif new == 'l':
high = num - 1
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Niel Godfrey Ponciano |
| Solution 2 | mkrieger1 |
