I have written these simple lines of code to get the current day name, and then using if/else statement wanted to check if it is the current day which is Sunday,and I should receive my if suite , because today is exactly Sunday, but the terminal gives me the else suite. I was wonder what is wrong with my code:
import datetime
now= datetime.datetime.now()
weeks=["Saturday","Sunday","Monday","Tuesday","Wednesday"]
print ("Today is {}, So:".format(now.strftime("%A")))
if now in weeks:
print("Gossh, You are now in your school days..")
else:
print("rest and recover!")
and the result is:
Today is Sunday, So:
rest and recover!
>Solution :
You are testing if now (a datetime object) is in weeks (string objects). now is not in weeks. No datetime object is in weeks
The formatted day name (now.strftime("%A")) might be, but you’re not testing that.
from datetime import datetime
now = datetime.now()
dayname = now.strftime("%A")
weekdays = ["Saturday", "Sunday", "Monday", "Tuesday", "Wednesday"]
print(f"Today is {dayname}, so:")
if dayname in weekdays:
print("Gossh, You are now in your school days...")
else:
print("rest and recover!")
That being said, both weeks and weekdays is a bad name for a variable that contains this particular list of day names. Find a better variable name.