Python(if,elif,else)使用时间戳

2024-03-28 18:40:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在上一个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.");

Tags: 函数代码youdatetimeifis编程语句
1条回答
网友
1楼 · 发布于 2024-03-28 18:40:00

不要使用返回strstrftime(),而是使用返回intweekday()

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

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

相关问题 更多 >