3

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'
  • 2
    Possible duplicate of [Replacements for switch statement in Python?](http://stackoverflow.com/questions/60208/replacements-for-switch-statement-in-python) – PointerToConstantChar Mar 20 '17 at 00:51
  • looks like information you should be parsing directly into dictionaries – abigperson Mar 20 '17 at 00:52
  • There are several things you could do, but it depends what you want to do after this. You could just create a dict mapping the numbers to strings. You could also use the four strings as arguments to `random.choice`. – Paul Rooney Mar 20 '17 at 00:52
  • use random.choice function instead. See Python doc – Nabil Mar 20 '17 at 01:01

3 Answers3

5

Use random.choice

import random

hero = ['Marth', 'Lucina', 'Robina', 'Tiki']
print(random.choice(hero))
Naz
  • 76
  • 5
  • @JohnnyAppleseed Glad to hear. please mark my answer as correct to close your question (green tick) – Naz Mar 20 '17 at 01:05
0
import random

hero_list = ['Marth', 'Lucina', 'Robin', 'Tiki']
print hero_list[random.randint(0, len(hero_list)-1)]
0
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'.

  • sorry your way is a bit too new and complex if you know what I mean. – Johnny Appleseed Mar 20 '17 at 01:00
  • Its the best way, and the best way to learn is to have complex solutions. Its quite simple, all we are saying is have a dictionary, then just do a lookup like as if you were doing `myDictionary[3]`, but the get statement as a default to return to. But fair enough, you could split it up into a dictionary such as myDictionary = { ... }, then do an if x in myDictionary do this else return the default. – Braedon Wooding Mar 20 '17 at 01:06
  • Although this code might solve the problem, you should really add an explanation to it, stating why/how this code works. – BDL Apr 09 '17 at 07:47