python multiply your last answer by a constant - python

so I'm trying to display salary with annual % increase for certain amount of years
print('Enter the strting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())
calculation1 = ANNUAL_INCREASE / 100
calculation2 = calculation1 * SALARY
calculation3 = calculation2 + SALARY
Yearloops = int(input('Enter number of years: '))
for x in range(Yearloops):
print(x + 1, calculation3 )
This is my output so far by entering 25000 as salary, 3 as % increase and 5 for years.
1 25750.0
2 25750.0
3 25750.0
4 25750.0
5 25750.0
I need to multiply the last answer again by the % increase. Should be like this
1 25000.00
2 25750.00
3 26522.50
4 27318.17
5 28137.72
Can someone show me how to do it? Thanks.

You need to put your calculations inside your for loop so that it occurs every year instead of just once
salary = float(input('enter starting salary: '))
annual_increase = float(input('enter the annual % increase: '))
years = int(input('enter number of years: '))
for x in range(years):
print(x + 1, salary)
increase = (annual_increase/100) * salary
salary += increase
Entering 25000, 3%, and 5 years outputs
1 25000.0
2 25750.0
3 26522.5
4 27318.175
5 28137.72025

Adapting a bit your version of the code:
print('Enter the strting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())
Yearloops = int(input('Enter number of years: '))
value = SALARY
for x in range(Yearloops):
print('{} {:.2f}'.format(x + 1, value))
value = value * (1 + ANNUAL_INCREASE/100)
This produces the following output with the test case 25000, 3, 5:
Enter the strting salary: 25000
Enter the annual % increase: 3
Enter number of years: 5
1 25000.00
2 25750.00
3 26522.50
4 27318.17
5 28137.72

I think this will do what you are looking for:
print('Enter the strting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())
calculation1 = ANNUAL_INCREASE / 100
Yearloops = int(input('Enter number of years: '))
newsalary = SALARY
print(1, newsalary )
for x in range(1,Yearloops):
newsalary = newsalary*(1+calculation1)
print(x + 1, newsalary )
I printed the first year outside the loop since we don't want to calculate an increase yet, according to your spec.

This seems like a pretty straightforward solution to your problem. For your knowledge: it is common to use for _ in something when you aren't actually going to use the item you're iterating over.
print('Enter the starting salary: ', end ='')
SALARY = float(input())
print('Enter the annual % increase: ', end ='')
ANNUAL_INCREASE = float(input())
Yearloops = int(input('Enter number of years: '))
for _ in range(Yearloops):
print(SALARY)
SALARY += (SALARY / 100) * ANNUAL_INCREASE

Related

Right justify an f-string with multiple columns of data

Help me!! It's not justified (python)
# Accept the inputs
startBalance = float(input("Enter the investment amount: "))
years = int(input("Enter the number of years: "))
rate = int(input("Enter the rate as a %: "))
# Convert the rate to a decimal number
rate = rate / 100
# Initialize the accumulator for the interest
totalInterest = 0.0
# Display the header for the table V.3
print("%4s%18s%10s%16s" % \
("Year", "Starting balance",
"Interest", "Ending balance"))
# f string
# Compute and display the results for each year
for year in range(1, years + 1):
interest = startBalance * rate
endBalance = startBalance + interest
print(f"{year:>4}{startBalance:<18.2f}{interest:>10.2f}{endBalance:>16.2f}")
startBalance = endBalance
totalInterest += interest
# Display the totals for the period
print("Ending balance: $%0.2f" % endBalance)
print("Total interest earned: $%0.2f" % totalInterest)
I was trying to align data in a table on the right side of the column. I use f string and formatting type in the variable placeholder but there was no alignment.
I try to run the code on jupyter and VS Code.
There is no need to mix different template systems. Just use f-strings:
pv = float(input('Enter the investment amount: '))
years = range(int(input('Enter the number of years: ')))
rate = int(input('Enter the rate as a %: ')) / 100
interests = 0.0
print('Year Starting balance Interest Ending balance')
for year in years:
interest = pv * rate
fv = pv + interest
print(f'{year + 1:>4d}{pv:>17.2f}{interest:>10.2f}{fv:>16.2f}')
pv = fv
interests += interest
print(f'Ending balance: ${fv:0.2f}')
print(f'Total interest earned: ${interests:0.2f}')
And here is an example of the output:
Enter the investment amount: 200
Enter the number of years: 10
Enter the rate as a %: 15
Year Starting balance Interest Ending balance
1 200.00 30.00 230.00
2 230.00 34.50 264.50
3 264.50 39.67 304.18
4 304.18 45.63 349.80
5 349.80 52.47 402.27
6 402.27 60.34 462.61
7 462.61 69.39 532.00
8 532.00 79.80 611.80
9 611.80 91.77 703.58
10 703.58 105.54 809.11
Ending balance: $809.11
Total interest earned: $609.11

What changes should I do for the output to display with two decimal places?

I want my output to have a 2 decimal places result. What should I do?
Ideal output is:
Enter the number of plants to purchase: 14
Enter the price per unit of plant: 250.00
The total payable amount is: P3,350.00
n1 = input('Enter number of plants: ')
n2= input('Enter price per unit: ')
mul= float(n1) * float(n2)
mul2= (float(n1)-float(10)) * (float(n2))
mul3 = float(10) * float(n2)
discount2 = float (mul2)* float(0.15)
total2=mul2-discount2
total3= total2+mul3
if float(n1)<=float(10):
mul= float(n1) * float(n2)
print('The total payable amount is: ', mul)
elif float(n1)>float(10):
print('The total payable amount is: ', total3)
A few answers missed the fact you also needed thousands separated by a comma. here is the format command which displays the price the way you expect it
n1 = input('Enter number of plants: ')
n2= input('Enter price per unit: ')
mul= float(n1) * float(n2)
mul2= (float(n1)-float(10)) * (float(n2))
mul3 = float(10) * float(n2)
discount2 = float (mul2)* float(0.15)
total2=mul2-discount2
total3= total2+mul3
if float(n1)<=float(10):
mul= float(n1) * float(n2)
print('The total payable amount is: ${:0,.2f}'.format(mul))
elif float(n1)>float(10):
print('The total payable amount is: ${:0,.2f}'.format(total3))
Use a formatted string. Also, convert the values to floats at the start, then there is no need to keep converting everything.
plants_str = input('Enter number of plants: ')
price_str = input('Enter price per unit: ')
plants = float(plants_str)
price = float(price_str)
total = plants * price
if plants > 10:
total -= 0.15 * (plants - 10) * price
print(f"The total payable amount is: {total:0,.2f}")
But as noted in a comment, for serious applications involving currency you should use the decimal library. This ensures decimal numbers are represented exactly.
from decimal import Decimal
plants_str = input('Enter number of plants: ')
price_str = input('Enter price per unit: ')
plants = Decimal(plants_str)
price = Decimal(price_str)
total = plants * price
if plants > 10:
total -= Decimal("0.15") * (plants - 10) * price
print(f"The total payable amount is: {total:0,.2f}")
You can use the str.format function and I made some small adjustments to your code.
n1 = float(input('Enter number of plants: '))
n2 = float(input('Enter price per unit: '))
mul = n1 * n2
if n1<=10:
print('The total payable amount is: ${:0,.2f}'.format(mul))
else:
print('The total payable amount is: ${:0,.2f}'.format(0.85*mul+1.5*n2))

How to print results in python for every year up to a requested year

I have a working code
I have a working code, which gives the correct answer, however I cant figure out how to get it to print the amount for each year (for example if i enter 5yrs it will only give the amounts for the fifth year. I want it to print year 1, 2, 3 ,4 and 5 (print results for every year up to the entered year)
InvestAmount = int(input("Enter the intial investment amount: "))
Years = int(input("Enter the number of years to invest: "))
Rate = float(input("Enter the intrest rate (as %): "))
TotalInterestEarned = 0
for i in range(Years):
InterestEarned = round(InvestAmount*(Rate/100),2)
EndingBal = round(InvestAmount+InterestEarned , 2)
print("Starting Balance: $"+ str (InvestAmount))
print("Ending balance: $"+str(EndingBal))
print("Total Interest Earned: $"+str(InterestEarned))
This gonna help you
InvestAmount = int(input("Enter the intial investment amount: "))
Years = int(input("Enter the number of years to invest: "))
Rate = float(input("Enter the intrest rate (as %): "))
TotalInterestEarned = 0
for i in range(Years):
InterestEarned = round(InvestAmount*(Rate/100),2)
EndingBal = round(InvestAmount+InterestEarned , 2)
print(f"{i+1} year - Starting Balance: ${InvestAmount}")
print(f"{i+1} year - Ending balance: ${EndingBal}")
print(f"{i+1} year - Total Interest Earned: ${InterestEarned}")
Modify your for loop like this:
for i in range(Years):
InterestEarned = round(InvestAmount*(Rate/100),2)
EndingBal = round(InvestAmount+InterestEarned , 2)
print("Year" + i+1 + " Interest Earned: $" + InterestEarned)
print("Year" + i+1 + " Balance: $" + EndingBal)
Shift your print statements to the for loop and print i as well
for i in range(Years):
InterestEarned = round(InvestAmount*(Rate/100),2)
EndingBal = round(InvestAmount+InterestEarned , 2)
print("Starting Balance: for year " +(i+1)+"$"+str (InvestAmount))
print("Ending balance: for year" +(i+1)+"$"+str(EndingBal))
print("Total Interest Earned: for year" +(i+1)
+"$"+str(InterestEarned))

Python: for loop with counter and scheduled increase in increase

Python Learner. Working on a recurring monthly deposit, interest problem. Except I am being asked to build in a raise after every 6th month in this hypothetical. I am reaching the goal amount in fewer months than I'm supposed to.
Currently using the % function along with += function
annual_salary = float(input("What is your expected Income? "))
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment= total_cost*.25
savings = 0
for i in range(300):
savings = monthly_savings*(((1+.04/12)**i) - 1)/(.04/12)
if float(savings) >= down_payment:
break
if i % 6 == 0 :
monthly_salary += monthly_salary * .03
monthly_savings = monthly_salary * portion_saved
Thanks for the advice all. My code is getting clearer and I reached correct outputs! The problem was with how and when I was calculating interest. In the case of a static contribution I successfully used the formula for interest on a recurring deposit, here, the simpler move of calculating interest at each month was needed to work with the flow of the loop.
annual_salary = float(input("What is your expected Income? "))
portion_saved = float(input("What percentage of your income you expect to save? "))
total_cost = float(input("what is the cost of your dream home? "))
semi_annual_raise = float(input("Enter your expected raise, as a decimal "))
monthly_salary = float(annual_salary/12)
monthly_savings = monthly_salary * portion_saved
down_payment = total_cost*.25
savings = 0
month = 1
while savings < down_payment :
print(savings)
savings += monthly_savings
savings = savings * (1+(.04/12))
month += 1
if month % 6 == 0 :
monthly_salary += (monthly_salary * semi_annual_raise)
monthly_savings = (monthly_salary * portion_saved)
print("")
print("it will take " + str(month) + " months to meet your savings goal.")
Does something like this work for you? Typically, we want to use while loops over for loops when we don't know how many iterations the loop will ultimately need.
monthly_savings = 1.1 # saving 10% each month
monthly_salary = 5000
down_payment = 2500
interest = .02
savings = 0
months = 0
while savings < goal:
print(savings)
savings = (monthly_salary * monthly_savings) + (savings * interest)
months += 1
if months % 6 == 0 :
monthly_salary += monthly_salary * .03
print("Took " + str(months) + " to save enough")

Using max() and min() unsuccessfully in Python array

Context: Continuing with my self-learn of Python, I recently completed a textbook exercise that asked for a program that allowed the user to define 'x' number of years and to be able to input, for every month in 'x', a value for rainfall.
Issue: Below is my code, which works 'ok', however the latest exercise demands I 'expand' my code to present the numerically largest and smallest user input rainfall value, in a print statement.
Disclosure: I have looked on S.O to try finding the solution to my question, but nothing seems to be close enough to my challenge, to help me.
What I've tried: I have tried using max() and min() however I keep getting a TypeError: 'int' object is not iterable when I type the code print(max(monthlyRainfall) or print(min(monthlyRainfall)
def yearsToTrack():
userYearsTracking = int(input("How many years do you want to track: "))
return userYearsTracking
def calculationAlgorithm(userYearsTracking):
totalMonths = 0
totalRainfall = 0
for currentYear in range (1, userYearsTracking +1):
for currentMonth in range (1, 13):
monthlyRainfall = int(input("Inches of rainfall for month " + format(currentMonth, "d",) + " | year " +
format(currentYear, "d",)+": "))
totalMonths += 1
totalRainfall += monthlyRainfall
averageRainfall = totalRainfall / totalMonths
print("Total months: " + str(totalMonths))
print("Total rain:", format(totalRainfall), "(inch)")
print("Total average rainfall:", round(averageRainfall,2), "(inch)")
def main():
userYearsTracking = yearsToTrack()
calculationAlgorithm(userYearsTracking)
main()
Is anyone able to offer some 'pointers' as to where I am going wrong?
You can use sys.maxsize and 0 to intilize variables for tracking the minimum and maximum rainfall values that realistically the user will never enter above above or below respectively.
However for the second case just to make sure you can also add a simple check to ensure the user does not enter a negative rainfall amount:
def calculationAlgorithm(userYearsTracking):
totalMonths = 0
totalRainfall = 0
maxRainfall = 0
minRainfall = sys.maxsize
for currentYear in range (1, userYearsTracking +1):
for currentMonth in range (1, 13):
monthlyRainfall = int(input("Inches of rainfall for month " + format(currentMonth, "d",) + " | year " +
format(currentYear, "d",)+": "))
if monthlyRainfall < 0:
print("Error invalid rainfall entered")
sys.exit()
if monthlyRainfall > maxRainfall:
maxRainfall = monthlyRainfall
if monthlyRainfall < minRainfall:
minRainfall = monthlyRainfall
totalMonths += 1
totalRainfall += monthlyRainfall
averageRainfall = totalRainfall / totalMonths
print("Total months: " + str(totalMonths))
print("Total rain:", format(totalRainfall), "(inch)")
print("Total average rainfall:", round(averageRainfall,2), "(inch)")
print("Largest input rainfall: " + str(maxRainfall))
print("Smallest input rainfall: " + str(minRainfall))
Try out the full program with above changes here.
Example Usage:
How many years do you want to track: 1
Inches of rainfall for month 1 | year 1: 2
Inches of rainfall for month 2 | year 1: 2
Inches of rainfall for month 3 | year 1: 2
Inches of rainfall for month 4 | year 1: 2
Inches of rainfall for month 5 | year 1: 4
Inches of rainfall for month 6 | year 1: 1
Inches of rainfall for month 7 | year 1: 2
Inches of rainfall for month 8 | year 1: 2
Inches of rainfall for month 9 | year 1: 2
Inches of rainfall for month 10 | year 1: 2
Inches of rainfall for month 11 | year 1: 2
Inches of rainfall for month 12 | year 1: 2
Total months: 12
Total rain: 25 (inch)
Total average rainfall: 2.08 (inch)
Largest input rainfall: 4
Smallest input rainfall: 1
N.B. I have only used camelCase in naming the new variables as that is the style you are using. I would recommend changing all the names of the variables in your program to snake_case as that is the convention in python.
Python's built-in min() and max() functions expect iterable object like list, set, etc. I think you are putting only one integer which is not so correct (how can you pick min or max number when only 1 number given - obviously it is bot min and max).
One way of doing this would be:
declare list var:
rainfallList = []
Then when you get monthlyRainfall, you should add this code:
rainfallList.append(monthlyRainfall)
After all for loops you can use min(rainfallList) and/or max(rainfallList)
So your final code should be:
def yearsToTrack():
userYearsTracking = int(input("How many years do you want to track: "))
return userYearsTracking
def calculationAlgorithm(userYearsTracking):
totalMonths = 0
totalRainfall = 0
rainfallList = []
for currentYear in range (1, userYearsTracking +1):
for currentMonth in range (1, 13):
monthlyRainfall = int(input("Inches of rainfall for month " + format(currentMonth, "d",) + " | year " +
format(currentYear, "d",)+": "))
totalMonths += 1
rainfallList.append(monthlyRainfall)
totalRainfall += monthlyRainfall
averageRainfall = totalRainfall / totalMonths
print("Total months: " + str(totalMonths))
print("Total rain:", format(totalRainfall), "(inch)")
print("Total average rainfall:", round(averageRainfall,2), "(inch)")
print("Min rain:", format(min(rainfallList)), "(inch)")
print("Max rain:", format(max(rainfallList)), "(inch)")
def main():
userYearsTracking = yearsToTrack()
calculationAlgorithm(userYearsTracking)
main()

Categories