Value won't increment inside while loop - python

my problem is that the 'month' value increments once to month = 1, then stays there the whole time, causing an infinite loop. How do I get this to change every time through the loop? I know I'm probably missing something extremely simple.
def rem_bal(balance, annualInterestRate, monthlyInterestRate):
month = 0
while month <= 12:
monthly_interest = (annualInterestRate) / 12.0
minimum_monthly = (monthlyInterestRate) * balance
monthly_unpaid= (balance) - (minimum_monthly)
updated_balance = round(((monthly_unpaid) + (monthly_interest * monthly_unpaid)), 2)
month =+ 1
print("Month " + str(month) + "Remaining balance: " + str(updated_balance) + " .")
balance = updated_balance
return balance

month += 1
not
month = +1
which is just
month = 1

It needs to be month += 1 not month =+ 1; the latter is just plain assignment rather than incrementing the value of month (i.e., assigning month to +1/1).

BTW, this is not how you write a code in python.
Why parentheses around almost everything?
Why recalculate monthly_interest over and over, when it doesn't change?
Using a while loop for this isn't pythonic. You should rather use
for month in range(13):

month = month+1 - tried this works

Related

How to triple the amount every other time?

I don't know how to triple the amount.
1st month's payment 1 dollar.
2nd month's payment 2 dollars. (doubled the amount)
3rd month's payment 6 dollars. (triple it every other months)
4th month's payment 12 dollars. (double the amount)
5th month's payment 36 dollars. (triple it every other month)
6th month's payment 72 dollars. (double the amount)
7th month's payment 216 dollars. (triple it every other month)
and so on ...
I'm using the for and if statements.
base = 1
payments = int(input("For how many months did they say you will receive payments? "))
for i in range(0, payments):
if i % 2 > 0:
base *= 3
else:
base *= 2
month = "Month " + str(i + 1) + ":" + str(base)
print(month)
for month 1 I get $2 and I expect to get $1
You could use modulus operator and on every odd entry, triple the amount.
base = 1
payments = 5
print("Month 1: %s" % base)
for i in range(2, payments):
if i % 2 == 1:
base *= 3
else:
base *= 2
print("Month %s: %s" % (i+1, base))
You can use a list of numbers to be multiplied for (2 and 3), while the installments are less than the input. The logic is to alternate between the two numbers of the list, while the condition is true:
base = 1
payments = input("For how many months did they say you will receive payments? ")
x = 1
multiplyList = [2, 3]
print(f'Month {x}: $ {base}')
while x <= int(payments):
i = 0
for number in multiplyList:
base = (base * multiplyList[i])
print(f'Month {x}: $ {base}')
i = i + 1
x = x + 1
# output:
# Month 1: $ 1
# Month 1: $ 2
# Month 2: $ 6
# Month 3: $ 12
# Month 4: $ 36
# Month 5: $ 72
# Month 6: $ 216
# Month 7: $ 432
# Month 8: $ 1296
# Month 9: $ 2592
# Month 10: $ 7776
EDIT: OP has edited the question to incorporate new attempts and
change the problem statement, so this is out of date.
As mentioned in other answers, your approach has a few drawbacks which make it non-ideal as a solution.
That being said, here is where the code went wrong:
Starting with a condensed version of your original:
base = 1
payments = 10
for i in range(payments):
month = "Month " + str(i + 1) + ":" + str(base)
base *= 2
if i in range(2, payments, 3):
base *= 3
print(month)
you need to end up here:
base = 1
payments = 10
for i in range(payments):
month = "Month " + str(i + 1) + ":" + str(base)
if i in range(1, payments, 3):
base *= 3
else:
base *= 2
print(month)
The changes needed are:
Using range(2, ...) instead of range(1, ...). This is because the way that you print and calculate you end up determining the new base during the previous month.
Moving *= 2 into an else: statement so you don't multiply by 6
This works:
base = 1
payments = int(input("For how many months did they say you will receive payments? "))
month = "Month " + str(1) + ":" + str(base)
print(month)
for i in range(1, payments):
if i % 2 > 0:
base *= 2
else:
base *= 3
month = "Month " + str(i + 1) + ":" + str(base)
print(month)
Because you were enetering straight into the for loop, it meant that you were doubling the first month. However if you print the first amount before the loop, start the loop at two, and swap the modulo statements around, it works.
This solution has only one print() statement to print month and amount, but it has an if == 0 in the loop
you could get rid of the if statement within the loop but had to add one more print line before the loop.
if you don't want to print intermediate results then you can start the range from 1, get ird of the if i == 0 and print the result after having left the for loop.
base = 1
payments = int(input("For how many months did they say you will receive payments? "))
print(base)
for i in range(0, payments):
if i == 0:
pass
elif i % 2 > 0:
base *= 2
else:
base *= 3
msg = "Month " + str(i + 1) + ":" + str(base)
print(msg)

Using functions in 'while' loop python

So I want to create a code that would calculate the minimum monthly payment and remaining balance, given an annual interest rate, principal amount and monthly payment rate. The desired output is:
Month: 1
Minimum monthly payment: 168.52
Remaining balance: 4111.89
Month: 2
Minimum monthly payment: 164.48
Remaining balance: 4013.2
and so on until month 12.
I know there's a way to do it without defining functions but the whole function thing was just messing me up so I wanted to try it. My current code is -
a=0
while a<=11:
def min_mth_pay(balance,monthlyPaymentRate):
x = balance * monthlyPaymentRate
return x
def balance(balance,min_mth_pay,annualInterestRate):
y=(balance - min_mth_pay)*((annualInterestRate/12)+1)
return y
a +=1
print('Month:' + str(a) + 'Minimum monthly payment:' + str(x) + 'Remaining balance:' + str('y'))
I'm not even sure if I can use functions in such a format? The error pops out saying the name 'x' is undefined. Really new at Python here obviously would appreciate any clarifications! :)
You're confusing defining functions with calling them. You should define then functions separately, then call them from within your loop.
def min_mth_pay(balance,monthlyPaymentRate):
x = balance * monthlyPaymentRate
return x
def balance(balance,min_mth_pay,annualInterestRate):
y=(balance - min_mth_pay)*((annualInterestRate/12)+1)
return y
a=0
while a<=11:
a +=1
x = min_mth_pay(balance,monthlyPaymentRate)
y = balance(balance,min_mth_pay,annualInterestRate)
print('Month:' + str(a) + 'Minimum monthly payment:' + str(x) + 'Remaining balance:' + str(y))
Note that it's not clear where balance, monthlyPaymentRate, min_mth_pay, and annualInterestRate are coming from in your code.

Beginner Python exercise

I'm having trouble solving problem 2 from this page
Here
Here's my code:
#Problem set 1 b
out_bal = float(raw_input("Enter the outstanding balance on your credit card: "))
ann_interest = float(raw_input("Enter the annual interest rate as a decimal: "))
min_pmnt = 10
months = 1
prev_bal = out_bal
month_interest = ann_interest / 12.0
updated_bal = prev_bal * (1 + month_interest) - min_pmnt
while out_bal > 0:
for i in range(1,13):
out_bal = updated_bal
prev_bal = out_bal
months += 1
if out_bal <= 0:
break
else:
min_pmnt = min_pmnt + 10
months = 0
print out_bal
print "RESULT"
print "Monthly payment to pay off debt in 1 year: $", min_pmnt
print "Number of months needed: ", months
print "Balance: ", round(out_bal, 2)
I want to take 1200 and .18 for the first two inputs, respectively. However when I do this the program gets caught in my while loop and keeps printing 1208.00.
When I read the code to myself it seems like it should be working. But I think I'm not using the prev_bal variable correctly.
Also, it's performing the math the way I expect it to the first time it goes through the loop but then it seems like it's not adding 10 to min_pmnt and going through the loop again. It seems like it's just using 10 over and over.
How can I write this so it does actually add 10 and perform the loop again?
Thanks!
Your problem is that updated_bal isn't changing, yet you are setting out_bal to it each time you iterate, and then conditioning the loop on out_bal becoming reduced in value.
It looks to me like you are thinking that updated_bal changes on each loop iteration, based on its component parts. In order for that to work, you would need to instead use a function that calculates an updated balance each time around.

Python - get while loop to run a certain amount of times

I am trying to get a while loop to function dur amount of times, however when I run it it just sits there, I assume calculating, seemingly forever. It is a simple script that shouldn't take very long to run, so I assume I have messed up the while loop.
Here is the code:
#Compound interest calculator
print "Enter amounts without $, years or %"
loan = input("How many dollars is your loan? ")
dur = input("How many years is your loan for? ")
per = input("What percent is the interest on your loan? ")
percent = per / 100
count = 0
#First calculation of amount
first = loan * percent
count = count + 1
#Continued calculation occurs until count is equal to the duration set by the user
while count <= dur:
out = first * percent
#Prints output
output = out + loan
print str(output)
There are a number of problems with your code.
percent will always be 0, because you are using integer division. Try percent = per / 100.0 instead.
As others have noted, you have to increase count to end the loop.
Without changing either first nor percent in the loop, the calculated value of out will be the same in each iteration of the loop. Try first = first * percent instead.
Finally, you do not need the loop at all. Just do this:
output = loan * (1 + per/100.)**dur
You need to increment count in the while loop, otherwise the stop condition (count <= dur) will never happen.
while count <= dur:
# do something
count += 1
If you know in advance the number of times you want to do something you could also use:
for i in xrange(dur): # use range if python3
# do something
Also note that your code has another problem: you're not really calculating compund interest. At every step you recalculate first * percent instead of adding percent to the previous interest. You should do:
# First calculation of amount
out = loan * percent
count = count + 1
while count <= dur:
out *= (1.0 + percent)
count += 1
count never changes within the loop. Do this
while count <= dur:
out = first * percent
count += 1

How do I update a single variable within a loop?

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.
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
I think I finally understand what your question is about and what's causing the problem -- namely a simple misspelling of a variable name. To fix it, just change the last line of the statements following the if in your while loop from:
if month > 12:
month = 0
g += 1
Cbalance = Balance
to:
if month > 12:
month = 0
g += 1
CBalance = Balance # note corrected spelling of variable name on left
Which explains why all the values weren't being reset. It would have been helpful if you explicitly mentioned which variable it was in your question if you knew it. Anyway, this sort of thing is more likely to happen when one uses Capitalized and mixedCase variable names as you are doing.
Many programmers try to avoid them for that reason, is especially with languages like Python where you generally don't have to declare variables before using them. You might want to check out the Naming Conventions section of PEP 8's style guidelines.
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.
I think what's happening is that each time you run this while you will get:
Payment = 10 * 1 //First while payment = 10
2nd time
Payment = 10 * 1 //payment = 10 again.
Which results in:
CBalance = CBalance * (1 + monthlyI) - 10
Which can never won't go to a negative value, which is needed to end the loop?
While you probably want:
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

Categories