首页 > 解决方案 > Python 3 新手问题:这段代码高效/干净吗?它可以改进/简化吗

问题描述

支付计算提示基于工作时间和每小时费率,其中 40 小时以上按原费率的 1.5 倍支付。

以每小时 10.50 的速度在 45 小时内进行测试。输出应该是支出数字。

代码

标签: python-3.xsyntax

解决方案


我会以不同的方式组织代码。1. 打包代码片段的函数,以便它们可以重用和参数化。2.异常处理以指示不正确的用户输入。

def get_hrs_rph_from_user():

    while True:
        hrs = input('Enter Hours: ')
        try:
            hrs = int(hrs)
            break
        except ValueError:
            print('Cannot convert [{}] into integer'.format(hrs))

    while True:
        rph = input('Enter Rate per Hour: ')
        try:
            rph = float(rph)
            break
        except ValueError:
            print('Cannot convert [{}] into float'.format(rph))

    return hrs, rph


def calculate_payout(hrs, rph, hrs_norm=40, coeff=1.5):

    if hrs <= hrs_norm:
        return hrs * rph
    else:
        return hrs_norm * rph + (hrs - hrs_norm) * coeff * rph


if __name__ == '__main__':

    payout = calculate_payout(*get_hrs_rph_from_user())
    print('\nCalculated payout = {}'.format(payout))

基于@Jeronimo 建议的相同代码的另一个版本(对于python 新手来说非常复杂且容易出错):

def get_from_user_factory(config):

    ans = dict()

    for key, elem in config.items():
        def get_from_user(line=elem['input_line'], type_=elem['value_type']):
            while True:
                value = input('{}: '.format(line))
                try:
                    return type_(value)
                except ValueError:
                    print(
                        'Cannot convert [{}] into {}'
                        .format(value, type_.__name__))
        ans[key] = get_from_user

    return ans


def calculate_payout(hrs, rph, hrs_norm=40, coeff=1.5):

    if hrs <= hrs_norm:
        return hrs * rph
    else:
        return hrs_norm * rph + (hrs - hrs_norm) * coeff * rph


if __name__ == '__main__':

    input_config = {
        'hrs': {'input_line': 'Enter Hours', 'value_type': int},
        'rph': {'input_line': 'Enter Rate per Hour', 'value_type': float}}

    input_functions = get_from_user_factory(input_config)

    input_data = {key: func() for key, func in input_functions.items()}
    print('\nData from user: {}'.format(input_data))

    payout = calculate_payout(**input_data)
    print('Calculated payout = {}'.format(payout))

推荐阅读