Providing Default Value for User Input

Francis Avila francisgavila at yahoo.com
Sat Jan 10 23:30:17 EST 2004


N?ant Humain wrote in message ...
>I have just begun learning Python so that I can write a simple script
>to make modification of a file used by another Python script easier.
>This file is basically a list of regular expressions. What I want to
>do is allow the user to select one of these regular expressions to
>modify, but I've realized I know of no way to provide a default value
>for user input. I could choose to show the regular expression the user
>has chosen and simply allow the user to retype it and modify it from
>there, but that is time consuming and error prone. Does Python support
>a way to do this? If worse comes to worst, is there a way I could
>write such code on my own without having to write a C-based module
>(I'd like to stick to Python code only since some users will be
>running this script on Windows without a C compiler)?

This question is entirely too vague, because the answer depends entirely
upon your implementation and has nothing to do with Python per se.  I
imagine the answer is pretty simple unless your design is horrible.

As a shot in the dark, why not just look at what the user types?  If it's
something you want to interpret as 'use default' (like just an empty line,
or the letter 'd' or something), then use a default!

E.g.:

choices = dict(a=1, b=2, default=100)
while True:
    print 'Please select:'
    for k,v in choices.items():
        print '%-10s%s' % (k,v)
    input = raw_input('?> ').lower()
    if input == 'd':
        input = 'default'
    try:
        print 'Value of %s is %s' % (input, choices[input])
    except KeyError:
        print 'Item %r not found.' % input
    print


If you're doing a lot of command-oriented input loops, look at the cmd
module, which is pretty handy (I use it quite a bit).
--
Francis Avila





More information about the Python-list mailing list