on writing a while loop for rolling two dice
Hope Rouselle
hrouselle at jevedi.com
Thu Sep 2 10:42:24 EDT 2021
David Raymond <David.Raymond at tomtom.com> writes:
>> def how_many_times():
>> x, y = 0, 1
>> c = 0
>> while x != y:
>> c = c + 1
>> x, y = roll()
>> return c, (x, y)
>
> Since I haven't seen it used in answers yet, here's another option using our new walrus operator
>
> def how_many_times():
> roll_count = 1
> while (rolls := roll())[0] != rolls[1]:
> roll_count += 1
> return (roll_count, rolls)
That's nice, although it doesn't seem more readable to a novice seeing a
while for the first time, seeing a loop for the first time, than that
while-True version. In fact, I think the while-True is the clearest so
far. But it's always nice to spot a walrus in the wild! (If you're
somewhere safe, that is.)
More information about the Python-list
mailing list