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

Discussão em 'Python' iniciado por Stack, Junho 20, 2025.

  1. Stack

    Stack Membro Participativo

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

    Continue reading...

Compartilhe esta Página