Here's the most similar solution to yours that just fixes the issues with your code:
score_of_enemy = 0
def enemy_score():
global score_of_enemy
print(" ENEMY SCORE")
score_of_enemy = score_of_enemy.__add__(1)
print(score_of_enemy)
enemy_score() # this is just if the function is ever called
enemy_score()
enemy_score()
Result:
ENEMY SCORE
1
ENEMY SCORE
2
ENEMY SCORE
3
Those issues were:
- if you operate on
score_of_enemy
inside your function without declaring it global
, then you won't be modifying the global copy that exists outside the function, which is what you want so that each call to the function adds to the score. So I added the call global score_of_enemy
.
score_of_enemy.__add__(1)
adds 1
to the value of score_of_enemy
but doesn't store the resulting value back in score_of_enemy
. You have to do that explicitly, as shown in my version.
- You can't put an assignment statement inside a
print
statement, so I broke the two operations onto separate lines.
- You don't need the
return
statement if you don't give it an argument to specify something to return. Just return
at the end of a function is redundant.
Using __add__
is unusual, as it's the same thing as +
. Most programmers use +
. You can abbreviate that line further using +=
. So the equivalent of the score_of_enemy = score_of_enemy.__add__(1)
is score_of_enemy += 1
.
To give you an idea of how to avoid the use of global
(per the comments), here's another version that avoids its use. It seems more complicated here, and it is, but that's only because this code is just a simple example. In real life, following this pattern will make your code more readable and stable:
score_of_enemy = 0
def enemy_score(score):
print(" ENEMY SCORE")
score += 1
print(score_of_enemy)
return score
score_of_enemy = enemy_score(score_of_enemy) # this is just if the function is ever called
score_of_enemy = enemy_score(score_of_enemy)
score_of_enemy = enemy_score(score_of_enemy)