Lesson 8: While loop and binary search

posted Dec 7, 2017, 8:02 AM by Attila Lengyel
import random

lowerlimit = 0
upperlimit = random.randint(5,10)

print("Think a number between 0 and", upperlimit)

answer = "no"
while answer != "yes":
  number = (lowerlimit + upperlimit) / 2
  number = round(number,0)
 
  print("Is the number", number, "? Or it is greater/less?")
  answer = input()
 
  if answer == "greater":
    lowerlimit = number
  if answer == "less":
    upperlimit = number
   
  if answer == "yes":
    print("I did it!!!")
   
Comments