on writing a while loop for rolling two dice
Hope Rouselle
hrouselle at jevedi.com
Sat Aug 28 08:00:27 EDT 2021
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!
More information about the Python-list
mailing list