在Python中向字符串添加函数名

2024-10-01 09:34:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我刚刚开始自学Python,我正在尝试编写一个代码来计算jog的结束时间。你知道吗

我的代码如下:

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))

在这段代码中,时间提示都是相同的:“Enter time(hh:mm:ss):”我希望每个提示都引用它的变量名,例如,“Enter start time(hh:mm:ss)”或“Enter time(hh:mm:ss):(warmup)”。有办法吗?你知道吗

注意:虽然这在技术上可能是重复的,但我已经检查了类似的问题,但我认为所提供的问题和答案都是不具体的,因此还是决定问我的问题。你知道吗


Tags: timehhstartssintmmenterwarmup
2条回答

是的,使用函数elapsed(t)的输入。
现在它被来自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

或者

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
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)

现在您可以在函数调用中使用字符串参数调用函数,它将针对不同的需求对函数进行泛化。你知道吗

最好以更可读的格式(如元组)在函数之间移动时间。你可以做更多的功能,例如: -输入测试有效时间 -将元组转换为秒进行计算 -将秒转换回元组格式 发射型计算机断层扫描仪。你知道吗

如果我误解了你,请告诉我。你知道吗

相关问题 更多 >