Question

I am taking a beginning Python programming class and I am having trouble getting the code below to work correctly. The assignment asks: write a Python code that uses the “strftime()” function to get the today’s weekday value and then use an “if..elif..else” statement to display the associated message. So, with today being Friday (w == 5) for me, it should print "Prevention is better than cure." Instead, it keeps printing the else statement "Stupid is as stupid does." Advice?

import datetime

t = datetime.date.today()
w = t.strftime("%w"); # day of week

if (w == 0): print("The devil looks after his own.");
elif (w == 1): print("Everything comes to him who waits.");
elif (w == 2): print("Give credit where credit is due.");
elif (w == 3): print("If you pay peanuts, you get monkeys.");
elif (w == 4): print("Money makes the world go round.");
elif (w == 5): print("Prevention is better than cure.");
else: print("Stupid is as stupid does.");
Was it helpful?

Solution

Instead of using strftime(), which returns a str, use weekday(), which returns an int:

t = datetime.date.today()
w = today.weekday() + 1  # +1 because weekday() is 0-based, %w is 1-based

In Python, a string and a number are never equal.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top