After the feedback for my last script, I realized I should be using functions and trying to adhere to the style guide. I tried to do that here, though still very beginner.
The rounding in Python confused me a bit, and originally the program got stuck for some numbers when the range narrowed down to 1. I think it should work for all cases now (only tested 1-1000).
# Users chooses number in given range, comp guesses
HIGH_NO = 10000
LOW_NO = 1
def getno():
# Get a number in range from user.
x = ""
while not x or x > HIGH_NO or x < LOW_NO:
print("Enter a number between %s and %s" % (LOW_NO, HIGH_NO))
x = input()
try:
x = int(x)
except ValueError:
x = getno()
return(x)
def approxhalf(lowno, highno):
# Find integer approx halfway point between two values.
x = abs(round((lowno+highno)/2))
return x
def guessno():
# Computer finds number by halving
no1 = LOW_NO
no2 = HIGH_NO
userno = getno()
compguess = ""
count = 0
while compguess != userno:
count += 1
compguess = approxhalf(no1, no2)
if abs(no2-no1) > 2 or compguess == userno:
print('%s. I guess %s' % (count, compguess))
if compguess > userno:
no2 = compguess
elif compguess < userno:
no1 = compguess
elif compguess == userno:
print("Got it!")
else:
print("wtf dude")
else:
# For when the low and high no.s are consecutive
if no1 == userno:
print('%s. I guess %s' % (count, no1))
print("Got it")
break
elif no2 == userno:
print('%s. I guess %s' % (count+1, no2))
print("Got it")
break
else:
print("I.. I don't understand")
def main():
while True:
guessno()
print('\n')
main()
number
everywhere you haveno
.no
is a very easily misread abbreviation. \$\endgroup\$ – Schism Aug 19 '15 at 18:43num
. \$\endgroup\$ – Panzercrisis Aug 19 '15 at 20:24userno
of 1 should have acount
that is 1 higher than thecount
for auserno
of 2, but as written, whenno1=1
andno2=3
, what the computer guesses with the nextcount
will differ, depending on the value ofuserno
. \$\endgroup\$ – Dan Henderson Aug 20 '15 at 17:23