+ 2

Alternative to numerous elif statements

In my code to figure out the weekday you were born: https://code.sololearn.com/cTQv78rqK1mR I need numerous elif statements to match the integer-version of the day to a string. Is there a more elegant, "pythonic" way of doing so?

1st Aug 2017, 8:45 AM
Martin Ed
Martin Ed - avatar
3 ответов
+ 10
This is probably how I would have wrote it: arr = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] if weekday >= 0 and weekday <= 6: print("It was a ", end = '') print(arr[weekday])
1st Aug 2017, 9:02 AM
Hatsy Rei
Hatsy Rei - avatar
+ 2
I just figured out that probably a dictionary works best here: weekdays = { 0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday", 4: "Friday", 5: "Saturday", 6: "Sunday"} print("It was a ", weekdays[weekday])
1st Aug 2017, 9:44 AM
Martin Ed
Martin Ed - avatar
+ 1
@Hatsy Rei - Thanks! That seems to be indeed the ideal solution here
1st Aug 2017, 10:48 AM
Martin Ed
Martin Ed - avatar