Why code is throwing error and what should I do to correct it? Code in description | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why code is throwing error and what should I do to correct it? Code in description

import random playerhealth = 150 enemyhealth = 200 attack = int(input("Attack!\n[1]Punch\n[2]Kick,[3]Knee,[4]Headbutt")) damage = [30,90,50,10] damaged = damage.choice(damage) def attacks() : if attack == 1 : print("You used Punch\n") global enemyhealth enemyhealth = enemyhealth - damaged print("damage to enemy",damaged,"\n") print(enemyhealth) elif attack == 2 : print("You used Kick\n") global enemyhealth enemyhealth = enemyhealth - damaged print("damage to enemy",damaged,"\n") print(enemyhealth) elif attack == 3 : print("You used Knee\n") global enemyhealth enemyhealth = enemyhealth - damaged print("damage to enemy",damaged,"\n") print(enemyhealth) elif attack == 4 : print("You used Headbutt\n") global enemyhealth enemyhealth = enemyhealth - damaged print("damage to enemy",damaged,"\n") print(enemyhealth) else : print("haaaaad")

20th Apr 2021, 9:22 AM
Tanishq Kamble
Tanishq Kamble - avatar
1 Answer
+ 1
You are calling global variable again and again in the if statement and elif statement. You don't need to do that. Just declare the global at the very first of that function and you will not get this error. https://code.sololearn.com/cA10a8A19A19 By the way, what are trying to achieve by this line: damaged = damage.choice(damage) It will also raise an error.
20th Apr 2021, 9:36 AM
The future is now thanks to science
The future is now thanks to science - avatar