首页 > 解决方案 > 计算达到首付的月数

问题描述

编写一个脚本,其中包含您刚刚编写的 house_loan() 的定义。当脚本执行时,它应该要求用户输入以下值,然后使用 house_loan() 函数计算节省足够的首付所需的月数。请注意,所有参数都必须是浮点数。

  1. 起薪年薪
  2. 工资中要存的部分
  3. 梦想家园的成本
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))

标签: pythonspyder

解决方案


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

推荐阅读