0

ALERT: Beginner's problem

Here is the question: Two players are given the same string, ex: "BANANA" For each sub-string that can be formed starting with a vowel adds a score of 1 to player 1 else 1 to player 2 (repetitions allowed) so finally: player's 1 score is 9 and player's 2 score is 12

vowels = "AEIOU"
player_1 = 0
player_2 = 0

def winner(user_string):
    for index, item in enumerate(user_string):
        if item in vowels:
            player_1 += len(user_string[index:])
        else:
            player_2 += len(user_string[index:])

    if player_1 > player_2:
        print("Ply 1 won")
    else:
        print("Ply 2 won")

winner("BANANA")

but it is throwing an error as shown below. enter image description here

can someone please help me out with the issue. Is there any order of compilation that I need to learn here? Thank you

Rajesh M
  • 31
  • 7

1 Answers1

1

This is an issue of the scope of variables (here both: player_1 and player_2). Check this question/answer.

So the correct approach would be to either move the initialization of the variables to the function or add:

global player_1
global player_2

at the beginning of the function winner body.

My preference is the first approach so the correct function is:

def winner(user_string):
    player_1 = player_2 = 0
    for index, item in enumerate(user_string):
        if item in vowels:
            player_1 += len(user_string[index:])
        else:
            player_2 += len(user_string[index:])

    if player_1 > player_2:
        print("Ply 1 won")
    else:
        print("Ply 2 won")
sophros
  • 14,672
  • 11
  • 46
  • 75