2

I'm trying to use a procedure to output multiple values (enemy, enemy_health, and treasure), but the procedure spawn() doesn't seem to do it. How can I do this successfully?

import random

def spawn(enemy, enemy_health, treasure):
    enemy_number = random.randint(1, 6)
    if enemy_number == 1:
        enemy = "pig"
        enemy_health = 20
        treasure = 20
    elif enemy_number == 2:
        enemy = "dragon"
        enemy_health = 500
        treasure = 500
    elif enemy_number == 3:
        enemy = "poop"
        enemy_health = 1
        treasure = 0
    elif enemy_number == 4:
        enemy = player_class + " robot"
        enemy_health = 100
        treasure = player_health
    elif enemy_number == 5:
        enemy = "alien"
        enemy_health = 75
        treasure = 75
    elif enemy_number == 6:
        enemy = "none"
        treasure = randint(1, 100)

enemy_damage = 0
enemy = ""
enemy_health = ""
treasure= ""
spawn(enemy,enemy_health,treasure)
print(enemy)
OverLordGoldDragon
  • 1
  • 9
  • 53
  • 101
  • Possible duplicate of [How do I return multiple values from a function?](https://stackoverflow.com/questions/354883/how-do-i-return-multiple-values-from-a-function) – Andreas Sep 24 '19 at 06:36

1 Answers1

1

Add return enemy, enemy_health, treasure at the end of spawn() (no arguments needed for a func like this). Also, better use a dictionary of lists for case-by-case selection:

def spawn():
    spawn_cases = {1: ["pig", 20, 20], 2: ["dragon", 500, 500]} # and so on
    enemy_number = random.randint(1, 6)
    return spawn_cases[enemy_number]

enemy, enemy_health, treasure = spawn() # list is automatically 'unpacked' into the three
print(enemy, enemy_health, treasure)
# >> dragon 500 500
OverLordGoldDragon
  • 1
  • 9
  • 53
  • 101
  • OverLordGoldDragon is correct: a return statement is needed at the end of the function, otherwise it returns None. – fralau Sep 24 '19 at 04:01
  • I've heard it's bad programming to use multiple return statements at the end of a function? Is this true?And what would be an alternative to that? –  Sep 25 '19 at 01:28
  • @VincentM. As long as your function name and return variable names are clear, it's fine - the advice is mainly for low-level programming languages, but former takes care of even that. More importantly, try to adhere to "one function does one thing" - which need not mean "returns one thing" – OverLordGoldDragon Sep 25 '19 at 01:48