Kimmo Hintikka Kimmo Hintikka - 7 days ago 7
Python Question

How mitigate the lack of Switch/Case statements in Python?

What is the good way to handle cases like below in Python? I would use Switch/Case break pattern in Java, but not sure what is the best way in Python.

The code below simply simulates 6 sided die rolls and prints their occurrences in 10000 rolls. My

if else
solution does work, but simply looks awful, so advice for a better solution would be much appreciated.

from random import randint

i = 0
ii = 0
iii = 0
iv = 0
v = 0
vi = 0

for trial in range(0, 10000):
die = randint(1, 6)
if die == 1:
i += 1
elif die == 2:
ii += 1
elif die == 3:
iii += 1
elif die == 4:
iv += 1
elif die == 5:
v += 1
else:
vi += 1

print("i = {}, ii = {}, iii = {}, iv = {}, v = {}, vi = {}"
.format(i, ii, iii, iv, v, vi))

Answer

just don't define 6 variables but a list:

from random import randint

rolls = [0]*6

for trial in range(0, 10000):
    die = randint(1, 6)
    rolls[die-1] += 1

print("i = {}, ii = {}, iii = {}, iv = {}, v = {}, vi = {}"
      .format(*rolls))

note the nice argument passing to format using *.

Comments