How do you write a code in Python that converts time between 4 zones with only for loops, if statements and strings

39 Views Asked by At

How do you convert time in Python with only a limited number of tools? I know there is a method that does it but we have not covered it yet in the book. I know there is a similar question on this website, however the solution involves def which comes close to the end of the book that I'm using. I think the key is in using the strings because this exercise comes in the Strings chapter. It reads as follows (Source:A Practical Introduction to Python Programming by Brian Heinold):

Write a program that converts a time from one time zone to another. The user enters the time in the usual American way, such as 3:48pm or 11:26am. The first time zone the user enters is that of the original time and the second is the desired time zone. The possible time zones are Eastern, Central, Mountain, or Pacific. Time: 11:48pm Starting zone: Pacific Ending zone: Eastern 2:48am

Here is my attempt that does not work:

#TIME ZONES:
#Pacific = 0
#Mountain = Pacific + 1
#Central = Mountain + 1
#Eastern = Central + 1

time = input("Time: ")
start = input("Starting zone: ")
end = input("Ending zone: ")

#An attempt to link the time zones to the variable i using numbers 0 to 3.

if start == "Pacific":
    s = 0
if start == "Mountain":
    s = 1
if start == "Central":
    s = 2
if start == "Eastern":
    s = 3

if end == "Pacific":
    e = 0
if end == "Mountain":
    e = 1
if end == "Central":
    e = 2
if end == "Eastern":
    e = 3

# This is where the problem shows up.
# I've tried multiple ways to convert the hours part
# from a string into an integer but none of them worked.
# Yes, I know that after I'm done I'll have to deal with
# the limited number of hours and switching from am to pm
# and vice versa but I need to solve this part first.

for i in range(4):
    hours = int(time[:1])
    time_h = hours + i
    time = str(time_h)+time[1:]
    if i == s:
        #print ("Starting zone: ", time)
    if i == e:
        print (time)
0

There are 0 best solutions below