I am learning python atm, and was doing an exercise from this site—
Instruct the user to pick an arbitrary number from 1 to 100 and proceed to guess it correctly within seven tries. After each guess, the user must tell whether their number is higher than, lower than, or equal to your guess.
the code I wrote, but did not match the solution was this–
import random
pick = int(input('number? '))
count = 0
while count <= 7:
number = random.randint(1, 10)
count += 1
print('is the number ', number, '?')
if number <= pick:
print('press enter if higher')
higher = input()
elif number >= pick:
print('press enter if lower')
lower = input()
elif number == pick:
print('good?')
yes = input()
break
print('end')
I couldn’t get this one right. When number ==pick, the loop did not end. Was it because of the random.randint that was mucking the elif number==pick ?
The solution given in the site was way different from the one I wrote. How could I have done this better?
Thanks!
Well here’s a quick rewrite I did just based on the problem text you posted:
What I did differently:
The main difference is that this code somewhat intelligently guesses the number. (Though with 7 guesses it could still fail.) A more intelligent algorithm would be to guess midpoints each time rather than randomly.