[Tutor] input with default value option
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Tue Apr 11 08:38:20 CEST 2006
> With raw_input(), it allows to input value. Can it be used to input
> value with default value option?
Hi Phon,
We can build your own function to do this. Bob showed how to set up code
so that the default's taken if the user just presses enter in his reply.
Let's take a look at it again:
###########################################
response = raw_input("Enter some data:")
if not response: response = "default value"
###########################################
We can capture this as a function that takes in a question and a default
answer:
##################################
def ask(question, default):
response = raw_input(question)
if not response:
response = default
return response
##################################
And now we have something that acts like raw_input(), but also gives the
user the ability to get a default:
######
>>> ask("favorite color?", "Blue. No yellow -- aaaugh!")
favorite color?red
'red'
>>> ask("favorite color?", "Blue. No yellow -- aaaugh!")
favorite color?
'Blue. No yellow -- aaaugh!'
>>>
######
(In the second call to ask(), I just pressed enter.)
Does this make sense?
More information about the Tutor
mailing list