Yehuda
Yehuda

Reputation: 1893

Add function names to a string in Python

I'm just beginning to learn Python on my own, and I'm trying to write a code that will calculate the end time of a jog.

My code so far looks as follows:

def elapsed(t):
    t = raw_input('Enter time (hh:mm:ss): ')
    th, tm, ts = t.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600

def mile(m):
    m = raw_input('How many miles? ')
    return int(m)

start = elapsed('start')
warmup = elapsed('warmup')
wmile = mile('wmile')
tempo = elapsed('tempo')
tmile = mile('tmile')
cooloff = elapsed('cooloff')
cmile = mile('cmile')

hour = (start + warmup * wmile + tempo * tmile + cooloff * cmile) // 3600
minute = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) // 60
second = (start + warmup * wmile + tempo * tmile + cooloff * cmile - hour * 3600) % 60

print('Your run ended at %02d:%02d:%02d' % (hour, minute, second))

In this code, the time prompts are all the same: "Enter time (hh:mm:ss):" I want each prompt to refer to its variable name, e.g., "Enter start time (hh:mm:ss)" or "Enter time (hh:mm:ss): (warmup)". Is there a way to do this?

Note: While this may technically be a duplicate, I have examined the similar questions, but decided that both the questions and the answers provided were on the more unspecific side, and therefore decided to ask my question anyway.

Upvotes: 0

Views: 391

Answers (2)

syntaxError
syntaxError

Reputation: 866

def enter_time(specify_string):
    print("Please enter the", specify_string, 'time in format hh:mm:ss > ', end='')
    hh, mm, ss = input().split(':')
    return (hh, mm, ss)

start_time = enter_time('start')
finish_time = enter_time('finish')


>>>Please enter the start time in format hh:mm:ss >13:32:34 
>>>Please enter the finish time in format hh:mm:ss >12:21:21
>>>start_time
(13, 32, 34)

Now you can call the function with string arguments in the function call, and it will generalise the function for different requirements.

It is better to move the time between functions in a more readable format, such as a tuple. You can make more functions, eg: - Test valid time entered - Convert tuple to seconds for calculations - Convert seconds back to tuple format ect.

Let me know if I misunderstood you.

Upvotes: 0

user2047399
user2047399

Reputation:

Yes, use the input to your function elapsed(t).
Right now it's being overwritten with the return from raw_input()

def elapsed(t):
    t1 = raw_input('Enter time (hh:mm:ss): ({0})'.format(t))
    th, tm, ts = t1.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600

or

def elapsed(t):
    t1 = raw_input('Enter time (hh:mm:ss): (%s)' % t))
    th, tm, ts = t1.split(':')
    return int(ts) + int(tm) * 60 + int(th) * 3600

Upvotes: 1

Related Questions