My task is to define a function weekdays(weekday)
that returns a list of weekdays, starting with the given weekday. It should work like this:
>>> weekdays('Wednesday')
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
So far I've come up with this one:
def weekdays(weekday):
days = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday',
'Sunday')
result = ""
for day in days:
if day == weekday:
result += day
return result
But this prints the input day only:
>>> weekdays("Sunday")
'Sunday'
What am I doing wrong?
The weekday() method is used to returns the day of the week (0 is Monday) for year (1970–...), month (1–12), day (1–31). Year for which the calendar should be generated. month for which the calendar should be generated.
You can use datetime. timedelta for that. It has an optional weeks argument, which you can set to -1 so it will subtract seven days from the date . You will also have to subract the current date's weekday (and another one, to even the day since the Monday is 0 ).
You can find the next Monday's date easily with Python's datetime library and the timedelta object. You just need to take today's date. Then subtract the number of days which already passed this week (this gets you 'last' monday).
Your result
variable is a string
and not a list
object. Also, it only gets updated one time which is when it is equal to the passed weekday
argument.
Here's an implementation:
import calendar
def weekdays(weekday):
days = [day for day in calendar.day_name]
for day in days:
days.insert(0, days.pop()) # add last day as new first day of list
if days[0] == weekday: # if new first day same as weekday then all done
break
return days
Example output:
>>> weekdays("Wednesday")
['Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday']
>>> weekdays("Friday")
['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
>>> weekdays("Tuesday")
['Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday', 'Monday']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With