Search code examples
pythonfunctionif-statementvariablestraceback

SIMPLE CODE: How to define a ranging variable? (Code error)


The code outputs an error: name 'numAttacks' is not defined. How do I define numAttacks if it will be based on user's input in def difficulty?

def fightBattle(difficulty):
    if (difficulty == "easy"):
        numAttacks = 10
    elif (difficulty == "hard"):
        numAttacks = 5
difficulty = input("Which difficulty mode you wish to play on?: (Easy/ Hard) ")


def game():
    for i in range (numAttacks):
        print("Village")
game()    


Solution

  • The function should return the value so you can assign it to the variable.

    def fightBattle(difficulty):
        if (difficulty == "easy"):
            numAttacks = 10
        elif (difficulty == "hard"):
            numAttacks = 5
        else:
            raise ValueError("Difficulty should be easy or hard")
        return numAttacks
    
    def game():
        print("something")
        difficulty = input("Which difficulty mode you wish to play on?: (Easy/ Hard) ")
        numAttacks = fightBattle(difficulty)
        for i in range (numAttacks):
            print("Village")
    
    game()