randomly choosing a function from a list then apply conditions to the result

Question:

In the code below, a, b, and c are pre-defined functions that are a part of much bigger code. The code is always returning the elif part even if the choice is enemy_def. I have tried printing each one but nothing happens.

a = enemy_hit
b = enemy_def
c = enemy_sphit
d = [a,b,c]
enemyresponse = random.choice(d)()
#print(enemyresponse)
if enemyresponse == b :
   thing.health = thing.health - 0.25
   #print(enemyresponse)
elif enemyresponse != b :
     #print(enemyresponse)
     thing.health = thing.health - 1
Asked By: Hasan Fares

||

Answers:

enemy_reponse will never be equal to b*, because enemy_reponse is the return value of the function, not the function itself. Note how you call the function immediately after randomly choosing it:

random.choice(d)()
#               ^Called it

Save the function that was chosen in a variable called chosen_function (or something similar), then check against that.

You probably meant something like this (untested):

a = enemy_hit
b = enemy_def
c = enemy_sphit
d = [a,b,c]

# Randomly get function from list
chosen_function = random.choice(d)

# Call it to get the return value
func_return = chosen_function()
print(func_return)

if chosen_function == b:
   thing.health = thing.health - 0.25

else:
   thing.health = thing.health - 1

*Unless b returns itself, which seems unlikely.

Answered By: Carcigenicate
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.