Providing 'default' value with raw_input()?

Steve Holden steve at holdenweb.com
Thu Dec 22 12:15:46 EST 2005


planetthoughtful wrote:
> Hi All,
> 
> As always, my posts come with a 'Warning: Newbie lies ahead!'
> disclaimer...
> 
> I'm wondering if it's possible, using raw_input(), to provide a
> 'default' value with the prompt?
> 
> I would like to include the ability to edit an existing value (drawn
> from an SQLite table) using a DOS console Python app, but my gut
> feeling from reading what I can find about raw_input() is that it only
> allows you to provide a prompt, not a default value as well.
> 
> If anyone can give me any advice on how I might achieve this, I would
> be immensely appreciative!
> 
> Many thanks and much warmth,
> 
> planetthoughtful
> 
You need to define your own function, with a default argument that gives 
the value. You can make it work just like raw_input if no default value 
is provided. Something like:

  >>> def raw_default(prompt, dflt=None):
  ...   if dflt:
  ...     prompt = "%s [%s]: " % (prompt, dflt)
  ...   res = raw_input(prompt)
  ...   if not res and dflt:
  ...     return dflt
  ...   return res
  ...
  >>> raw_default("How many beans make five", '5')
How many beans make five [5]: six
'six'
  >>> raw_default("How many beans make five")
How many beans make fiveten
'ten'
  >>> raw_default("How many beans make five", '5')
How many beans make five [5]:
'5'

regards
  Steve
-- 
Steve Holden       +44 150 684 7255  +1 800 494 3119
Holden Web LLC                     www.holdenweb.com
PyCon TX 2006                  www.python.org/pycon/




More information about the Python-list mailing list