UcanDoIt
UcanDoIt

Reputation: 1845

Suggestion to implement a text Menu without switch case

I'm giving my first steps on Python. I saw that we don't have switch case statement, so I would you guys implement a text Menu in python?

Thanks

Upvotes: 3

Views: 6135

Answers (6)

Gerry
Gerry

Reputation: 11194

I came here looking for the same thing and ended up writing my own: https://github.com/gerrywastaken/menu.py

You call it like so:

import menu

message = "Your question goes here"
options = {
    'f': ['[F]irst Option Name', 'First value'],
    's': ['[S]econd Option Name', 'Second value'],
    't': ['[T]hird Option Name', 'Third value']
}

selection = menu.getSelection(message, options)

It presents the user with a menu and they can select the option they want via the characters in the brackets. If they entered "s" as their option then selection would be assigned the value of 'Second Value'. I could have made it fancier, but I wanted to keep things simple, although pull requests are very welcome.

Upvotes: 0

Paul Fisher
Paul Fisher

Reputation: 9666

You might do something like this:

def action1():
    pass # put a function here

def action2():
    pass # blah blah

def action3():
    pass # and so on

def no_such_action():
    pass # print a message indicating there's no such action

def main():
    actions = {"foo": action1, "bar": action2, "baz": action3}
    while True:
        print_menu()
        selection = raw_input("Your selection: ")
        if "quit" == selection:
            return
        toDo = actions.get(selection, no_such_action)
        toDo()

if __name__ == "__main__":
    main()

This puts all your possible actions' functions into a dictionary, with the key being what you will input to run the function. It then retrieves the action input action from the list, unless the input action doesn't exist, in which case it retrieves no_such_action.

After you have a basic understanding of how this works, if you're considering doing a Serious Business command-line–type application, I would look at the cmd framework for command-line applications.

Upvotes: 15

ggambetta
ggambetta

Reputation: 3433

To your first question I agree with Ali A.

To your second question :

import sys
sys.exit(1)

Upvotes: 0

Ali Afshar
Ali Afshar

Reputation: 41663

Generally if elif will be fine, but if you have lots of cases, please consider using a dict.

actions = {1: doSomething, 2: doSomethingElse}
actions.get(n, doDefaultThing)()

Upvotes: 5

kgiannakakis
kgiannakakis

Reputation: 104188

Have a look at this topic from "An Introduction to Python" book. Switch statement is substituted by an if..elif..elif sequence.

Upvotes: 2

Gonzalo Quero
Gonzalo Quero

Reputation: 3323

You can use if...elif. If you have to choose a number, it would be like this:

n = chosenOption()
if(n == 0):
    doSomething()
elif(n == 1):
    doAnyOtherThing()
else:
    doDefaultThing()

Upvotes: 2

Related Questions