CreativeGuy888
CreativeGuy888

Reputation: 38

Python integer input to corresponding command value

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.

Upvotes: 0

Views: 66

Answers (3)

toti08
toti08

Reputation: 2464

Another approach without using dictionaries could be:

command = ["One", "Two", "Three", "Four"]
try:
    print(command[val-1])
except:
    print('Invalid option')

Upvotes: 0

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11083

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.

Upvotes: 0

Bill
Bill

Reputation: 11633

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]

Upvotes: 2

Related Questions