osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Implement C's Switch in Python 3


Hi

I am trying to convert a switch statement from C into Python. (why? practising).

This is the C code. 

printf("Dated this %d", day);
  switch (day) {
    case 1: case 21: case 31:
        printf("st"); break;
    case 2: case 22:
        printf("nd"); break;
    case 3: case 23:
        printf("rd"); break;
    default: printf("th"); break;
    
  }
  printf(" day of ");

#Premise if the use enter an int as the date 21 for example it would print 21st. It appends the correct suffix onto a date.

Reading and trying to implement a function that uses a dictionary. Not sure how to supply list into it to keep it brief and with default case of 'th'.

This is my current code.

def f(x):
    return {
        [1, 21, 31]: "st",
        [2, 22]: "nd",
        [3, 23]: "rd",
    }.get(x, "th")


print(f(21))

I have an unhashable type list. Whats the best way to go?

Cheers

Sayth