有趣的猜字游戏

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

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 randomwhile 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!")

请看程序结果 有趣的猜字游戏
文章图片

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

    推荐阅读