on writing a while loop for rolling two dice

Peter J. Holzer hjp-python at hjp.at
Sat Sep 4 06:05:32 EDT 2021


On 2021-09-02 11:28:21 -0300, Hope Rouselle wrote:
> dn <PythonList at DancesWithMice.info> writes:
> > On 29/08/2021 08.46, Hope Rouselle wrote:
> >> Here's my solution:
> >> 
> >> --8<---------------cut here---------------start------------->8---
> >> def how_many_times():
> >>   x, y = 0, 1
> >>   c = 0
> >>   while x != y:
> >>     c = c + 1
> >>     x, y = roll()
> >>   return c, (x, y)
> >
> >> 
> >> Why am I unhappy?  I'm wish I could confine x, y to the while loop.
> >> The introduction of ``x, y = 0, 1'' must feel like a trick to a
> >> novice.  How would you write this?
[...]
> But perhaps we may agree that while rolling dice until a certain
> success, we want to roll them while something happens or doesn't happen.
> One of the two.  So while-True is a bit of a jump.  Therefore, in this
> case, the easier and more natural option is to say while-x-not-equal-y.
> 
> But this approach seems to force me into initializing x, y with
> different values.

You can get around this by using NaN:

def how_many_times():
  c, x, y = 0, math.nan, math.nan
  while x != y:
    c = c + 1
    x, y = roll()
  return c, x, y

Not sure if this is an improvement. Now you have to explain to your
students why math.nan != math.nan.

When I need a guaranteed unique value I often just use object():

def how_many_times():
  c, x, y = 0, object(), object()
  while x != y:
    c = c + 1
    x, y = roll()
  return c, x, y

Of course now you are back to two different values, but they look the
same. Which may be better or worse for your students. Plus x and y are
now bound to objects of different types during their lifetime, which may
be a bit dicey.

        hp


-- 
   _  | Peter J. Holzer    | Story must make more sense than reality.
|_|_) |                    |
| |   | hjp at hjp.at         |    -- Charles Stross, "Creative writing
__/   | http://www.hjp.at/ |       challenge!"
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 833 bytes
Desc: not available
URL: <https://mail.python.org/pipermail/python-list/attachments/20210904/e9b22313/attachment.sig>


More information about the Python-list mailing list