#python #python-3.x #python-2.7 #jupyter-notebook
#python #python-3.x #python-2.7 #jupyter-записная книжка
Вопрос:
В данном коде я работаю над финансовым планированием. в этом участвует человек, обладающий финансовой грамотностью (fl), а не человек, обладающий финансовой грамотностью (nfl). Я должен рассчитать их баланс после 40 лет сбережений, выплаты по кредиту, оплаты жилья и отобразить его на графике. он включает в себя два словаря fl и nfl, и я не уверен, как вводить словари в функцию, потому что последняя функция «simulation» должна вызывать rest all функцию, и, и если я ввожу только в последнюю функцию, она показывает ошибку
import numpy as numpy
import matplotlib.pyplot as plt
import matplotlib
fl = {"savings": 5000, "checking": 1000, "debt": 30100, "loan": 0, "yearsWithDebt": 0, "yearsRented": 0, "debtPaid": 0}
nfl = {"savings": 5000, "checking": 1000, "debt": 30100, "loan": 0, "yearsWithDebt": 0, "yearsRented": 0, "debtPaid": 0}
#nfl["savings"]=nfl["savings"]*1.01
#print(range(12))
house_var = False
house_var_1 = False
def savingsPlacement(person):
"""
This function simulates the increasing interest on a person's savings account depending on whether
they put it in a bank account or a mutual fund.
input: a dictionary representing fl or nfl
output: an updated dictionary with the new savings amount after 1 year of it being in
either the mutual fund of the bank account
"""
nfl["savings"]=nfl["savings"]*1.01
fl["savings"]=fl["savings"]*1.07
return person
def debt(person):
"""
This function simulates the amount of debt a person has left and the amount they
paid after one year.
input: a dictionary representing fl or nfl
output: an updated dictionary. debt, savings, debtPaid, and yearsWithDebt
are all changed each year if there is debt remaining.
"""
if(nfl["debt"]>0):
j=0
for i in range(12):
nfl["debt"]=nfl["debt"]-(0.03*nfl["debt"] 1)
nfl["debtPaid"]=0.03*nfl["debt"] 1
nfl["debt"]=1.2*nfl["debt"]
j=j 1;
nfl["yearsWithDebt"]=j
if (fl["debt"]>0):
k=0
for i in range(12):
fl["debt"]=fl["debt"]-(0.03*fl["debt"] 15)
fl["debtPaid"]=0.03*fl["debt"] 15
fl["debt"]=1.2*fl["debt"]
k=k 1;
fl["yearsWithDebt"]=k
return person
def rent(person):
"""
This function simulates the amount of money a person has left in their bank account
after paying a year's worth of rent.
input: a dictionary representing fl or nfl
output: an updated dictionary with a checking account that has been lowered by the
amount the person had to pay for rent that year.
"""
nfl["checking"]=nfl["checking"]-850
fl["checking"]=fl["checking"]-850
def house(person):
"""
This function simulates the amount of money a person has left in their bank accont
after paying monthly mortgage payments for a year.
input: a dictionary representing fl or nfl
output: an updated dictionary with a loan and checking account lowered by the
mortgage payments made that year.
"""
if house_var==True :
for j in range(12):
N = 360
D = ((0.05 1) * N - 1) / (0.05 * (1 0.05) * N)
P = 175000 / D
nfl["checking"] = nfl["checking"] - P
nfl["loan"] = (175000-0.05*175000) - P
if house_var_1==True:
for j in range(12):
N = 360
D = ((0.045 1) * N - 1) / (0.045 * (1 0.045) * N)
P = 175000 / D
fl["checking"] = fl["checking"] - P
fl["loan"] = (175000-0.2*175000) - P
return person
def simulator(person):
"""
This function simulates financial decisions over the course of 40 years.
input: a dictionary representing fl or nfl
output: a list of intergers representing the total sum of money that fl
or nfl has each year.
"""
simulator()
"""for i in range(40):
fl["wealth"]=fl["savings"] fl["checking"]-fl["debt"]-fl["loan"]
nfl["wealth"]=nfl["savings"] nfl["checking"]-nfl["debt"]-nfl["loan"]
fl["checking"]=fl["checking"] 0.3*29500
fl["savings"]=fl["savings"] 0.2*29500
nfl["checking"]=nfl["checking"] 0.3*29500
nfl["savings"]=nfl["savings"] 0.2*29500
savingsPlacement(person)
debt(person)
if(nfl["checking"]>0.05*175000):
house_var=True
house(person)
if(fl["checking"]>0.2*175000):
house_var_1=True
return fl["wealth"],nfl["wealth"],person
"""
datafl = simulator(fl)
datanfl = simulator(nfl)
plt.xlabel('Years')
plt.ylabel('Wealth')
plt.title('Wealth of fl vs nfl Over 40 Years')
plt.plot(datafl, label='fl')
plt.plot(datanfl, label='nfl')
plt.legend()
plt.show()
Комментарии:
1. В чем ошибка? Покажите, пожалуйста, обратную трассировку исключения.
Ответ №1:
На момент написания все ваши функции имели подписи, подобные этой:
def savingsPlacement(person):
Однако ни один из них не использует параметр, person
, который передается в. Вместо этого они напрямую ссылаются на переменные fl
и nfl
.
Возможно, это может быть задание. Если это так, то его нужно было бы переработать. Я бы начал с того, что отложил копию этой версии и начал заново. Выберите одну функцию, такую как savingsPlacement()
, и напишите только это, без каких-либо ссылок на имена переменных fl или nfl вообще. Вместо этого используйте только переменную person
. Используйте только то, что вы можете знать о человеке при входе в функцию. Возможно, вам потребуется добавить другой параметр для других значений, жестко закодированных в некоторых ваших функциях. Протестируйте функцию, вызвав ее с параметрами из командной строки Python. Только после этого переходите к другой функции.
Если это не задание, вы в любом случае найдете результирующую программу более полезной и общей таким образом.
Комментарии:
1. да, я понял это и изменил код относительно аргумента в функции, а позже отредактировал еще несколько строк, которые заставили код выполняться. Спасибо вам за помощь.