通过使用功能消除代码重复来减少代码?

时间:2020-01-21 12:41:29

标签: python function

我已要求减少代码以消除重复:

june_hours = 243
june_cost = june_hours * 0.65
print("In June we spent: " + str(june_cost))

july_hours = 325
july_cost = july_hours * 0.65
print("In July we spent: " + str(july_cost))

august_hours = 298
august_cost = august_hours * 0.65
print("In August we spent: " + str(august_cost))

我试图:

def print_monthly_expense(month, hours):
    time = hours * 0.65
    print("In " + month + " We spent : " + str(time))

print_monthly_expense("June",243)
print_monthly_expense("July",325)
print_monthly_expense("August",298)

结果是:

6月,我们花费了:157.95000000000002
7月我们度过了:211.25
8月,我们花费了:193.70000000000002

系统回答:

不完全是。让您的职能部门完成大部分工作, 将月份名称和相关的小时数传递为 参数。

记住6月,7月和8月的时间 分别是243、325和298。

请帮助我,代码有什么问题?

预先感谢

1 个答案:

答案 0 :(得分:0)

Monirul,看来我们俩都在做同一件事。我遇到第一次运行代码时遇到的错误。

我最初有以下代码:

def print_monthly_expense(month, hours):
    cost = (hours) * 0.67
    print("In "  + month + " we spent: " + str(cost))

print_monthly_expense("June",243)
print_monthly_expense("July",325)
print_monthly_expense("August",298)

运行它的前几次,我遇到了与您相同的错误,我无法弄清楚。然后我意识到0.67是错误的,我应该使用0.65。修复错误后,代码正确运行,并且收到了此消息。

Here is your output:
In June we spent: 157.95000000000002
In July we spent: 211.25
In August we spent: 193.70000000000002

Nice work! You're getting acquainted with some interesting
coding practices to reduce code duplication.

您确定出什么问题了吗?也许是文本格式?您有大写字母“ We”,在冒号前面的空格“ spent:”?只是猜测,我什么都没看到。