Implement C's Switch in Python 3

Frank Millman frank at chagford.com
Sun Feb 3 02:14:46 EST 2019


"Sayth Renshaw"  wrote in message 
news:73a1c64c-7fb1-4fc8-98a2-b6939e82a0b7 at googlegroups.com...

>>> chooseFrom = { day : nthSuffix(day) for day in range(1,32)}
>>> chooseFrom
{1: '1st', 2: '2nd', 3: '3rd', 4: '4th', 5: '5th', 6: '6th', 7: '7th', 8:
'8th', 9: '9th', 10: '10th', 11: '11th', 12: '12th', 13: '13th', 14: '14th',
15: '15th', 16: '16th', 17: '17th', 18: '18th', 19: '19th', 20: '20th', 21:
'21st', 22: '22nd', 23: '23rd', 24: '24th', 25: '25th', 26: '26th', 27:
'27th', 28: '28th', 29: '29th', 30: '30th', 31: '31st'}
>>> chooseFrom[1]
'1st'
>>> chooseFrom[11]
'11th'
>>> chooseFrom[21]
'21st'

> Not having a default case as in switch forced you to write out all 
> possible combinations.

> I think the intent and readbility of switch statements is a bit nicer.

I have not been following this thread in detail, but how about this -

>>> choose = {1: 'st', 2: 'nd', 3: 'rd', 21: 'st', 22: 'nd', 23: 'rd', 31: 
>>> 'st'}
>>> for x in range(1, 32):
...   print('{}{}'.format(x, choose.get(x, 'th')), end = ' ')
...
1st 2nd 3rd 4th 5th 6th 7th 8th 9th 10th 11th 12th 13th 14th 15th 16th 17th 
18th 19th 20th 21st 22nd 23rd 24th 25th 26th 27th 28th 29th 30th 31st >>>

Frank Millman





More information about the Python-list mailing list