Issue
The following is my code:
import greettime as gt
if int(gt.now.strftime("%H")) < 12:
print("Good Morning, Rudra!")
elif int(gt.now.strftime("%H")) >= 12 and int(gt.now.strftime("%H")) < 17:
print("Good Afternoon, Rudra!")
elif int(gt.now.strftime("%H")) >= 17 and int(gt.now.strftime("%H")) < 0:
print("Good Evening, Rudra!")
print(int(gt.now.strftime("%H")))
and the file named greettime is:
import datetime as dt
now = dt.datetime.now()
This code is not producing any output.It is producing output if the "and" part is commented out. What is the error here? I am a student and learning python therefore asking for pardon if there is a presence of any simple silly mistake
Solution
Your code compares the time so that it's...
* less than 12
* greater than-equal to 12 and less then 17
* greater than-equal to 17 and less than 0
That last condition doesn't work because how is a number going to be greater than 17 and also less than 0? It doesn't work, and Python datetime
also only supports hours from 0..23
.
If you just to print Good Morning
if it's midnight - noon, then Good Afternoon
from noon to 5 PM, and then Good Evening
otherwise, you can just do this and scrap the final comparison cases and replace it with a bare else
, because you've already covered morning and afternoon hours.
from datetime import datetime
now = datetime.now()
if now.hour < 12:
print("Good Morning, Rudra!")
elif now.hour >= 12 and now.hour < 17:
print("Good Afternoon, Rudra!")
else:
print("Good Evening, Rudra!")
print(now.hour)
You'll also notice I got rid of your strftime
conversions because you can access the hour
property on datetime
objects directly.
Answered By - wkl
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.