PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, November 25, 2022

[FIXED] Why is "and" operator not working in my python program?

 November 25, 2022     date, module, python, python-3.x, time     No comments   

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
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing