Python Day 40 – random numbers and infinite guesses

Today I learned how to generate random numbers with the random model. You set a variable with a range equal to:

random.randint(low#, high#)

I used this in a practice exercise with the while loop to have a user input guess a randomly generated number until they get it right. Here’s the code:

highest = 10
answer = random.randint(1, highest)

print(“How many fingers do you think I have? “)
guess = int(input())

if guess == answer:
print(“Arr you right first time”)
else:
while 0 < guess < answer:
print(“too low!”)
guess = int(input())
while guess > answer:
print(“ya too high”)
guess = int(input())
if guess == answer:
print(“okay well done you got it eventually i guess”)
while guess == 0:
print(“give up!”)
break

Here I learned to set the high range of the random generator to be a variable itself, so it’s easier to change after the fact. I also used the break function to allow the player to stop the game whenever they input 0, but in order for this to work I had to set the low guess while loop to be between 0 and the answer, otherwise it would obstruct the code from getting to the break line if the input is 0.

The Udemy course then got into this binary guessing game, which sets up the computer to guess a number someone is thinking by splitting the range of possible answers in half each time. This is pretty neat although I don’t yet see the applicability of this in normal coding. The biggest takeaway from it was one could guess a number between 1 and 1000 in 10 guesses (provided you know whether your guess is higher or lower than the answer each time).

Some neat stuff. Definitely applicable to an interactive narrative. I’m now starting to see how essential while loops are.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: