0

I'm very new to python and was wondering if there was a way to convert a series of if statements to two corresponding lists?

To take something like this:

var = int(input("Enter a number: "))

if var == 1:
    print("One")
elif var == 2:
    print("Two")
elif var == 3:
    print("Three")
elif var == 4:
    print("Four")

And convert it into something like this:

commandnumber = [1, 2, 3, 4]
command = [("One", "Two", "Three", "Four")]

print(command[commandnumber.index(var)])

I don't know enough about to python to understand if this is even doable or not. I basically want an easier way for a user to input a number and receive a corresponding command (i.e. print or turtle.forward) depending on what number was inputted.

Thank you for your time.

  • The code that you've written would work as you expected. What's exactly your question? – Lie Ryan Sep 29 '18 at 05:53
  • Though an easier way to do what you wanted to do is to use a dict rather than two arrays. – Lie Ryan Sep 29 '18 at 05:55
  • @LieRyan There's a problem in the code. The list is only 1 long and the only element is a 4-tuple. – iBug Sep 29 '18 at 05:55
  • @iBug good catch, but yes, just removing the extraneous round brackets would've made things work – Lie Ryan Sep 29 '18 at 05:58
  • But what about just defining `command = ["One", "Two", "Three", "Four"]` and then printing `command[val-1]`? – toti08 Sep 29 '18 at 06:09

3 Answers3

2

Using a dictionary might be a better way to do this.

outputs = {
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four"
}

var = int(input("Enter a number: "))

print outputs[var]
Bill
  • 10,323
  • 10
  • 62
  • 85
0

Try this, it is a little better and will not raise KeyError if get a bad option:

outputs = {
    1: "One",
    2: "Two",
    3: "Three",
    4: "Four",
    'default': 'bad option' 
}
try:
    var = int(input("Enter a number: "))
except ValueError:
    print(outputs.get('default'))        
else:
    print(outputs.get(var, 'bad option'))

Read here to learn more about try except else.

Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59
  • probably don't need `else`, the line can be put directly after the input line - if a ValueError is raised, it won't be reached – iBug Sep 29 '18 at 06:24
0

Another approach without using dictionaries could be:

command = ["One", "Two", "Three", "Four"]
try:
    print(command[val-1])
except:
    print('Invalid option')
toti08
  • 2,448
  • 5
  • 24
  • 36