python - 计算达到首付的月数
问题描述
编写一个脚本,其中包含您刚刚编写的 house_loan() 的定义。当脚本执行时,它应该要求用户输入以下值,然后使用 house_loan() 函数计算节省足够的首付所需的月数。请注意,所有参数都必须是浮点数。
- 起薪年薪
- 工资中要存的部分
- 梦想家园的成本
Test Case #1
>>>
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream house: 1000000
Number of months: 183
>>>
Test Case #2
>>>
Enter your annual salary: 80000
Enter the percent of your salary to save (as a decimal): .15
Enter the cost of your dream home: 500000
Number of months: 105
>>>
当我执行我的代码时,我要么得到一个超高的数字,要么得到一个低于它的数字。我想不出正确的方法来设置我的代码以使其通过第一种和第二种情况。此外,我只是帮助正确设置它,以获得正确的答案。
Code
annual_salary = float(input('What's your annual salary? \n'))
portion_saved = float(input('What portion would you like to save (as a decimal)? \n'))
portion_downpayment = 0.25
total_cost = float(input('What is the total cost of your dream house? \n'))
def house_loan(annual_salary,
portion_saved,
portion_downpayment,
total_cost):
cost_to_be_paid = total_cost - portion_downpayment #calculat the pending money to be paid
monthly_salary = annual_salary/12 #calculate the monthly salary
monthly_savings = monthly_salary*portion_saved #calculate monthly savings in salary
total_months = cost_to_be_paid/monthly_savings #returning the months required to pay money
return total_months
print('The months required to pay enough money for the down payment is: ',house_loan(annual_salary, portion_saved, portion_downpayment, total_cost))
解决方案
您的part_downpayment 不是全局变量,因此它从未传递到您的函数中。这有效:
annual_salary = float(input('Whats your annual salary? \n'))
portion_saved = float(input('What portion would you like to save (as a decimal)? \n'))
total_cost = float(input('What is the total cost of your dream house? \n'))
def house_loan(annual_salary,
portion_saved,
portion_downpayment,
total_cost):
portion_downpayment = 0.25
cost_to_be_paid = total_cost * portion_downpayment #calculat the pending money to be paid
monthly_salary = annual_salary / 12 #calculate the monthly salary
monthly_savings = monthly_salary * portion_saved #calculate monthly savings in salary
total_months = cost_to_be_paid / monthly_savings #returning the months required to pay money
return(total_months)
print('The months required to pay enough money for the down payment is: %s' % house_loan(annual_salary, portion_saved, portion_downpayment, total_cost))
推荐阅读
- java - 使用 One-Jar 找不到主要方法
- angular - 在 TypeScript 中循环访问类型为 any 的数组时访问属性
- ios - iOS App 在发布模式下启动时崩溃,但在调试模式下不会崩溃
- oracle12c - OBIEE 新计算项 - 大于或等于
- delphi - Delphi XE6 E2008 on Inherited
- ruby-on-rails - Ruby反转由下划线分隔的单个字符串的单词
- r - 在R中设置图形图例的大小
- javascript - 如何使用承诺检查错误?
- python - Python - 检查几列并比较字符串
- android - 从活动调用微调器到适配器类