I created a game wherein I select a number from 1 to 100, and the computer guesses it. However I get IndexError when i'm selecting numbers below 6. why is this happening?.
Here is my code :
print("Helllo user, select a number from 1-100 in your mind and i will try to guess it...")
list_nums = range(1,101)
counter = 0
while True :
mid_element = list_nums[int(len(list_nums)/2)-1]
print(" Is your selected number {}".format(mid_element))
counter = counter + 1
response = str(input("is it too high or too low..? : "))
try:
if response == "too low":
list_nums = list_nums[int(len(list_nums)/2):int(len(list_nums))]
mid_element = list_nums[int(len(list_nums)/2)]
elif response == "too high":
list_nums = list_nums[1:int(len(list_nums)/2)]
mid_element = list_nums[int(len(list_nums)/2)]
elif response == "correct":
print("Perfect i finally guessed it. Your number is {}\n".format(mid_element))
break
except:
print("Invalid entry..Try again")
continue
print("\nI guessed it in {} attempts".format(counter))
Change line
list_nums = list_nums[1: int(len(list_nums)/2)]
to:
list_nums = list_nums[0: int(len(list_nums)/2)]
Because, list index starts at zero.
Or:
list_nums = list_nums[: int(len(list_nums)/2)]
Because, Python knows list starts at zero.