0

I'm a total noob in Python and I'm currently reading a script provided by a colleague. I got confused with the below script having it run today.

import datetime

today=datetime.date.today() - datetime.timedelta(days=4)
print (today)

if today.weekday() in [range(0,7)]:
    saturday=today-datetime.timedelta(today.weekday()-5)
    sunday=today-datetime.timedelta(today.weekday()-6)
else:
    saturday=today-datetime.timedelta(today.weekday()+2)
    sunday=today-datetime.timedelta(today.weekday()+1)

print (saturday)
print (sunday)
print (today.weekday())

Below is the result:

2018-07-19
2018-07-14
2018-07-15
3

Why is the script executing the one in else-statement? The today.weekday() results to 3 which should've executed the if-statement since 3 is within the range which if manually computed saturday = 2018-07-21.

Kindly advise where I have it understood incorrectly.

1
  • Using the correction from @Piotrek or @ThatBird, please note that today.weekday() in range(0,7) will always evaluate to True so the else statement is not reachable Commented Jul 23, 2018 at 9:04

2 Answers 2

2

In this line -

if today.weekday() in [range(0,7)]

range() already gives you a list but in this case, it is a list of list and you get something like -

[[0, 1, 2, 3, 4, 5, 6]]

And as you see, 3 is not in [[0, 1, 2, 3, 4, 5, 6]]

But if it were something like -

[[0, 1, 2, 3, 4, 5, 6], 3] #then it would have been true

Remove the brackets and make it this -

if today.weekday() in range(0,7)

And it should work

Sign up to request clarification or add additional context in comments.

2 Comments

Hi! Thank you for explaining this to me. If I proceed with your instruction, when will the above script execute the else statement? Isn't each day assigned an integer from 0 to 7? If so, it will always execute the if statement, right?
@Janine you are right. It won't go in else statement
1

Change

if today.weekday() in [range(0,7)]:

to:

if today.weekday() in range(0,7):

and it will work properly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.