I'm currently new to coding Python and am struggling with a small piece of code that I can't seem to figure out. My code essentially takes in a starting salary and outputs the salary increase over the course of how ever many years the user enters and makes a table out of the output. Everything in my code is correct except for one problem. I need to start the table with the starting salary that the user enters instead it starts the table with what you would make in year 2.
percent = float(input("Enter the annual percent increase: "))
years = int(input("Enter the number of years: "))
percent = percent / 100
print("%-7s%10s" % ("Year","Salary"))
for i in range(1,years):
starting += (starting * percent)
print("%2d%17.2f" % (i, starting))
Try swapping the order of the prints and the addition:
for i in range(1,years):
print("%2d%17.2f" % (i, starting))
starting += (starting * percent)
Try this
starting = 1000 # sample starting
percent = float(input("Enter the annual percent increase: "))
years = int(input("Enter the number of years: "))
percent /= 100
print("%-7s%10s" % ("Year", "Salary"))
for i in range(years):
print("%2d%17.2f" % (i, starting))
starting += (starting * percent)
Will give
Year Salary
0 1000.00
1 1030.00
2 1060.90
Related
I'm writing a program that asks a user to input a number of years. and then asks the user to input a yearly tax amount until the specified number of years is met. Then the program needs to output the maximum yearly income tax based on those user inputs. All of my program is working except for the maximum part. It keeps giving me a random number whenever I try to output a maximum value.
Is anyone able to tell me where I'm going wrong?
Below is my code:
`enter code here`
years = int(input('Number of years: '))
if years == 0:
print('Could not calculate maximum tax given.')
exit()
for i in range(years):
tax = input("Income tax given for year " +str(i+1)+ "($): ")
maximum = 0
for x in range(int(tax)):
if (maximum==0 or maximum<x):
maximum = x
print('Maximum tax given in a year($): ' + str(maximum))
You should add the tax input to a list, otherwise it will be overwritten. to get the max number you can use max().
years = int(input('Number of years: '))
if years == 0:
print('Could not calculate maximum tax given.')
exit()
tax=[]
for i in range(years):
tax.append(int(input("Income tax given for year " +str(i+1)+ "($): ")))
maximum = 0
for x in tax:
if (maximum==0 or maximum<x):
maximum = x
print('Maximum tax given in a year($): ' + str(maximum))
print('Maximum tax given in a year($): (using max()) ' + str(max(tax)))
The answer Kilian gave is spot on, just one suggestion though.
Python print of integers or Numbers should be like this:
print('Maximum tax given in a year($): (using max()) %d' %max(tax))
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).
This program starts with 1 cent and doubles each day. However, I'm stuck on trying to find a way to convert the number of pennies into a dollar and cent amount. For example, converting 1020 pennies to $10.20.
I'm also attempting to make it so if user input is not a positive number, the user will be continously prompted until they enter a positive number. This isn't working, however.
I also feel I've messed up by using range, as I want to enter a set number of days, say 16 days, and when I enter 16, I receive the days 1-17, as range should be doing, and I'm not sure how to go about fixing that.
b = int(input("Input number of days "))
if b > 0:
print(b)
else:
b = int(input("Days must be positive "))
print("Day 1:","1")
days = 1
aIncrement = 2
penny = 1
for i in range(b):
pAmount = int(penny*2)
addAmount = int(2**aIncrement -1)
aIncrement +=1
days +=1
penny *= 2
print("Day " + str(days) + ":",pAmount)
Your question has multiple parts, which is not ideal for stackoverflow, but I will try to hit them all.
Fixing the numeric values to show dollars and cents.
As noted in comments to other answers, division can often run into snags due to floating point notation. But in this case, since all we really care about is the number of times 100 will go into the penny count and the remainder, we can probably safely get away with using divmod() which is included with Python and calculates the number of times a number is divisible in another number and the remainder in whole numbers.
For clarity, divmod() returns a tuple and in the sample below, I unpack the two values stored in the tuple and assign each individual value to one of two variables: dollars and cents.
dollars, cents = divmod(pAmount, 100) # unpack values (ints)
# from divmod() function
output = '$' + str(dollars) + '.' + str(cents) # create a string from
# each int
Fixing the range issue
The range() function produces a number and you can set it to start and end where you want, keeping in mind that the ending number must be set at one value higher than you want to go to... i.e. to get the numbers from one to ten, you must use a range of 1 to 11. In your code, you use i as a placeholder and you separately use days to keep track of the value of the current day. Since your user will tell you that they want b days, you would need to increment that value immediately. I suggest combining these to simplify things and potentially using slightly more self-documenting variable names. An additional note since this starts off on day one, we can remove some of the setup code that we were using to manually process day one before the loop started (more on that in a later section).
days = int(input("Input number of days "))
for day in range(1, days + 1):
# anywhere in your code, you can now refer to day
# and it will be able to tell you the current day
Continuous input
If we ask the user for an initial input, they can put in:
a negative number
a zero
a positive number
So our while loop should check for any condition that is not positive (i.e. days <= 0). If the first request is a positive number, then the while loop is effectively skipped entirely and the script continues, otherwise it keeps asking for additional inputs. Notice... I edited the string in the second input() function to show the user both the problem and to tell them what to do next.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input positive number of days: "))
Putting all this together, the code might look something like this:
I put the items above together AND cleaned up a few additional things.
days = int(input("Input number of days "))
while days <= 0:
days = int(input("Days must be positive, input number of days: "))
# aIncrement = 2 # this line not needed
penny = 1
for day in range(1, days + 1):
pAmount = int(penny) # this line was cleaned up
# because we don't need to manually
# handle day one
dollars, cents = divmod(pAmount, 100)
output = '$' + str(dollars) + '.' + str(cents)
# addAmount = int(2**aIncrement -1) # this line not needed
# aIncrement +=1 # this line not needed
penny *= 2
print("Day " + str(day) + ":", output)
For the continuous prompting, you can use a while loop.
while True:
user_input = int(input("Enter the number"))
if user_input > 0:
break
else:
continue
Or alternatively:
user_input = int(input("Enter the number"))
while user_input <= 0:
user_input = int(input("Enter the number"))
For the range issue, you can add -1 to the parameter you're passing range.
for i in range(b - 1):
Suppose you have an investment plan where you invest a certain fixed amount at the beginning of every year. Compute the total value of the investment at the end of the last year. The inputs will be the amount to invest each year, the interest rate, and the number of years of the investment.
This program calculates the future value
of a constant yearly investment.
Enter the yearly investment: 200
Enter the annual interest rate: .06
Enter the number of years: 12
The value in 12 years is: 3576.427533818945
I've tried a few different things, like below, but it doesn't give me that 3576.42, it gives me only $400. Any ideas?
principal = eval(input("Enter the yearly investment: "))
apr = eval(input("Enter the annual interest rate: "))
years = eval(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print("The value in 12 years is: ", principal)
If it's a yearly investment, you should add it every year:
yearly = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
years = int(input("Enter the number of years: "))
total = 0
for i in range(years):
total += yearly
total *= 1 + apr
print("The value in 12 years is: ", total)
With your inputs, this outputs
('The value in 12 years is: ', 3576.427533818945)
Update: Responding to your questions from the comments, to clarify what's going on:
1) You can use int() for yearly and get the same answer, which is fine if you always invest a whole number of currency. Using a float works just as well but also allows the amount to be 199.99, for example.
2) += and *= are convenient shorthand: total += yearly means total = total + yearly. It's a little easier to type, but more important, it more clearly expresses the meaning. I read it like this
for i in range(years): # For each year
total += yearly # Grow the total by adding the yearly investment to it
total *= 1 + apr # Grow the total by multiplying it by (1 + apr)
The longer form just isn't as clear:
for i in range(years): # For each year
total = total + yearly # Add total and yearly and assign that to total
total = total * (1 + apr) # Multiply total by (1 + apr) and assign that to total
It can be done analytically:
"""
pmt = investment per period
r = interest rate per period
n = number of periods
v0 = initial value
"""
fv = lambda pmt, r, n, v0=0: pmt * ((1.0+r)**n-1)/r + v0*(1+r)**n
fv(200, 0.09, 10, 2000)
Similarly, if you are trying to figure out the amount you need to invest so you get to a certain number, you can do:
pmt = lambda fv, r, n, v0=0: (fv - v0*(1+r)**n) * r/((1.0+r)**n-1)
pmt(1000000, 0.09, 20, 0)
As suggested in the comments, you shouldn't use eval() here. (More info on eval can be found in the Python Docs). -- Instead, change your code to use float() or int() where applicable, as shown below.
Also, your print() statement printed out the parenthesis and comma, which I expect you didn't want. I cleaned it up in the code below, but if what you wanted is what you had feel free to put it back.
principal = float(input("Enter the yearly investment: "))
apr = float(input("Enter the annual interest rate: "))
# Note that years has to be int() because of range()
years = int(input("Enter the number of years: "))
for i in range(years):
principal = principal * (1+apr)
print "The value in 12 years is: %f" % principal
I am a python/programming beginner. I was assigned a problem on MIT open courseware to:
Write a program that calculates the minimum fixed monthly payment in order to pay off a credit card balance within 12 months.
Take as raw_input() the following floating point numbers:
1) the outstanding balance on the credit card
2) the annual interest rate as a decimal
Print out the fixed minimum payment, number of months(at most 12 and possibly less than 12) it takes to pay off the debt, and the balance (likely to be a negative number).
Assume the interest is compounded monthly according to the balance at the start of the month(before the payment for that month is made). The monthly payment must be a multiple of $10 and is the same for all months. Notice that it is possible for the balance to become negative using this payment scheme.
THE ANSWER IS:
balance = float(raw_input('Enter the outstanding balance on your credit card: '))
interest = float(raw_input('Enter the annual credit card interest rate as a decimal: '))
minPay = 10
newBalance = balance
while balance > 0:
for month in range(1,13):
newBalance = newBalance*(1+(interest/12))-minPay
if newBalance <=0:
break
if newBalance <= 0:
balance = newBalance
else:
newBalance = balance
minPay = minPay+10
print 'RESULT'
print 'Monthly payment to pay off debt in 1 year: ' + str(minPay)
print 'Number of months needed: ' + str(month)
print 'Balance: ' + str(round(balance,2))
MY QUESTIONS:
1) Using 1200 as the raw input balance, and .18 as the interest rate. Could someone explain in words how you would arrive at minPay = 120, month = 11, and balance = - 10.05?
I am confused by the newBalance = newBalance* (1 +(interest/12)) - minPay.
Using 1200 as the balance would make newBalance = 1200 * (1 +(.18/12)) - 10 = 1218 - 10 = 1208.
2) Since newBalance is not <= 0 the program would then proceed to the else statement. What is happening with the newBalance = balance part of the else statement. Does that assign newBalance back to 1200(original balance input).
I am having some trouble understanding this problem. Any insight whatsoever would be appreciated.
I would strongly recommend going through each line of the code as a python interpreter would and then seeing, why the program does perform as expected.
If you are lazy for that, try to put a print statement within the loop itself to see what the values of each variable are at every step. This always helps me figure out, what the code is doing.
As for your questions,
Yes, New balance does have the value that you expect it to have
Yes, it does get reassigned to balance, in the else part. You might want to change this.
As, I do not understand what the code is actually trying to do, I cannot help you with what the correct approach is, but try to add print statements, and it should help. Good Luck!
What is happening with the newBalance = balance part of the else statement? Does that assign newBalance back to 1200(original balance input).
Yes that's it. Then the minPay is increased and the loop starts again.
As minPay increases at each iteration, newBalance will end being negative.
balance = 3329
annualInterestRate = 0.2
minimum_fixed_payment = 10
unpaid_balance = balance
MonthlyInterestRate = annualInterestRate / 12
month_count = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
while balance > 0:
for month in month_count:
unpaid_balance = unpaid_balance - minimum_fixed_payment
interest = MonthlyInterestRate * unpaid_balance
unpaid_balance = unpaid_balance + interest
if unpaid_balance <= 0:
break
if unpaid_balance <= 0:
balance = unpaid_balance
else:
unpaid_balance = balance
minimum_fixed_payment = minimum_fixed_payment + 10
print "Lowest Payment: %s" % (minimum_fixed_payment)
The easiest way to answer this question would be to see it from this angle and that is, using the minimum fixed payment, we subtract the minimum fixed payment from the unpaid balance every month and check if the value left is lesser than 0. if it is not we increase the minimum fixed payment by 10 and repeat the process until we have a balance that is lesser than or equal to zero.
That is the modification I made to the code.