The question may have been answered many times, but it deserves to be answered again as it is a bit tricky.
It seems that you want to use the outer (as if global) variable mobhp
defined before the function definition -- as others pointed out in the comments. You should follow Hasan's advice, but you may have done it if the problem were not masked by the definition outside the function. Actually, you will want probably to pass the outer value via argument as Daniel suggested. I suggest not to use global
at all -- it is almost never the way to go.
What others failed to explain is that actually, the following code would work:
import time
import random
mobhp = random.randint(10,40)
def fun1():
print("You have chosen option number 1")
#time.sleep(1)
print("You attept an attack")
#time.sleep(2)
cointoss = 1
if cointoss == 1:
print("Attack successfull!")
playerDam = random.randint(10,60)
newmobhp = mobhp - playerDam
def main():
fun1()
main()
Here the mobhp
is also used before the assignment, and all commands above the usage are the same as in the earlier case. The difference is that the lookup rules found the variable outside the function.
If the variable is not found in the local scope, the variable is searche in the outer scope. However, it is only the case when the varialble is read. Once the variable is assigned inside the function body, it is always considered local, and it is never searched in the outer scope.
The decision whether the variable is local or can be outer is done during the compilation of the function -- simply said, during loading the function body when reading the script. When the function is called, its definition was already loaded (i.e. body compiled). And because of the line mobhp = newmobhp
it was decided that mobhp
must be local, even though the command is found later than the newmobhp = mobhp - playerDam
.
That is probably always the reason for UnboundLocalError
.