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> 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)
>
>
> Ooops.  I made a mistake.  ask_for_a_digit() is not technically quite
> right, because I forgot that when we're doing the expression:
>
>     digit not in "0123456789"
>
> that this is technically checking that the left side isn't a substring
> of the right side.  That's not what I wanted: I intended to check for
> element inclusion instead.  So there are certain inputs where the
> buggy ask_for_a_digit() won't return an integer with a single digit.
>
> Here's one possible correction:
>
> ###################################################
> def ask_for_a_digit():
>     while True:
>         digit = raw_input("Give me a digit between 0 and 9.")
>         if len(digit) != 1 or digit not in "0123456789":
>             print "You didn't give me a digit.  Try again."
>         else:
>             return int(digit)
> ###################################################
>
>
> My apologies for not catching the bug sooner.
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
>
_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to