<>引入

如果给你一个给定的范围,让你猜出这个范围内的任意一个数,你怎样才能又快又准确的猜出你?可以采用
二分法,比如在一到一百内猜,先猜五十,如果大了就猜二十五,如果小了就猜七十五,按照这样下去很快就能猜出那个数!

<>程序
import random target = random.randint(0,100) x = int(input("Try to guess the
number I'm think of:")) while True: if x > target: x = int(input('Too high!
Guess again:')) elif x < target: x = int(input('Too low! Guess again')) else:
break print("That's it! Thank for playing!")
<>请看程序结果

这个程序一次就结束了,可是如果用户想多玩几次程序又该怎么改进呢?

<>改进程序
import random while True: target = random.randint(0,100) x = int(input("Try to
guess the number I'm think of:")) while True: if x > target: x = int(input('Too
high! Guess again:')) elif x < target: x = int(input('Too low! Guess again:'))
else: break choice = input("That's it! Would you like to play again?(yes/no)")
if choice == 'no': break print("That's it! Thank for playing!")
<>请看程序结果

这样用户就可以多次玩了!

技术
今日推荐
下载桌面版
GitHub
百度网盘(提取码:draw)
Gitee
云服务器优惠
阿里云优惠券
腾讯云优惠券
华为云优惠券
站点信息
问题反馈
邮箱:[email protected]
QQ群:766591547
关注微信