Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

2) (20 points) Write a Python script named \"isValidTime.py\" that Take 1 string

ID: 3606952 • Letter: 2

Question

2) (20 points) Write a Python script named "isValidTime.py" that Take 1 string as an argument and determine if it is a valid time in 12-hour am/pm format. Hour must be between 1 and 12 and can have 1 or 2 digits. Minutes must be between 0 and 59 and must have 2 digits. Example: "7:35 am" and "09:59 pm" are valid, while "7:65 am" and "15:25 pm" are not valid The am/pm part is valid only if both characters are uppercase, or both characters are lowercase. Example: "AM", "PM", "am", and "pm" are all valid while "aM", "pM", “Am", "Pm" are not valid The space between the minute portion and am/pm portion is optional. Example "7:35am" and "7:35 am" are both valid If valid print "valid time", otherwise print "invalid time" If there is not exactly 1 argument, print an error message and exit a. b. c. d. e. f.

Explanation / Answer

Explanation:

First we find the position of :

Then we take characters from start till : this is hour

Then we take 2 digits after : this is minutes

Then we take all the characters after that till last of string, remove any white space.

Then we check for hour between 1 to 12

minutes between 0 to 59

and

AM am PM pm

using ==

We are using if else here.

Kindly see the code below. If you have more doubts kindly comment. All the best. :)

*************************************************************************************************************************************

Code:

********************************************************************************************************************************

Code as text:

t = input("Enter the time: ")
i= t.find(":")
hour = (t[0:i])
mins=t[i+1:i+3]
z=t[i+3:]
z=z.strip()
if int(hour)>=1 and int(hour) <=12:
    if int(mins)>=0 and int(mins) <=59:
        if z=="AM" or z=="am" or z=="PM" or z=="pm":
            print("valid time")
        else:
             print("invalid time!")
    else:
         print("invalid time!")
else:
     print("invalid time!")

********************************************************************************************************************************

Sample output 1 :

Enter the time:1:25 AM
valid time

Sample output 2 :

Enter the time:1:25pm
valid time

Sample output 3 :

Enter the time:13:25AM
invalid time!

Sample output 4 :

Enter the time:13:25 PM
invalid time!

********************************************************************************************************************************

I hope this helps you.
If you find my answer helpful,
Kindly rate the answer.
All the best :)

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote