learning python--couldn't figure out random.randint
I am learning python atm, and was doing an exercise from this site--
开发者_JS百科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:
import random
input("Think of a number from 1 to 10, then press enter. Don't tell me, I'll guess it.")
low = 1
high = 10
done = False
for guesses in range(7):
number = random.randint(low, high)
print("I'm guessing", number)
happy = False
while not happy:
resp = input('Enter H if your number is higher, L if lower or E for equal: ')[0].upper()
if resp == 'E':
if guesses:
plural = 'es'
else:
plural = ''
print('Yay! I got it in {} guess{}.'.format(guesses+1, plural))
happy = True
done = True
break
elif resp == 'H':
happy = True
low = number + 1
elif resp == 'L':
happy = True
high = number -1
else:
print("That wasn't a valid response.")
if done:
break
print('end')
What I did differently:
- The program doesn't get your number as input (it's trying to guess it after all).
- I set low & high to the initial range and set up a done flag as I'll need to break out of two levels of loop on success
- next I guess based on low-high range.
- ask for H, L or E to indicate where my guess falls
- modify the range based on what user tells me
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.
The error here is in your usage of <=
and >=
. These mean less-than-or-equal-to
and greater-than-or-equal-to
, respectively. Your code will therefore never reach the elif number == pick:
line because one of the first two statements will always be true. It's clear to see that if number == pick
then the first statement will be true and the program will prompt the user to press enter if higher
.
The answer? Change <=
to simply <
, and similarly let >=
become >
. This way the test is only for less-than
and greater-than
.
精彩评论