美文网首页
Python3.x | 猜数字游戏

Python3.x | 猜数字游戏

作者: Ghibli_Someday | 来源:发表于2018-04-18 21:18 被阅读80次
    # 猜数字游戏
    
    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))
            
    
    

    相关文章

      网友评论

          本文标题:Python3.x | 猜数字游戏

          本文链接:https://www.haomeiwen.com/subject/rabbkftx.html