[Tutor] split struggle

Peter Otten __peter__ at web.de
Wed Jun 23 16:46:41 CEST 2010

Richard D. Moores wrote:

> Please see my Python 3.1 code pasted at
> <http://python.pastebin.com/T3vm9vKT>.
> This does what I want, which is to do one of:
> 1. print all the elements of the list, lst.
> 2. print "Done" when "" is entered.
> 3. print the elements of lst whose indexes are entered.
> (sorry if all this is obvious)
> Now, the code works, but isn't there a better way to do what I want?
> I've been away from Python for a while, and have gotten rusty.

Although the code gets slightly more complex having a look at the cmd module 
may be worthwhile. Once you have set up the bases you can add commands by 
adding a do_xxx() method assuming 'xxx' is the name of the command. Tab 
completion works (for commands) and you get a rudimentary help function for 

$ cat indexes.py
import cmd

class Cmd(cmd.Cmd):
    prompt = "Enter a command -> "
    def precmd(self, line):
        if line.strip().isdigit():
            # treat a lone integer as a shortcut
            # for the 'one' command
            return "one " + line
        if not line:
            return "EOF"
        return line
    def do_all(self, line):
        "print all items"
        for i, item in enumerate(items):
    def do_one(self, line):
        i = int(line)
    def do_EOF(self, line):
        print("That's all, folks")
        return True

items = [100,101,102,103]

def print_item(i):
    print(i, "->", items[i])

Cmd().cmdloop("Enter a command or type 'help' for help")
$ python3 indexes.py
Enter a command or type 'help' for help
Enter a command -> help

Documented commands (type help <topic>):

Undocumented commands:
EOF  help  one

Enter a command -> one 1
1 -> 101
Enter a command -> help all
print all items
Enter a command -> all
0 -> 100
1 -> 101
2 -> 102
3 -> 103
Enter a command -> 3
3 -> 103
Enter a command ->
That's all, folks

More information about the Tutor mailing list