user3666755
user3666755

Reputation: 45

Printing random element of list of strings always gives the same string

I am making a text based game and Im trying to print out a random enemy and it prints the same enemy every time in the output variable

import random

monsters = [("Goblin", 1), ("Troll", 3), ("Bear", 2), ("Giant Spider", 1), ("Bandit", 1), ("Wolf", 1), ("Homeless Man", 1), ("Goblin Chief", 3)]

def spawnMonster():
    enemy, DMG = random.choice(monsters)
    print(enemy)
    output = "A " + enemy + " comes out of the bushes."

spawnMonster()
print(output)

Upvotes: 0

Views: 96

Answers (1)

abarnert
abarnert

Reputation: 365657

It looks like the problem with your program has nothing to do with randomness. It's that you're not returning the output value from the function to the top level, so whatever you had lying around in output before (probably from a previous run of your old program that you're doing in the same interactive session) is never getting changed.

Your old version used global output. That works, although it's a bit clunky.

A better solution would be to return the value. Like this:

def spawnMonster():
    enemy, DMG = random.choice(monsters)
    print(enemy)
    output = "A " + enemy + " comes out of the bushes."
    return output

print(spawnMonster())

But if you want it to be a global for some reason, you can go back to that.

Upvotes: 1

Related Questions