【问题标题】:Why does this code not update the Score? It only changes it to 1 but never higher为什么此代码不更新分数?它只会将其更改为 1 但不会更高
【发布时间】:2023-01-08 00:30:12
【问题描述】:

在此代码中,我希望 Score 变量在输入 f 时增加,但它始终保持在 1。

Score = 0


def Game():
    KAJSH = input("f e")

    if KAJSH == "f":
        Score =+ 1
        print(Score)
        Game()


Game()

这是为什么?

【问题讨论】:

  • 将 =+ 更改为 +=。好像是这个问题
  • 嘿,欢迎来到 stackoverflow!请不要发布您的代码的屏幕截图。而是编辑您的帖子并将您的代码添加到代码块中。使用屏幕截图会使试图帮助您重现问题的人变得困难,搜索引擎也很难为问题编制索引,以便将来帮助其他人。
  • 你可能想看看这个问题:What is the difference between '+=' and '=+'?。我不确定这个在技术上是否重复,但它解释了根本原因。

标签: python


【解决方案1】:

这是您的代码的重写版本。

Score = 0
def game(Score):
    k = input("f e")
    if k == 'f':
        Score += 1
        print(Score)
        game(Score)
game(Score)

考虑使用循环代替,但如果你真的想使用递归,不要忘记传入“Score”

【讨论】:

  • 我建议对全局变量和局部变量使用相同的名称可能会让 OP 感到有些困惑。更改一个名称以表明它们是不同的或更好地省略第一行代码并使最后一行成为game(0)会更清楚
  • 你说的不同是什么意思?
【解决方案2】:

您的代码中有两个问题(以及一些风格问题):

这是屏幕截图中的代码:

Score = 0


def Game():
    KAJSH = input("f e")

    if KAJSH == "f":
        Score =+ 1
        print(Score)
        Game()


Game()

第一个问题是打字错误,您写的是 Score =+ 1 而不是 Score += 1 - 有关详细信息,请参阅 this question。本质上你说的是Score = (+1),这解释了为什么你的分数一直是 1。

有趣的是,这个错字隐藏了另一个与 score 变量范围相关的问题。您将 Score 定义为函数外部的全局变量。为了能够修改函数内的变量,您需要在函数中将其定义为全局变量:global Score

将这些东西放在一起,您的代码如下所示:

Score = 0


def Game():

    global Score

    KAJSH = input("f e")

    if KAJSH == "f":
        Score += 1
        print(Score)
        Game()

Game()

这里有一些部分违反了 Python 的 PEP-8 styleguide 并使您的代码对其他开发人员来说不那么直观。一个更传统的实现看起来像这样:

SCORE = 0

def game():

    global SCORE

    user_input = input("f e")

    if user_input == "f":
        SCORE += 1
        print(SCORE)
        game()

game()

Global variables are also not ideal,所以这里有一个版本可以避免他们在函数中使用分数的默认值,然后将更改后的值传递给递归:

def game(score=0):

    user_input = input("f e")

    if user_input == "f":
        score += 1
        print(score)
        game(score)

game()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 2022-12-31
    • 2018-07-01
    • 2012-01-02
    相关资源
    最近更新 更多