import random
k = random.randint(10,20)
x =0whileTrue:
y =input("请输入您猜的数字:")ifint(y)>k:print("大了")
x+=1elifint(y)<k:print("小了")
x+=1else:print("您猜对了")print("您总共猜了{0}次".format(x))break
2.二分法查找元素
defsearch():
k=[1,2,3,4,5,6,7,8]#数组
x =0
y =len(k)-1
j =input("请输入您的数字:")ifint(j)in k:while y>= x:
i =(x + y)//2if k[i]>int(j):
y =i -1elif k[i]<int(j):
x =i +1else:breakprint("你要查找的数字{0}出现在数组的下标为{1}".format(j,i))return i
else:print("你想要查找的数字{0}不在数组内".format(j))return-1
search()