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


Asked by: Chelsea934 | Posted: 05-10-2021






Answer 1

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.

Answered by: Julian439 | Posted: 06-11-2021



Answer 2

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)()

Answered by: Walter472 | Posted: 06-11-2021



Answer 3

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()

Answered by: Chelsea673 | Posted: 06-11-2021



Answer 4

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

Answered by: Julian629 | Posted: 06-11-2021



Answer 5

To your first question I agree with Ali A.

To your second question :

import sys
sys.exit(1)

Answered by: Roman630 | Posted: 06-11-2021



Answer 6

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.

Answered by: Byron849 | Posted: 06-11-2021



Similar questions

python - Haystack Whoosh Spelling Suggestion too greedy

This questions is about Django Haystack, with Whoosh backend. I would like to use spelling suggestion in my search. The problem is that it is suggesting TOO much. Say I have two models: Apples and Oranges. If I have somethine like this: result = SearchQuerySet().models(Apples).filter( content=escaped_value).spelling_suggestion(escaped_value) it will actually LOOK into O...


python lottery suggestion

I know python offers random module to do some simple lottery. Let say random.shuffle() is a good one. However, I want to build my own simple one. What should I look into? Is there any specific mathematical philosophies behind lottery? Let say, the simplest situation. 100 names and generate 20 names randomly. I don't want to use shuffle, since I want to learn to build one myself. I need some ...


pep - how can I make a suggestion for a new feature in python

Suppose I think I have a great idea for some feature that should be in python's standard library. Not something of the magnitude of a new keyword etc, just a suggestion for another decorator that would help a lot, IMO. How can I suggest such a feature to the consideration of the "python committee :)"?


IDE Suggestion for python and javascript

Closed. This question does not meet Stack Overflow guid...


Anyway to bring up suggestion box when typing python code

I'm learning wxpython right now and one thing that helps me ALOT is when I'm typing in the text editor I sometimes press the tab key to give me a hint on what I'm looking for...This is great when it works but I notice sometimes it doesn't work and I get lost looking for a syntax I can't remember... Question is how can I get the suggestion box to pop back up again, Or what am I doing that causes it to stop coming up...


I need a neat data structure suggestion to store a very large dataset (to train Naive Bayes in Python)

I am going to implement Naive Bayes classifier with Python and classify e-mails as Spam or Not spam. I have a very sparse and long dataset with many entries. Each entry is like the following: 1 9:3 94:1 109:1 163:1 405:1 406:1 415:2 416:1 435:3 436:3 437:4 ... Where 1 is label (spam, not spam), and each pair corresponds to a word and its frequency. E.g. 9:3 corresponds to the word 9 and it occurs 3 times in...


suggestion on tkinter for python 3.X

first of all my apology if you find this topic redundant....but I need some specific answers from you..thats why I have made this. I have recently start learning tkinter for python. But I cant decide which route to take . Every tutorial comes up with a new approach which is confusing. So I need to know: 1.Which part of tkinter should I study first ?? 2.what knowledge should I have before start tkin...


json - Python web framework suggestion for a web service


python - Suggestion on creation app for getting information from webpage

First want to say that I have experience with python and some web libraries like mechanize, beautiful soup, urllib2. The idea is to create an app that will grab information from webpage, that I currently looking on in webbrowser. And than store it. For example: I manually go to the website, create a user. Than run my app, that will grab some details from webpage, that I'm currently looking on. like user nam...


python - Clipping raster image with a polygon, suggestion to resolve an error related to use 16 bit image instead of 8 bit image

I am clipping an raster image (Erdas Imagine Images, *.img) using a polygon (shapefile, *.shp) following example Clip a Raster using a Shapefile. Following the example i have the Error: Traceback (most recent call last): File "<interactive input>", line 1, in <module> IndexError: too ...






Still can't find your answer? Check out these communities...



PySlackers | Full Stack Python | NHS Python | Pythonist Cafe | Hacker Earth | Discord Python



top