美文网首页
猜数字小游戏

猜数字小游戏

作者: 希文X | 来源:发表于2020-05-02 12:07 被阅读0次

    学习收获

    • random模块的使用:secretNumber = random.randint(1, 20)
    • 捕获输入数据的方法:guess = int(input())

    程序运行效果

    猜数字小游戏.png

    程序源码

    # 导入用于生成随机数的模块
    import random
    
    # 1 随机产生一个1到20之间的数字,作为目标数字
    secretNumber = random.randint(1, 20) 
    print('I am thinking of a number between 1 and 20.') 
    
    # 2 猜数字(6次机会)
    for guessesTaken in range(1, 7):
        # 2.1 提示玩家输入所猜数字
        print('Take a guess.')     
        guess = int(input()) 
    
        # 2.2 判断输输入数字是否为目标数值,并给出大小关系提示
        if guess < secretNumber:         
            print('Your guess is too low.')     
        elif guess > secretNumber:         
            print('Your guess is too high.')     
        else:         
            break # This condition is the correct guess!
    
    # 3 判断游戏结果,在6次机会中是否成功猜出数字
    if guess == secretNumber:     
        print('Good job! You guessed my number in ' + str(guessesTaken) + ' guesses!') 
    else:     
        print('Nope. The number I was thinking of was ' + str(secretNumber)) 
    

    相关文章

      网友评论

          本文标题:猜数字小游戏

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