Python(if、elif、else)处理时间戳

0 投票
1 回答
1868 浏览
提问于 2025-04-17 21:20

我正在上一个初学者的Python编程课程,但我在让下面的代码正常工作上遇到了问题。作业要求是:写一段Python代码,使用“strftime()”函数来获取今天是星期几的值,然后用“if..elif..else”语句来显示相应的消息。所以,今天是星期五(w == 5),它应该打印“预防胜于治疗。”但是,它一直在打印else语句“愚蠢的行为就是愚蠢。”有什么建议吗?

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.");

1 个回答

0

与其使用 strftime() 这个函数,它会返回一个字符串(str),不如使用 weekday() 这个函数,它会返回一个数字(int):

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

在Python中,字符串和数字是永远不相等的。

撰写回答