【问题标题】:Add function names to a string in Python在 Python 中将函数名称添加到字符串
【发布时间】:2017-06-08 01:19:16
【问题描述】:

我刚刚开始自学 Python,我正在尝试编写一个代码来计算慢跑的结束时间。

到目前为止,我的代码如下所示:

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

在这段代码中,时间提示都是一样的:“输入时间(hh:mm:ss):”我希望每个提示都引用它的变量名,例如,“输入开始时间(hh:mm:ss) )”或“输入时间 (hh:mm:ss): (预热)”。有没有办法做到这一点?

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

【问题讨论】:

标签: python python-2.7 function


【解决方案1】:

是的,使用函数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

【讨论】:

    【解决方案2】:
    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)
    

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

    最好以更易读的格式(例如元组)在函数之间移动时间。您可以制作更多功能,例如: - 输入测试有效时间 - 将元组转换为秒以进行计算 - 将秒转换回元组格式 等等。

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

    【讨论】:

      猜你喜欢
      • 2023-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 2021-07-08
      • 1970-01-01
      • 2019-07-24
      相关资源
      最近更新 更多