Header Ads

Write a program that asks the user for their name and greets them with their name.

 Question Source

In this program we will ask the user for his/her name and greet the user according to the time. We will get the current time by using datetime module. Then we will define a greets(nam) function which will do all the processing to greet the user

Code:

from datetime import datetime


def greets(nam):
tim = datetime.now()
mor = tim.replace(hour=5, minute=0, second=0)
mid = tim.replace(hour=12, minute=0, second=0)
eve = tim.replace(hour=18, minute=0, second=0)
nig = tim.replace(hour=23, minute=0, second=0)
if mor <= tim < mid:
print("Good Morning", nam)
elif mid <= tim < eve:
print("Good Afternoon", nam)
elif eve <= tim < nig:
print("Good Evening", nam)
else:
print("Good Night", nam, "\nYou should sleep now")


name = input("Enter your Name : ")
greets(name)

Output:

at 8:11 P.M

Enter your Name : Abhi
Good Evening Abhi

at 11:14 P.M

Enter your Name : Abhi
Good Night Abhi 
You should sleep now

Explanation:

The time at which i have executed this program is 8:11 P.M and 11:14 P.M, according to that i got a output 
'Good Evening Abhi' and 
'Good Night Abhi 
You should sleep now' respectively
 if-else ladder is responsible for printing all the greets. tim variable gives the current time, mor variable is assigned for 5:00 A.M, mid variable is assigned for 12:00 P.M, eve variable is assigned for 6:00 P.M, nig variable is used for 11:00 P.M.

Note: In datetime module 24 hour clock is used, so in the code hours is assigned in 24 hour clock.

Copy the code in your Python Interpreter, and see how you are greeted according to the time at which you execute the code.

Post a Comment

0 Comments