+ 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?
3 Antworten
+ 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])
+ 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])
+ 1
@Hatsy Rei - Thanks!
That seems to be indeed the ideal solution here