Working with multiple input variables in Python 3 - python

So I'm very new to coding and I'm learning python so I decided I'd try to make a loan calculator. I made it so when the user inputs their principle, interest rate, and years required to pay the loan in full, it will output their annual payment, their monthly payment, and their total payment for the loan. I made this and it worked. I decided to take it a step further and make it so that after this, if the user inputs their annual income, it will compare their monthly income to their monthly payment and tell them if they need to refinance or not.
Here's the program I made:
principle = float(input("Principle: ")) #principle = the amount of dollars borrowed
rate = float(input("Rate: ")) #rate = the interest rate that is charged each year on unpaid principle
years = float(input("Years: ")) #years = the number of years required to repay the loan in full
payment = ((1 + rate)**years * principle * rate)/((1 + rate)**years - 1)
#lines 7-10 print the annual, monthly, and total payments made respectively
print("Annual payment: ${:,.2f}".format(payment))
print("Monthly payment: ${:,.2f}".format(payment/12))
print("Total paid for the life of the loan: ${:,.2f}".format(payment*years))
principle = float(input("Principle: ")) #principle = the amount of dollars borrowed
rate = float(input("Rate: ")) #rate = the interest rate that is charged each year on unpaid principle
years = float(input("Years: ")) #years = the number of years required to repay the loan in full
payment = ((1 + rate)**years * principle * rate)/((1 + rate)**years - 1)
annualinc = float(input("Annual income: ")) #annualinc = the annual income
#to check if the user needs to refinance or not by comparing their monthly
income to their monthly payment
if (annualinc / 12) <= (payment / 12) and rate > .05:
print("You should refinance")
elif (annualinc / 12) <= (payment / 12):
print("You should seek financial counseling")
else:
print("If you make all your payments, your loan will be paid on time.")
The only way I could get the if statement to work is by having the user re-input every variable between the print statements and the if statement. Whenever I put the variable annualinc = float(input("Annual income: ") at the beginning of the program before the print statements or between the print statements and if statement it would break the line after it with a syntax error. Why did I have to ask for all the variables again and why could I not just ask for the variable annualinc by itself? And why does it not work when I put it with the first group of variables?
edit: I fixed it so I don't have to put in all the variables again! I was missing a parenthesis at the end of the line and I've been copy and pasting the line when I moved it around so the error traveled with it. Sorry for such a rookie mistake and thank you!

Would this suit you?
principle = float(input("Principle: ")) #principle = the amount of dollars borrowed
rate = float(input("Rate: ")) #rate = the interest rate that is charged each year on unpaid principle
years = float(input("Years: ")) #years = the number of years required to repay the loan in full
payment = ((1 + rate)**years * principle * rate)/((1 + rate)**years - 1)
#lines 7-10 print the annual, monthly, and total payments made respectively
print("Annual payment: ${:,.2f}".format(payment))
print("Monthly payment: ${:,.2f}".format(payment/12))
print("Total paid for the life of the loan: ${:,.2f}".format(payment*years))
annualinc = float(input("Annual income: ")) #annualinc = the annual income
#to check if the user needs to refinance or not by comparing their monthly income to their monthly payment
if (annualinc / 12) <= (payment / 12) and rate > .05:
print("You should refinance")
elif (annualinc / 12) <= (payment / 12):
print("You should seek financial counseling")
else:
print("If you make all your payments, your loan will be paid on time.")
I just eliminated the redundant parts and it works on my machine!

Related

I am trying to do a function calculation in python and every time I run the module I get an error message that says "name 'sales bonus is not defined

#End of Year Bonus Calculation WITH FUNCTION
#modify the computer program provided so that the calculation of the bonus is done by a function whose input data (its parameters)are the employee’s total sales for the year and the employee’s years of service. Your function must calculate and return the employee’s total bonus for the year using the same decision logic used in the provided program code. This function must be called from the main program which must first prompt the user to enter the total sales for the year and the number of years with the company, which need to be used as the arguments of the function call. Finally, the main program must report to the user the value for the total bonus returned by the function. When executed, this new version of the bonus calculation program must produce exactly the same results as those produced by the original code provided.
#function definition:
--- the signature(header)
def yearlyBonus(yearSales, yearsOfService):
#Calculate monthly average sales
monthlyAveSales = yearSales / 12
#Decide bonus based on monthly sales average
if monthlyAveSales < 1000:
salesBonus = 100
elif monthlyAveSales >= 1000 and monthlyAveSales < 2000:
salesBonus = 200
elif monthlyAveSales >= 2000 and monthlyAveSales < 3000:
salesBonus = 300
else:
salesBonus = 400
return(salesBonus)
#
#
#Main Program
#Prompt user to enter basic data
yearSales = float(input('Enter the total sales for the year: '))
yearsOfService = int(input('Enter the number of years with the company: '))
#Calculate the yearly bonus by adjusting the sales bonus
#per years of service:
#if years of service is 10 or more,
#increase the sales bonus by the appropriate percent
if yearsOfService >= 20:
yearlyBonus = salesBonus * 1.20
elif yearsOfService >= 10:
yearlyBonus = salesBonus * 1.10
else:
yearlyBonus = salesBonus
#Report yearly bonus
print('The bonus for the year is {0:.2f}.'.format(yearlyBonus(yearSales, yearsOfService)))
you need to set salesBonus = yearlyBonus(yearSales, yearsOfService) in the main before the if..else. or better try and recode because it is a bit confused

How do you round a string in Python?

I am new to Python and a student, my college has chosen the worst book on earth for our course. I cannot find examples of any concepts, so I apologize in advance as I know these concepts are very basic. I hope you can help me.
I need to know how to use the round feature in a string. I find examples but they do not show the string, just simple numbers.
Here is what we are supposed to get as an output:
Enter the gross income: 12345.67
Enter the number of dependents: 1
The income tax is $-130.87 <---- this is what we are supposed to figure out
Here is the coding we are given to alter:
TAX_RATE = 0.20
STANDARD_DEDUCTION = 10000.0
DEPENDENT_DEDUCTION = 3000.0
# Request the inputs
grossIncome = float(input("Enter the gross income: "))
numDependents = int(input("Enter the number of dependents: "))
# Compute the income tax
taxableIncome = grossIncome - STANDARD_DEDUCTION - \
DEPENDENT_DEDUCTION * numDependents
incomeTax = taxableIncome * TAX_RATE
# Display the income tax
print("The income tax is $" + str(incomeTax))
As I do not have an NUMBER to plug into the formula - I have to figure out how to use "incomeTax" - I have no idea how to do this. THe book doesnt explain it. Help?
You can use format strings:
print("The income tax is ${:.2f}".format(incomeTax))
If you are using Python 3.6+, you can also use f-strings:
print(f"The income tax is ${incomeTax:.2f}")
You can round just before making it a string:
print("The income tax is $" + str(round(incomeTax,2)))
Output:
Enter the gross income: 12345.67
Enter the number of dependents: 1
The income tax is $-130.87
Im a student as well, with the same dumb book and HW.
I tried the above
str(round(incomeTax,2))
and it didn’t work. Maybe I typed something wrong. After playing around I found this to work
# Display the income tax
incomeTax = round(incomeTax,2)
print(“The income tax is $” + str(incomeTax))
I hope this helps some other poor soul searching the web for an answer!

Working with commas in output

I'm in an intro programming class and am lost. We've had several labs that required knowledge that we haven't been taught but I've managed to find out what I need on google (as nobody responds to the class message board) but this one has me pretty frustrated. I'll include a pastebin link here: https://pastebin.com/6JBD6NNA
`principal = input()
print('Enter the Principal Value of your investment: $', float(principal))
time = input()
print('\nEnter the Time(in years) you plan to save your investment: ', int(time))
rate = input()
print('\nEnter the Rate (2% = 0.02) you will collect on your investment: ', float(rate))
interest = (float(principal) * float(rate)) * int(time)
final_value = float(principal) + float(interest)
print('\nThe Final Value of your investment will be: $%.2f' % final_value)`
So I need the output of the dollar amounts to have a comma ($27,500.00) but I have no idea how to do this. I've seen a couple of solutions on this site and others but I can't get them to work. PLEASE can someone help me?
In Python 2.7 or above, you can use
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
This is documented in PEP 378.
Source: Python Add Comma Into Number String
Here is a working example:
principal = float(input('Enter the Principal Value of your investment: $'))
time = int(input('\nEnter the Time(in years) you plan to save your investment: '))
rate = float(input('\nEnter the Rate (2% = 0.02) you will collect on your investment: '))
interest = principal * rate * time
final_value = principal + interest
print('The Final Value of your investment will be: ${:,.2f}'.format(final_value))
Your last line should be:
print ("\nThe Final Value of your investment will be: ${:,.2f}".format(final_value))

Loan calculator program

So far I have been coding this all week trying to get it to work.
It should come out as this:
Please enter Amount that you would like to borrow(£): 4000
Please enter Duration of the loan(Years):2
Please enter the interest rate (%):6
The total amount of interest for 2 (years) is: £480.00
The total amount of the period for 2 (years) is £4480.00
You will pay £186.67 per month for 24 months.
Do you wish to calculate a new loan payment(Y or N)
Code:
monthlypayment = 0 #Variable
loanamount = 0 #Variable
interestrate = 0 #Variable
numberofpayments = 0 #Variable
loandurationinyears = 0 #Variable
loanamount = input("Please enter the amount that you would like to borrow(£) ")
loandurationinyears = input("How many years will it take you to pay off the loan? ")
interestrate = input("What is the interest rate on the loan? ")
#Convert the strings into floating numbers
loandurationinyears = float(loandurationinyears)
loanamount = float(loanamount)
interestrate = float(interestrate)
#Since payments are once per month, number of payments is number of years for the loan
numberofpayments = loandurationinyears*12
#calculate the monthly payment based on the formula
monthlypayment = (loanamount * interestrate * (1+ interestrate)
* numberofpayments / ((1 + interestrate) * numberofpayments -1))
#Result to the program
print("Your monthly payment will be " + str(monthlypayment))
looks to me like the only thing you're missing in the code above from what you described is a while loop. This will allow your program to calculate the loan and run the program over and over again until the user inputs no, in which case the program exits. all what you have to do is:
YorNo = input("Do you wish to calculate a loan payment")
YorNo.Title()
while YorNo != "n":
#Your code goes here
YorNo = input("Do you wish to calculate a loan payment")
YorNo.Title()
print("Thank you for using the program")
In case you dont understand this, baisically, you type the first 3 lines just before your code. Then you leave an indentation and type your code after them. Once your done, you type in the 3rd and 4th line. Then, simply go back that indentation (to show the program that this isnt part of the loop.) If im not mistaken, the result of this will be:
You will be asked wether you want to calculate a loan
If you answer "y" your code will run and the loan will be calculated and printed to the user
Then you will be asked again. The above will repeat until you input "n"
the N cant be capitalised

Comparing Loans in Python

I am doing an assignment for my Python class. I almost figured it out but my output is just a little bit different with the one showed in the original problem. When interest rate is 5.125%, I have a Monthly Payment for 189.29, but the output from the problem is 188.28. The original number without format is 189.286. I guess maybe in the finance system, they just simply cut the decimals instead of using "round". I am not sure if there is any way to do that in Python. Here is the problem.
Write a program that lets the user enter the loan amount and loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8.
Input:
Loan Amount: 10000
Number of Years: 5
Output:
Interest Rate Monthly Payment Total Payment
5.000% 188.71 11322.74
5.125% 189.29 11357.13
...
7.875% 202.17 12129.97
8.000% 202.76 12165.84
Code:
LoanAmount = float(input("Loan Amount:"))
NumOfYears = float(input("Number of Years:"))
AnnualRate = float(5.0)
print("\nInterest Rate\t" + "Monthly Payment\t" + "Total Payment")
while (AnnualRate <= 8.0):
MonthlyRate = float(AnnualRate/1200)
MonthlyPayment = float(LoanAmount * MonthlyRate / (1- 1/ pow(1+MonthlyRate, NumOfYears *12)))
TotalPayment = format(MonthlyPayment * NumOfYears * 12, ".2f")
print (format(AnnualRate, ".3f"), end = "%\t\t")
print (format(MonthlyPayment, ".2f"), end = "\t\t")
print(TotalPayment, end = "\n")
AnnualRate += 1.0/8
When you work with money use the decimal module. This allows many different rounding modes. For example, round down:
import decimal
payment = decimal.Decimal('189.286')
with decimal.localcontext() as ctx:
ctx.rounding = decimal.ROUND_DOWN
print(round(payment, 2))
Prints:
189.28
Bankers' rounding would be:
decimal.ROUND_HALF_EVEN
Round to nearest with ties going to nearest even integer.
with decimal.localcontext() as ctx:
ctx.rounding = decimal.ROUND_HALF_EVEN
print(round(payment, 2))

Categories