def compound_interest(P, r, n, Y):
'''
Computes the future value of investment after Y years
P: initial investment principal
r: the annual interest rate
n: the number of times per year interest will be compounded
Y: the number of years over which to invest
P = float(input("Enter your starting principal ($): "))
r = float(input("Enter the annual interest rate (value between 0 and 1): "))
n = float(input("Enter the number of times per year to compound interest: "))
Y = float(input("Enter the number of years over which to invest: "))
returns: the future value of investment
'''
compound_interest = ((P)((1+(r/n))**(ny)))
print("After 10 year (s), you will have", "$" + str(compound_interest))
return compound_interest
Here is a solution to your problem:
import math
def compound_interest():
P = float(input("Enter your starting principal ($): "))
r = float(input("Enter the annual interest rate (value between 0 and 1): "))
n = float(input("Enter the number of times per year to compound interest: "))
Y = float(input("Enter the number of years over which to invest: "))
cpd_interest = P * math.pow(r+1, n * Y)
print("After {} year (s), you will have {} $".format(Y, cpd_interest))
return cpd_interest
compound_interest()
I've removed the parameters you give in your function, because you don't need them if you ask for them as input()
from the user.
I also improved your calculation: When you want to calculate the interest it should be the starting principal * (the interest percentage +1 to the power (number of years times number of times per year)). I used the math.pow() function for this, and you can see here how it works exactly.
I renamed the variable name from compound_interest to cpd_interest, as it's a bad idea to have variable names the same name as your function.
I also rewrote your print statement, and used a replacement field to correctly format the invested years & interest. You cannot return inside a print statement, returning is always the last thing the function does (unless it returns nothing).
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.