on writing a while loop for rolling two dice

Chris Angelico rosuav at gmail.com
Sat Aug 28 17:41:21 EDT 2021


On Sun, Aug 29, 2021 at 7:37 AM Hope Rouselle <hrouselle at jevedi.com> wrote:
>
> How should I write this?  I'd like to roll two six-sided dice until I
> get the same number on both.  I'd like to get the number of times I
> tried.  Here's a primitive I'm using:
>
> --8<---------------cut here---------------start------------->8---
> >>> x, y = roll()
> >>> x
> 6
> >>> y
> 6 # lucky
>
> >>> x, y = roll()
> >>> x
> 4
> >>> y
> 1 # unlucky
> --8<---------------cut here---------------end--------------->8---
>
> 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)
> --8<---------------cut here---------------end--------------->8---
>
> 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?  Thank you!

Your loop, fundamentally, is just counting. So let's just count.

def how_many_times():
    for c in itertools.count():
        ...

Inside that loop, you can do whatever you like, including returning
immediately if you have what you want. I'll let you figure out the
details. :)

ChrisA


More information about the Python-list mailing list