如何在猜谜游戏中创建猜测计数器

我正在尝试制作一个数字猜谜游戏,当你猜对数字时,它会告诉你猜了多少次。


我已经尝试了几个循环,但无法弄清楚如何让我的“猜测”增加。


import random


rand_num = random.randrange(1,201)



def guess_game():


    guess = int(input("Please enter your guess: "))

    guesses = 1

    if guess == rand_num:

        print("Hit!\nIt took you " + str(guesses) + " guesses!")

    elif guess < rand_num:

        print("Your guess is too low.")

        guesses = guesses + 1

        guess_game()

    else:

        print("Your guess is too high")

        guesses = guesses + 1

        guess_game()


guess_game()

例如,所需的输出应该是这样的:


"Hit! It took you 5 guesses"

但无论尝试了多少次,它都只说 1 次猜测。


慕尼黑8549860
浏览 109回答 3
3回答

大话西游666

您的代码不起作用,因为您guess_game()在每次猜测后继续调用,每次猜测后有效地开始新游戏。当用户最终正确猜测时,它总是在该新游戏中的 1 次猜测之后,然后所有游戏立即结束,但代码永远不会到达在任何这些游戏中多次猜测后打印数字的行。有很多不同的方法可以解决这个问题,但这里的主要问题是(像许多新程序员一样)你没有意识到调用函数不仅让程序跳转到你的新代码,它还为你创造了一个全新的空间。要工作的程序(对函数的每次调用都有自己的“作用域”)并在函数完成后从该程序返回,在大多数情况下之前的作用域不变。

Qyouu

每次你打电话guess_game(),你基本上是在重置游戏。相反,您希望将游戏封闭在一个while循环中,该循环仅在游戏结束时退出。我在这里为您编写了一个工作版本:import randomrand_num = random.randrange(1,201)def guess_game():&nbsp; &nbsp; guesses = 1&nbsp; &nbsp; while(True):&nbsp; &nbsp; &nbsp; &nbsp; guess = int(input("Please enter your guess: "))&nbsp; &nbsp; &nbsp; &nbsp; if guess == rand_num:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Hit!\nIt took you " + str(guesses) + " guesses!")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return 0&nbsp; &nbsp; &nbsp; &nbsp; elif guess < rand_num:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Your guess is too low.")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; guesses = guesses + 1&nbsp; &nbsp; &nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; print("Your guess is too high")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; guesses = guesses + 1guess_game()

函数式编程

您的代码运行不正常,因为guesses=1当您调用函数本身(递归)时,您在函数中进行了初始化,变量guess 的值被重置。import random&nbsp; &nbsp;&nbsp;rand_num = random.randrange(1,201)guesses=0 #initialize it outside functiondef guess_game():&nbsp; &nbsp; guess = int(input("Please enter your guess: "))&nbsp; &nbsp; global guesses&nbsp;&nbsp; &nbsp; guesses+=1&nbsp; &nbsp; if guess == rand_num:&nbsp; &nbsp; &nbsp; &nbsp; print("Hit!\nIt took you " + str(guesses) + " guesses!")&nbsp; &nbsp; elif guess < rand_num:&nbsp; &nbsp; &nbsp; &nbsp; print("Your guess is too low.")&nbsp; &nbsp; &nbsp; &nbsp; guess_game()&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print("Your guess is too high")&nbsp; &nbsp; &nbsp; &nbsp; guess_game()guess_game()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python