为什么我的函数参数返回未定义的错误

2024-06-10 01:38:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我是新的功能,所以我不太清楚如何或为什么这是发生的,我不知道如何修复它。有人能解释为什么这个错误一直发生吗

def loan_payment(l):
    loan = float(input("Please enter how much you expend monthly on loan payments:"))
    return loan
def insurance_cost(i):
    insurance = float(input("Please enter how much you expend monthly on insurance:"))
    return insurance
def gas_cost(g):
    gas = float(input("Please enter how much you expend monthly on gas:"))
    return gas
def maitanence_cost(m):
    maitanence = float(input("Please enter how much you expend monthly on maintanence:"))
    return maitanence
def monthly_cost(l, i, g, m):
    monthly_expenses = float(l + i + g + m)

    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
def main():
    loan_payment(l)
    insurance_cost(i)
    gas_cost(g)
    maitanence_cost(m)
    monthly_cost(l, i, g, m)
    yearly_cost(monthly_cost)
main()

此代码返回错误:

line 24, in main loan_payment(l) NameError: name 'l' is not defined


Tags: youinputreturndeffloatenterpleaseinsurance
2条回答

我认为您可能对python如何通过赋值传递有点误解,您不会是第一个,这里有一个很棒的question to help,以及如何assign valuesdefining methods。据我所知,你的主要方法应该更像:

def main():
    l = user_in_loan_payment()
    i = user_in_insurance_cost()
    g = user_in_gas_cost()
    m = user_in_maintanence_cost()
    monthly_cost = calculate_monthly_cost(l, i, g, m)
    yearly_cost = calculate_yearly_cost(monthly_cost)

我将方法名改为以“calculate”或“user\u in”开头,以使其更具可读性

这正是错误所说的:l没有定义,就像其他变量一样。如果我没弄错的话,你可以在前4个函数中输入值,然后在接下来的两个函数中使用它们进行计算

如果这是真的,您的代码应该如下所示:

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(l, i, g, m):
    monthly_expenses = float(l + i + g + m)

    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
def main():
    l = loan_payment()
    i = insurance_cost()
    g = gas_cost()
    m = maitanence_cost()
    mc = monthly_cost(l, i, g, m)
    yearly_cost(mc)
main()

相关问题 更多 >