Please don't top-post. Put your response under the quote you're responding to. And trim the parts that are no longer relevant. I've rearranged this message to try to pretend that you did that.

> On Wed, Nov 26, 2014 at 3:46 PM, Alan Gauld <alan.ga...@btinternet.com>
> wrote:
>
>> On 26/11/14 09:57, Sunil Tech wrote:
>>
>>> Hi Danny,
>>>
>>> Curious to the use the need of using while True in the given example of
>>> ask_for_a_digit().
>>>
>>>
>>> On Mon, Nov 17, 2014 at 9:57 AM, Danny Yoo <d...@hashcollision.org
>>> <mailto:d...@hashcollision.org>> wrote:
>>>
>>>      > def ask_for_a_digit():
>>>      >     while True:
>>>      >         digit = raw_input("Give me a digit between 0 and 9.")
>>>      >         if digit not in "0123456789":
>>>      >             print "You didn't give me a digit.  Try again."
>>>      >         else:
>>>      >             return int(digit)
>>>
>>
>> The while loop makes it keep on asking until a valid input is
>> received. Without the while loop it would only ask once and
>> either return None or a digit.
>>


On 11/26/2014 06:16 AM, Sunil Tech wrote:
Thank you Alan. But a question here, how would it understand that the given
input is valid?


Inside the while loop there is a else clause containing a return statement. That's how the code escapes the while loop: whenever the user enters something deemed correct.

More traditionally, a break will exit a loop. Or the while can contain a more complex condition. Example of that, untested:

def ask_for_a_digit()
    digit = "xxx"
    while len(digit) != 1   or  digit not in "0123456789":
        digit = raw_input("Give me a digit between 0 and 9.")

Unfortunately, this form doesn't include the "chiding" of the user. That's more painful, but it can be done.

def ask_for_a_digit()
    digit = ()
    while len(digit) != 1   or  digit not in "0123456789":
        if digit = (): print "You didn't give me a digit.  Try again"
        digit = raw_input("Give me a digit between 0 and 9.")




--
DaveA
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to