【问题标题】:Python issue with iterationPython 迭代问题
【发布时间】:2014-02-11 02:56:06
【问题描述】:
import math
import sys

def calculateValues(loanAmt, numYears):
    for monthlyRate in range (4, 9):
        monthlyRate = monthlyRate / 100
        monthlyPayment = loanAmt * monthlyRate / (1 - math.pow(1 / (1 + monthlyRate), numYears * 12))
        totalPayment = monthlyPayment * numYears * 12
        return monthlyRate, monthlyPayment, totalPayment

def printPayments(monthlyRate, monthlyPayment, totalPayment, loanAmt, numYears):
    print("Rate   Monthly Payment  Total Payment")
    for monthlyRate in range (4, 9):
        calculateValues(loanAmt, numYears)
        print("{0}%     ${1:0.2f}         ${2:0.2f}".format( monthlyRate, monthlyPayment, totalPayment))

def repeat():
    question = str(input("Would you like to create a new table? (Enter y for yes): "))
    if (question == "y"):
        main()
    else:
        sys.exit()

def getPositiveFloat():
    loanAmt = int(input("Enter the amount of the loan: "))
    numYears = int(input("Enter the number of years: "))
    if (loanAmt < 0) or (numYears < 0):
        print("Please enter a positive number for both questions")
        main()
    return loanAmt, numYears

def main():
    loanAmt, numYears = getPositiveFloat()
    monthlyRate, monthlyPayment, totalPayment = calculateValues(loanAmt, numYears)
    printPayments(monthlyRate, monthlyPayment, totalPayment, loanAmt, numYears)
    repeat()

main()

当该程序运行时,monthlyRate 变量(在 printPayments 中定义)迭代,但在 calculateValues 中计算的值不会迭代。我发现我需要将monthlyRate 提供给calculateValues 作为参数,但我不确定如何在不破坏所有内容的情况下做到这一点。

【问题讨论】:

  • 只是一个提醒——如果一个答案很好地解决了你的问题,你应该正式接受它。祝你好运!

标签: python loops for-loop arguments iteration


【解决方案1】:

代码中存在一些问题,您可以通过下面的代码进行 diff 轻松查看。

  1. calculateValues:循环运行并在第一次迭代时返回结果
  2. printPayments 调用 calculateValues 但没有获取结果(这就是为什么会一次又一次地打印同一行
  3. printPayments 也会循环打印 - 这意味着不需要一个循环
  4. main() 调用 calculateValues 然后 printPayments - 这意味着这两个 for 循环再次被调用太多次,没有保存结果

这里是固定代码:

import math
import sys

def calculateValues(monthlyRate, loanAmt, numYears):
    monthlyRate = monthlyRate / 100
    monthlyPayment = loanAmt * monthlyRate / (1 - math.pow(1 / (1 + monthlyRate), numYears * 12))
    totalPayment = monthlyPayment * numYears * 12
    return monthlyRate, monthlyPayment, totalPayment

def printPayments(loanAmt, numYears):
    print("Rate   Monthly Payment  Total Payment")
    for monthlyRate in range (4, 9):
        monthlyRate, monthlyPayment, totalPayment = calculateValues(monthlyRate, loanAmt, numYears)
        print("{0}%     ${1:0.2f}         ${2:0.2f}".format(int(monthlyRate*100, monthlyPayment, totalPayment))

def repeat():
    question = str(input("Would you like to create a new table? (Enter y for yes): "))
    if (question == "y"):
        main()
    else:
        sys.exit()

def getPositiveFloat():
    loanAmt = int(input("Enter the amount of the loan: "))
    numYears = int(input("Enter the number of years: "))
    if (loanAmt < 0) or (numYears < 0):
        print("Please enter a positive number for both questions")
        main()
    return loanAmt, numYears

def main():
    loanAmt, numYears = getPositiveFloat()
    printPayments(loanAmt, numYears)
    repeat()

main()

输出:

Enter the amount of the loan: 100
Enter the number of years: 20
Rate   Monthly Payment  Total Payment
4%     $4.00         $960.08
5%     $5.00         $1200.01
6%     $6.00         $1440.00
7%     $7.00         $1680.00
8%     $8.00         $1920.00
Would you like to create a new table? (Enter y for yes): 

我认为您在这里计算利息的方式有问题:

monthlyPayment = loanAmt * monthlyRate / (1 - math.pow(1 / (1 + monthlyRate), numYears * 12))

但是这部分我会让你自己解决;)

【讨论】:

  • 我试过你的代码,但它没有按预期工作。我也不确定你改变了什么。
【解决方案2】:

问题是你的代码第一次遇到“return”语句时,它会返回值并离开函数。看起来您在 printpayments 中循环遍历monthlyRate (monthlyRate = [4, 5, 6, 7, 8])。没关系。现在,对于您的 calculateValues 函数,您希望将monthlyPayment 和totalPayment 返回到调用函数。您还需要将monthlyRate 作为参数传入。

def calculateValues(monthlyRate, loanAmt, numYears):
    monthlyRate = monthlyRate / 100
    monthlyPayment = loanAmt * monthlyRate \
                / (1 - math.pow(1 / (1 + monthlyRate), numYears * 12))
    totalPayment = monthlyPayment * numYears * 12
    return (monthlyPayment, totalPayment)

def printPayments(monthlyRate, monthlyPayment, totalPayment, loanAmt, numYears):
    print("Rate   Monthly Payment  Total Payment")
    for monthlyRate in range (4, 9):
        monthlyPayment, totalPayment = calculateValues(monthlyRate, loanAmt, numYears)
        print("{0}%     ${1:0.2f}         ${2:0.2f}".format( monthlyRate, \
               monthlyPayment, totalPayment))

通常,您似乎需要大量阅读和思考如何在计算机编程中编写函数,尤其是在程序执行期间可以看到变量的地方。以下是此类阅读的潜在有用链接:

http://gettingstartedwithpython.blogspot.com/2012/05/variable-scope.html

希望这会有所帮助。

【讨论】:

    【解决方案3】:

    如果您的代码与您在此处键入的代码一样,这很容易,您的 return 语句缩进太多

    def calculateValues(loanAmt, numYears):
        myAnswer = []
        for monthlyRate in range (4, 9):
            monthlyRate = monthlyRate / 100
            monthlyPayment = loanAmt * monthlyRate / (1 - math.pow(1 / (1 + monthlyRate), numYears * 12))
            totalPayment = monthlyPayment * numYears * 12
            thisRound = (monthlyRate, monthlyPayment, totalPayment)
            myAnswer.append(thisRound)
        return myAnswer
    

    第一次迭代后返回的结果应该类似于上面的内容

    我只是在这里猜测您想要每次迭代的结果,您需要将它们保存在某个容器中。我个人会将它们保存在字典中,但在您的目标更明确之前还没有准备好

    您应该考虑的一件事是在您的函数中添加一些打印语句,这样您就可以看到每次迭代期间的值是什么

     def testFunction(somevalue):
        for x in range(0, somevalue):
            print 'hello'
        return x
    
    y = testFunction(2)
    
    hello
    hello
    >>>y
    1
    

    【讨论】:

    • 你是说你的代码是按照我的格式格式化的
    • 您应该更清楚的是您正在寻找每个月的付款
    • 是的。拥有完全一样的代码并不能解决问题。
    • 运行程序。每月和总付款应该重复,但它们不会。
    • @user3295439 这是因为这只是众多问题之一。有关详细信息,请参阅我的答案。
    猜你喜欢
    • 1970-01-01
    • 2011-02-15
    • 2021-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-14
    • 2016-10-29
    • 2014-09-23
    相关资源
    最近更新 更多