Johnny Appleseed
Johnny Appleseed

Reputation: 79

Simpler If Statements

I have very little coding experience with Python, and am making a game for a Python coding class. I don't know any complicated stuff except this.

Is there a way to simplify the if statements from the code provided below to possibly one single if statement to reduce repetition? I have many more of these that will have to do many more rather than 4 numbers. Thanks.

import random
hero = random.randint(1,4)
if hero == 1:
    print 'Marth'
elif hero == 2:
    print 'Lucina'
elif hero == 3:
    print 'Robin'
else:
    print 'Tiki'

Upvotes: 3

Views: 158

Answers (3)

Braedon Wooding
Braedon Wooding

Reputation: 171

import random
def GetHeroName(x):
    return {
      1 : 'Marth',
      2 : 'Lucina',
      3 : 'Robin'
    }.get(x, 'Tiki')


hero = random.randint(1,4)
print GetHeroName(hero)

Note: the get(x, 'Tiki') statement is saying get x, but if that fails default to 'Tiki'.

Upvotes: 0

Naz
Naz

Reputation: 76

Use random.choice

import random

hero = ['Marth', 'Lucina', 'Robina', 'Tiki']
print(random.choice(hero))

Upvotes: 5

Mitchell Gouzenko
Mitchell Gouzenko

Reputation: 129

import random

hero_list = ['Marth', 'Lucina', 'Robin', 'Tiki']
print hero_list[random.randint(0, len(hero_list)-1)]

Upvotes: 0

Related Questions