tags:

views:

734

answers:

6

Hi.

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

Thanks

+2  A: 

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()
Gonzalo Quero
+1: Python "switch" is spelled "if"; "case" is spelled "elif".
S.Lott
+2  A: 

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

kgiannakakis
+5  A: 

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)()
Ali A
A: 

How can I do a exit? In c my Menus are like:

do { printf "Menu"

Swith case statment

}

while (option < 8)

so when I put an 8 I exit from my program... How can I do that here in python? How can I exit from the program?

UcanDoIt
Consider creating a new question rather than writing a question in a comment in Stack Overflow.
Matthew Schinckel
A: 

To your first question I agree with Ali A.

To your second question :

import sys
sys.exit(1)

ggambett
+8  A: 

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.

Paul Fisher