如何更新循环中的单个变量?

2024-10-01 15:30:28 发布

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

我在while循环中尝试的是用一个10的整数来迭代支付,这样如果这个整数(g)在12个月内没有得到CBalance <= 0,那么除了g之外的所有变量都会重置,g会上升1。你知道吗

Balance = float(raw_input('Enter Balance '))
Rate = float(raw_input('Enter interest rate '))
monthlyI = Rate/12
month = 0
g = 1
Payment = 10
CBalance = Balance
while CBalance > 0:
    Payment = Payment*g
    month += 1
    CBalance = CBalance *(1+ monthlyI)- Payment
    if month > 12:
        month = 0
        g += 1
        Cbalance = Balance

Tags: inputrawrate整数paymentfloat重置enter
2条回答

What I'm trying to do in the while loop is iterate the payments by an integer of 10 so that if that integer (g) fails to get the CBalance <= 0 within a 12 months period then all of the variables reset except for g, which goes up by 1.

我认为现在的情况是,每次运行此程序时,您将得到:

Payment = 10 * 1 //First while payment = 10

第二次

Payment = 10 * 1 //payment = 10 again.

结果是:

  CBalance = CBalance * (1 + monthlyI) - 10

它永远不会变成负值,这是结束循环所需要的?你知道吗

你可能想:

counter = 1;
while CBalance > 0:
   Payment = Payment*counter
   month += 1
   counter += 1
   CBalance = CBalance *(1+ monthlyI)- Payment
   if month > 12:
      month = 0
      counter = 1
      g += 1
      Cbalance = Balance

我想我终于明白你的问题是关于什么的了,是什么导致了这个问题,也就是一个简单的变量名拼写错误。要解决这个问题,只需将while循环中if后面语句的最后一行从:

        if month > 12:
            month = 0
            g += 1
            Cbalance = Balance

收件人:

        if month > 12:
            month = 0
            g += 1
            CBalance = Balance  # note corrected spelling of variable name on left

这就解释了为什么没有重置所有的值。如果你明确地提到你的问题中的哪个变量,如果你知道的话,这会很有帮助。无论如何,当您使用大写和mixedCase变量名时,这种情况更可能发生。你知道吗

由于这个原因,许多程序员试图避免使用它们,尤其是在Python这样的语言中,在使用变量之前通常不必声明变量。您可能想查看pep8风格指南的Naming Conventions部分。你知道吗

相关问题 更多 >

    热门问题