Reputation: 39
def diserang(self, lawan, attackPower_lawan):
print(self.name + " Diserang " + lawan.name)
attack_diterima = attackPower_lawan / self.armorNumber
print("Serangan terasa :", str(attack_diterima))
self.health -= attack_diterima
print("Darah " + self.name + " tersisa " + str(self.health))
# TODO make hero attack and armor status up by 30% if the health reach by 50%
def statusUp(self, attUp, armUp):
if self.health <= 50 :
attUp += 30
armUp += 30
else:
raise Exception("Darah Anda Masih Normal")
i want to call the "statusUp" inside the "diserang", can anyone help me and explain it to me? im new at programming, thanks!
Upvotes: 1
Views: 9354
Reputation: 68
A function defined inside another function is called a nested function. Nested functions can access variables of the enclosing scope. In Python, these non-local variables are read-only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
You use inner functions to protect them from everything happening outside of the function, meaning that they are hidden from the global scope.
Here’s a simple example that highlights that concept:
def outer(num1):
def inner_increment(num1): # Hidden from outer code
return num1 + 1
num2 = inner_increment(num1)
print(num1, num2)
inner_increment(10)
# outer(10)
Try calling inner_increment():
Traceback (most recent call last):
File "inner.py", line 7, in <module>
inner_increment()
NameError: name 'inner_increment' is not defined
Now comment out the inner_increment() call and uncomment the outer function call, outer(10), passing in 10 as the argument:
10 11
Note: Keep in mind that this is just an example. Although this code does achieve the desired result, it’s probably better to make inner_increment() a top-level “private” function using a leading underscore: _inner_increment().
Upvotes: 2
Reputation: 4875
# TODO make hero attack and armor status up by 30% if the health reach by 50%
def statusUp(self, attUp, armUp):
if self.health <= 50 :
attUp += 30
armUp += 30
else:
raise Exception("Darah Anda Masih Normal")
def diserang(self, lawan, attackPower_lawan):
print(self.name + " Diserang " + lawan.name)
attack_diterima = attackPower_lawan / self.armorNumber
print("Serangan terasa :", str(attack_diterima))
self.health -= attack_diterima
print("Darah " + self.name + " tersisa " + str(self.health))
#mention your variables
statusUp(attUp, armUp)
Just call it inside function
Upvotes: 2