首页 > 解决方案 > 通过删除函数代码中的重复来减少代码?

问题描述

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

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)

结果是:

六月我们花费了:157.95000000000002
七月我们花费了:211.25
八月我们花费了:193.70000000000002

系统回复:

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

请记住,六月、七月和八月的时间分别是 243、325 和 298。

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

提前致谢

标签: pythonfunction

解决方案


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.

你弄清楚出了什么问题吗?也许是文本格式?你有大写的“我们”和最后的冒号前的空格“花费:”?只是猜测,我没有看到其他任何东西。


推荐阅读