Home > OS >  Why is "and" operator not working in my python program?
Why is "and" operator not working in my python program?

Time:08-28

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

CodePudding user response:

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.

CodePudding user response:

First, I advise you to store your value in a variable:

t = int(gt.now.strftime("%H"))

This way, you won't have to recompute a value multiple times, and probably different values each time. (Pedantically, if executed at border times, it could even make for a situation where none of the ifs will be executable.)

Then your logic would be more readable:

if t < 12:
    print("Good Morning, Rudra!")
elif t >= 12 and t < 17:
    print("Good Afternoon, Rudra!")
elif t >= 17 and t < 0:
    print("Good Evening, Rudra!")

The last conditions attached by and would never be true together. You probably meant before midnight by t < 0, but it doesn't make sense here. Leave it out so that your if conditions will be both disjoint and inclusive.

  • Related