[英]Python (if, elif, else) working with timestamp
I am taking a beginning Python programming class and I am having trouble getting the code below to work correctly. 我正在学习Python入门编程课程,但无法获取下面的代码才能正常工作。 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.
作业要求:编写一个Python代码,该代码使用“ strftime()”函数获取今天的工作日值,然后使用“ if..elif..else”语句显示关联的消息。 So, with today being Friday (w == 5) for me, it should print "Prevention is better than cure."
因此,对于我来说今天是星期五(w == 5),它应打印“预防胜于治疗”。 Instead, it keeps printing the else statement "Stupid is as stupid does."
相反,它将继续打印else语句“愚蠢与愚蠢”。 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.");
Instead of using strftime()
, which returns a str
, use weekday()
, which returns an int
: 代替使用返回一个
str
strftime()
,而使用一个返回int
weekday()
:
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. 在Python中,字符串和数字从不相等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.