0

Getting a NameError: name 'cost' is not defined at player.reduce_mp(cost)

elif index == 1:
    player.choose_magic()
    magic_choice = int(input('Choose magic'))-1
    magic_dmg = player.generate_spell_damage()
    spell = player.get_spell_name(magic_choice)
    cost = player.get_spell_mp_cost(magic_choice)
    current_mp = player.get_mp()

    if cost > current_mp:
        print(bcolors.FAIL + '\nNot enough MP\n' + bcolors.ENDC)
        continue

player.reduce_mp(cost)
enemy.take_damage(magic_dmg)
print(bcolors.OKBLUE + '\n' + spell + 'deals', str(magic_dmg), 'points of damage' + bcolors.ENDC)
VMAtm
  • 27,943
  • 17
  • 79
  • 125
Monty
  • 107
  • 1
  • 3
  • 9
  • 1
    Without seeing the code around that area, it's difficult to say, but as `cost` is only shown within the `elif` part, it looks like it's out of scope when you come to use it within `player.reduce_mp(cost)` – gabe3886 Apr 18 '17 at 13:30
  • 2
    Show where you think cost is defined. – Mad Physicist Apr 18 '17 at 20:11

2 Answers2

0

How about now:

elif index==1:
    player.choose_magic()
    magic_choice=int(input('Choose magic'))-1
    magic_dmg=player.generate_spell_damage()
    spell=player.get_spell_name(magic_choice)
    cost=player.get_spell_mp_cost(magic_choice)

    current_mp=player.get_mp()

    if cost>current_mp:
        print(bcolors.FAIL+ '\nNot enough MP\n'+bcolors.ENDC)
        continue

    player.reduce_mp(cost)
    enemy.take_damage(magic_dmg)
    print(bcolors.OKBLUE+'\n'+spell+'deals',str(magic_dmg),'points of damage'+bcolors.ENDC)
zipa
  • 27,316
  • 6
  • 40
  • 58
-1

The thing is that you're using the 'cost' value outside the scope of its declaration. If your final if statement is well indented, then add

int cost

In the printing scope, before its assignment (before the elif, without indentation). This post will explain you further this concept.

Community
  • 1
  • 1
Leath
  • 101
  • ``int cost`` is not valid python. Also, no scopes are involved here: if statements (and else/elif) do not open any scopes in python. – Jonas Schäfer Apr 18 '17 at 16:58