Kimmo Hintikka
Kimmo Hintikka

Reputation: 15410

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))

Upvotes: 0

Views: 134

Answers (3)

Phillip Martin
Phillip Martin

Reputation: 1960

For a more generalized case, you could use a dictionary. How is this useful at all? Well, lets say you want random numbers between 1001 and 1006, instead of 1 and 6. Using a list, you would have to add 1000 placeholders. This is not necessary when using a dictionary.

from random import randint

rolls = {
    1001: 0,
    1002: 0,
    1003: 0,
    1004: 0,
    1005: 0,
    1006: 0
}

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

print("1001 = {}, 1002 = {}, 1003 = {}, 1004 = {}, 1005 = {}, 1006 = {}"
      .format(rolls[1001], rolls[1002], rolls[1003], rolls[1004], rolls[1005], rolls[1006]))

Upvotes: 0

TheClonerx
TheClonerx

Reputation: 343

There are a lots of questions like this

You can do this easily enough with a sequence of if... elif... elif... else. There have been some proposals for switch statement syntax, but there is no consensus (yet) on whether and how to do range tests. See PEP 275 for complete details and the current status.

For cases where you need to choose from a very large number of possibilities, you can create a dictionary mapping case values to functions to call. For example:

def function_1(...):
    ...


functions = {'a': function_1,
             'b': function_2,
             'c': self.method_1, ...}

func = functions[value] 
func()

from Why isn’t there a switch or case statement in Python?

Upvotes: 2

Jean-François Fabre
Jean-François Fabre

Reputation: 140148

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 *.

Upvotes: 6

Related Questions