因此,我需要计算用户每月花费的金额,然后使用该数字来计算他们每年花费的金额。为了做到这一点,我想将他们的每月费用乘以12以获得他们的年度费用,但我一直到达同样的错误,我不能将int和函数与运算符相乘" *"
def loan_payment():
loan = float(input("Please enter how much you expend monthly on loan payments:"))
return loan
def insurance_cost():
insurance = float(input("Please enter how much you expend monthly on insurance:"))
return insurance
def gas_cost():
gas = float(input("Please enter how much you expend monthly on gas:"))
return gas
def maitanence_cost():
maitanence = float(input("Please enter how much you expend monthly on maintanence:"))
return maitanence
def monthly_cost():
monthly_expenses = float(loan + insurance + gas + maintanence)
return float(monthly_expenses)
print("You expend $"+format(monthly_cost, '.2f')+"in a month.")
def yearly_cost():
yearly_expenses = 12 * monthly_cost
return yearly_expenses
print("At your current monthly expenses, in a year you will have paid $"+format(yearly_cost, '.2f')+".")
def main():
loan_payment()
insurance_cost()
gas_cost()
maitanence_cost()
monthly_cost
yearly_cost()
main()
答案 0 :(得分:1)
在我看来,你正在学习如何使用功能。
def loan_payment():
loan = float(input("Please enter how much you expend monthly on loan payments:"))
return loan
def insurance_cost():
insurance = float(input("Please enter how much you expend monthly on insurance:"))
return insurance
def gas_cost():
gas = float(input("Please enter how much you expend monthly on gas:"))
return gas
def maitanence_cost():
maitanence = float(input("Please enter how much you expend monthly on maintanence:"))
return maitanence
def monthly_cost(loan, insurance, gas, maitanence):
monthly_expenses = float(loan + insurance + gas + maitanence)
print("You expend $"+format(monthly_expenses, '.2f')+"in a month.")
return float(monthly_expenses)
def yearly_cost(monthly_cost):
yearly_expenses = 12 * monthly_cost
print("At your current monthly expenses, in a year you will have paid $".format(yearly_expenses, '.2f') + ".")
return yearly_expenses
loan = loan_payment()
insurance = insurance_cost()
gas = gas_cost()
maitanence = maitanence_cost()
monthly_cost = monthly_cost(loan, insurance, gas, maitanence)
yearly_cost(monthly_cost)
是你想要的。
无论您使用return
语句返回什么,我都会将其分配给变量。所以一旦我收集了它们,我就可以在收集4个变量的monthly_cost()
函数中传递它们。
此外,仅当您要退出该功能时才return
。如果print
在return
语句到达之前,则不会执行print
语句。我希望所有这一切都有道理。 w ^
了解return
的工作原理!
答案 1 :(得分:0)
您忘记了括号来调用该函数:
yearly_expenses = 12 * monthly_cost()
然后您有无法访问的代码:无法访问最后一行print...
。
def monthly_cost():
monthly_expenses = float(loan + insurance + gas + maintanence)
return float(monthly_expenses)
print("You expend $"+format(monthly_cost, '.2f')+"in a month.")