python cant use a function to change the value of a variable -
i'm rather new python , wondering why function , therefore if statement returns "100" instead of "83" in code below. i'm not sure if i'm missing obvious seems if should work.this code i'm refering to:
playerhp = 100 def attack1(x): x = (x - 17) return x while playerhp > 0: enemyattack = input("please type word 'attack': ") if enemyattack.upper() == "attack": attack1(playerhp) print(playerhp) else: break
as mentioned in comment above, issue comes down scoping. try googling more info, i'll try give beginner level explanation here.
when declare variable, exists in specific scope, , can accessed variables in same or lower scope. example,
var1 = 5 if var1 < 6: print(var1) var2 = 7 print(var2) #error on line
var1
exists in highest scope in example, accessible lower ones, print(var1)
line works fine. however, var2
in higher scope statement attempting print it, , such cannot find variable. since python forces nice formatting, can think of scope broadly each level of indentation. if have go section more indented, can find it, if need go through section less indented find it, can't.
this extends functions. function attack1
exists in different scope inside while loop, , variable x
exists within function. such, when modify x
, modifies in scope, not original. beyond scope of original question, passing value
, passing reference
mean, , how apply python. other answers point out, can fix assigning return value
of x original number passing in, i.e.
playerhp = attack1(playerhp)
to take new number, 17 less used be, , reassign original value, assumes new value instead.
edit regards other answers suggest
some people suggest modifying global variable directly. (i'm assuming python 3 here, don't know version you're using or if python 2 different), can that. python little funny scoping out of functions, simple rewrite attack function this:
def attack1(): global playerhp playerhp -= 17 #shortcut subtract 17, same playerhp = playerhp - 17
and can call
attack1()
and work same way. many programmers shy away using global variables if can avoid it, subjective , they'll fight day until end of time.
Comments
Post a Comment