I need some help in this program. I need help figuring out how to make it calculate interest for a period over ten years (including the first one). This is as far as i have gotten on my own. I would greatly appreciate some insight to this problem.
Thanks.
*The "print() is just for spacing so that the program looks cleaner.
p= int(input(" Intial Amount? "))
print()
r= float(input(" Rate? (Decimal) "))
print()
n= int(input(" Number Of Times Compunded? (Yearly) "))
print()
t= float(input(" Number Of Years? "))
A= p*(1+r/n)**(n*t)
print()
print( " Interest At Final Year","$",format(A, ',.2f'))
print()
for i in range (10):
print(format(i+1, '3')," Year","Interest","$",format(A,',.2f'))
In the body of your loop, you are not updating the values of any of the variables. You need to update A at every iteration or store the intermediate results in some other variable. As an example, see the following:
def compound_interest(r, n, initial):
current_value = initial
for i in range(n):
current_value *= (1 + r)
print(current_value)
I use the current_value variable to save the intermediate results of the loop. If I had simply done initial * (1 + r) at every iteration then the value of initial would never change; the result of the calculation must be saved if you want to keep using it.
At the very end of the program it will count 1-10 but it will have the same amount as the first calculation.
Yes, that's because the only thing that happens in that loop is the print call. You're just calculating A all at once, before you get into the loop, and then using the same A over and over again.
I need help making it add the new values to add up while the "n" and the "p" are changing.
Well, you aren't changing n or p, and I don't think you need to. But you do need to change something. If you want to print a different value of A each time through the loop, you have to recalculate next year's A based on the previous year's A, or whatever else goes into determining the right value.
For example:
for year in range (10):
jan1balance = p
for period in range(n):
p = p * (1 + r)
print(format(year+1, '3')," Year","Interest","$",format(p - jan1balance,',.2f'))
Or:
for year in range (10):
yearlyinterest = 0
for period in range(n):
periodinterest = p * r
yearlyinterest += periodinterest
p += periodinterest
print(format(year+1, '3')," Year","Interest","$",format(yearlyinterest,',.2f'))
Related
I've been coding for about 3 months. Could someone help me understand why my code isn't working? I could look up the answer, but I'd really like to figure out what is going wrong. It runs perfectly the first time through the code, but while it is While-Looping, x always stays as the number inserted into the function. Thanks for your help! The assignment and code is below (for an Udemy class).
Happy Numbers -
A happy number is defined by the following process. Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers, while those that do not end in 1 are unhappy numbers. Display an example of your output here. Find first 8 happy numbers.
def find_happy_number(x):
#we need a bunch of lists
digit_list = []
squared_list = []
result_list = []
happy_numbers = []
unhappy_numbers = []
while True:
#break our number into digits
x = str(x)
for digit in x:
digit_list.append(int(digit))
#square each digit and store in list
for digit in digit_list:
squared_digit = digit**2
squared_list.append(squared_digit)
#adds all numbers on that list
result = sum(squared_list)
print(result)
#check to see if it is a happy number
if result == 1:
print(f'{x} is a happy number!')
break
#check to see if it is an un-happy number
if result in result_list:
print(f'{x} is an UN-happy number!')
break
#if it isn't we continue the churning.
#adds result to result list to see if we are looping infinitally
x = result
result_list.append(result)
`
The PROBLEM is that you are not resetting digit_list and squared_list in every loop, so they just keep getting bigger and bigger. Move their initialization into the while loop, or use a list comprehension instead of a loop.
Consider this for your loop:
while True:
digit_list = [int(digit) for digit in str(x)]
squared_list = [digit**2 for digit in digit_list]
Now you don't need to initialize them. Or, for extra fun, combine it all into one:
while True:
result = sum(int(digit)**2 for digit in str(x))
The purpose of this program is to find the smallest and largest values in a list. The moment the user inputs a negative number, the program should stop. Here is the code I have written so far:
user_inputs = []
number = int(input())
for i in range(number):
value = int(input())
if i >= 0:
user_inputs.append(value)
else:
break
print(min(user_inputs))
print(max(user_inputs))
As you can see, I am new to programming and still struggling to find the logic behind loops. Surely, this code is ridden with mistakes and any helpful improvements is much appreciated. Thanks in advance.
Brother one mistake that you have done is that you are using
for i in range(number):
basically by doing this you are telling compiler that repeat the code in for loop for "number" of times and obviously number would change every time user inputs a new number resulting in error
The right way to make the code do what you want is :
user_inputs = []
while True:
number = int(input('Enter a positive number : '))
if number >= 0 :
user_inputs.append(number)
else:
print(user_inputs)
print('Smallest number in list is : ',min(user_inputs))
print('Largest number in list is : ',max(user_inputs))
break
Here while loop will run continuously until a negative number has been input, so when a negative number is input the while loop woulb break .
You are checking
i
when you should be checking
value
you have to compare value
i.e. if value >= 0
you are using i which is the number of iteration
I need to make a python function where i can find the surface with the riemann sum. This is what i have , and with the feedback of my teacher i am very close to it, but it does not work as properly as i want. the teacher said also something about try-catch what means that i need to make an extra code to control the answer (if im not wrong) To find the surface the uppper and the lower limits are asked and how many rectangles you want under the line like in the program.
(edit) I have made a new program , could you guys check if this is correct.
import math
def f(x): return math.sqrt(x) #Function in the left!
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
n = int(input("How many division intervals do you want?:"))
dx = (b-a)/n;
xi = 0;
sum = 0;
for i in range(n):
xi = xi+dx;
sum = sum + f(xi)
print("The surface under the line is ", (sum*dx))
#einde programma!
import math
def f(x):
return math.sqrt(x) #Function in the left!
def positiveinput(message):
while True:
try:
c = int(input(message))
if c <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?: ")
b = positiveinput("What is the upperlimit?: ")
c = positiveinput("How many division intervals do you want?: ")
a = int(input("What is the lowerlimit?:"))
b = int(input("What is the upperlimit?:"))
c = int(input("How many division intervals do you want?:"))
dx = float((b-a)/c)
xi = a
Sum = dx
for i in range(0,c):
xi = a - dx
Sum = Sum + f(xi)
print("The surface under the line is ", (sum*dx))
There are a few issues with the code above:
1) Most importantly, You don't actually calculate the correct answer because you are assuming that the lower limit is equal to 0. Instead of writing xi=0 you should be writing xi=a!!! (Note that this will use the far end of each rectangle to calculate the height - if you want to use the lower end, and don't want to change any other code you will need to write xi = a - dx so you start on a. (Having said that, I wouldn't do it this way, but this is how to fix this without changing anything else).
2) Validation errors: There are a few things you should check:
That the values of a, b are valid numbers (note they shouldn't really have to be integers, just numbers). You can use float() to convert something to a number, just as you would use int() to convert to an integer.
that n is an integer and is not equal to 0, as that will raise an error, when you try and divide by n,
that n is not negative, as this will result in you getting the wrong value (with the code as it is).
Having said that, I would not write the code as it is. Using a for-loop and then incrementing your value is not a very pythonic thing to do. You might be interested to learn you can actually specify a lower bound and an upper bound using the range function. Experiment with:
for i in range(3,11,0.5):
print(i)
See what happens. I'm not going to give you a full solution, as this is a homework assignment, and it will benefit you most to work it out yourself, but hopefully this points you these things will point you in the right direction.
As #Sadap said, you can try something like this:
def positiveinput(message):
while True:
try:
n = int(input(message))
if n <= 0:
raise ValueError
break
except ValueError:
print("Oops! That was no valid number. Try again...")
a = positiveinput("What is the lowerlimit?:")
b = positiveinput("What is the upperlimit?:")
n = positiveinput("How many division intervals do you want?:")
Having this code as a guide, you can complete the list of errors verification that #tim-mccurrach have written in an answer to this post. Also you can check out this link where they make the Riemann Sum in a different way. For documentation about try-catch you can enter this link.
So this code is meant to return the final error and the final logarithm of a number inputted by a user. Now my issue is that it doesn't run the loop, it just keeps going over the same number and it never ends. I am not sure if I have my print statements in the wrong area, or if I am doing the loop wrong but I want the loop to end when the error is less then 1x10^-9. It's possible my iterations are set up wrong too, not really sure what I messed up on here.
import math
import sys
#Computing natural log of x
#x value is input here
x = float(input("Please input a positive number: "))
#If x is not positive then program will not work, so it will exit
if x<=0:
print("Your number is not positive. System Shutdown.")
sys.exit()
#Retrieving ln(x) using the math command
lnx0 = math.log(x)
#Formula for approximate ln
xfrac = (x - 1)/(x + 1)
lnx = 0 #Initializing the approximating
i=0
#This is the code to make it go until it hits the error we want
while True:
ex = 2*i - 1
lnx += 2.0* (xfrac**ex / ex)
#Counter adding 1 to it
i+=1
#This is the error
err = math.fabs(lnx0 - lnx)
if err<0.0000000001:
break
#Priting approximate ln at end of loop
print ("ln(x) at " ,x,"is: " ,lnx)
#Final Error
print ("Final error is:" ,err)
#Number of itterations
#Printing accurate version of ln(x) just to see what it should be
print ("Your accurate value of ln(x) is: " ,lnx0)
I'm assuming you're using the fourth formula on this page to approximate the log function. If so, your i is starting at the wrong value; you've initialized it to 0 here, but it needs to start at 1.
Also, if you only want output after the answer has been found, rather than once per iteration, your print functions should be de-indented so they are outside the loop. Try:
import math
import sys
#Computing natural log of x
#x value is input here
x = float(input("Please input a positive number: "))
#If x is not positive then program will not work, so it will exit
if x<=0:
print("Your number is not positive. System Shutdown.")
sys.exit()
#Retrieving ln(x) using the math command
lnx0 = math.log(x)
#Formula for approximate ln
xfrac = (x - 1)/(x + 1)
lnx = 0 #Initializing the approximating
i=1
#This is the code to make it go until it hits the error we want
while True:
ex = 2*i - 1
lnx += 2.0* (xfrac**ex / ex)
#Counter adding 1 to it
i+=1
#This is the error
err = math.fabs(lnx0 - lnx)
if err<0.0000000001:
break
#Priting approximate ln at end of loop
print ("ln(x) at " ,x,"is: " ,lnx)
#Final Error
print ("Final error is:" ,err)
#Number of itterations
#Printing accurate version of ln(x) just to see what it should be
print ("Your accurate value of ln(x) is: " ,lnx0)
Result:
Please input a positive number: 5
ln(x) at 5.0 is: 1.6094379123624052
Final error is: 7.169509430582366e-11
Your accurate value of ln(x) is: 1.6094379124341003
Thanks to DSM for identifying the formula and possible fix
There are several problems with this. The first is that your computations are incorrect. I tried entering 'e' to 9 places. Your estimate, lnx, quickly degenerates to -3.3279+ and sticks there. This dooms you to an infinite loop, because the estimate will never get near the true value.
Others have already pointed out that you haven't traced your computations with print statements. I'll add another hint from my days in numerical analysis: use a restricted "for" loop until you've debugged the computations. Then trade it in for a "while err > tolerance" loop.
To address your most recent comment, you're not getting the same numbers. The first few terms are significant, but the infinite sequence quickly drops close to 0, so the additions don't show up after about 15-20 iterations.
Also print out ex and lnx values within the loop. Especially check the first one, where your exponent is -1; I believe that you've started the loop in the wrong place.
Finally, you might find this loop form a little easier to read. Get rid of your if...break statement and use this instead:
i = 1
err = 1
tolerance = 1e-10
# This is the code to make it go until it hits the error we want
while err >= tolerance:
I have an assignment for Python to take 2 user inputted numbers (making sure the 1st number is smaller than the second) and to find numbers that are multiples of the first, and divisors of the second.. I'm only allowed to use a while loop (new condition my teacher added today..) I've done it with a for loop:
N_small = int(input("Enter the first number: "))
N_big = int(input("Enter the second number: "))
numbers = ""
if N_small > N_big:
print("The first number should be smaller. Their value will be swapped.")
N_small, N_big = N_big, N_small
for x in range(N_small, N_big+1, N_small):
if N_big % x == 0:
numbers += str(x) + " "
print("The numbers are: ", numbers)
I'm not asking for the answer to how to do this with a while loop - but I just need a hint or two to figure out how to start doing this... Can anyone enlighten me?
Thanks
You can convert any for loop into a while loop trivially. Here's what a for loop means:
for element in iterable:
stuff(element)
iterator = iter(iterable)
while True:
try:
element = next(iterator)
except StopIteration:
break
stuff(element)
Of course that's not what your teacher is asking for here, but think about how it works. It's iterating all of the values in range(N_small, N_big+1, N_small). You need some way to get those values—ideally without iterating them, just with basic math.
So, what are those values? They're N_small, then N_small+N_small, then N_small+N_small+N_small, and so on, up until you reach or exceed N_big+1. So, how could you generate those numbers without an iterable?
Start with this:
element = N_small
while element ???: # until you reach or exceed N_big+1
stuff(element)
element ??? # how do you increase element each time?
Just fill in the ??? parts. Then look out for where you could have an off-by-one error that makes you do one loop too many, or one too few, and how you'd write tests for that. Then write those tests. And then, assuming you passed the tests (possibly after fixing a mistake), you're done.
You don't have to iterate over all the numbers, only the multiples...
small, big = 4, 400
times = 1
while times < big / small:
num = times * small
if big % num == 0: print(num)
times += 1