Python3.x | 猜数字游戏

2018-04-18  本文已影响80人  Ghibli_Someday
# 猜数字游戏

import random, os

#输入值的函数,且防止输入非数字
def input_num():
    while True:
        try:
            num = int(input('\nPls enter an integer which you think is the right num: '))
            return num
            break
        except ValueError:
            print('Pls enter an integer!')

#取随机数           
rn = random.randint(0 ,1000)
low, high = 0, 1000
print('************Guess A Num Betweem 0 And 1000!************\n')

while True:
    #调用输入函数
    num = input_num()
    
    #清空界面,告知使用者结果正确
    if num == rn:
        os.system('cls')
        print('You enter the right num! It is:', num)
        break
    
    #提示输入的值不在范围内
    elif num < low or num > high:
        print('Pls enter a num between', str(low), 'and', str(high))
    
    #输入的值大于随机数,重新给定范围   
    elif num > rn:
        print('It is higher')
        high = num
        print('Pls enter a num between', str(low), 'and', str(high))
    
    #输入的值小于随机数,重新给定范围   
    elif num < rn:
        print('It is lower')
        low = num
        print('Pls enter a num between', str(low), 'and', str(high))
        

上一篇 下一篇

猜你喜欢

热点阅读