Home > OS >  Why does this code not update the Score? It only changes it to 1 but never higher
Why does this code not update the Score? It only changes it to 1 but never higher

Time:01-08

In this code I expect the Score variable to increase when f is entered, but it stays at 1 all the time.

Score = 0


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

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


Game()

Why is that?

CodePudding user response:

There are two problems (and a few stylistic ones) in your code:

This is your code from the screenshot:

Score = 0


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

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


Game()

The first problem is a typo, you wrote Score = 1 instead of Score = 1 - see this question for more details on that. Essentially you're saying Score = ( 1) which explains why your score will be 1 all the time.

Interestingly enough this typo hides another problem that's related to the scope of your score variable. You define Score as a global variable outside of the function. To be able to modify the variable inside a function, you need to do define it as global in the function: global Score.

Putting these things together, your code looks like this:

Score = 0


def Game():

    global Score

    KAJSH = input("f e")

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

Game()

There are some parts here, that violate the PEP-8 styleguide for Python and make your code less intuitive to other developers. A more conventional implementation would look like this:

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, so here's a version that avoids them using a default value for the score in the function and then passing the changed value into the recursion:

def game(score=0):

    user_input = input("f e")

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

game()

CodePudding user response:

Here is a rewritten version of your code.

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

Cosnider using a loop instead, but if youf really want to use recursion, dont forget to pass in "Score"

  • Related