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))
Related
I wrote a program in python to find compound interest (more like copied). This program was written in python 2 and I am having a problem on the last line .format(years).
I need to know what I can do with this code, and how to write it properly in Python 3. Also with the {} part in the last line. Should I change it to %s? The error says:
"AttributeError: 'NoneType' object has no attribute 'format'".
My code looks like this :
# Estimated yearly interest
print ("How many years will you be saving ? ")
years = int(input("Enter the number of years : "))
print("How much money is currently in your account ? ")
principal = float(input("Enter current amount in account : "))
print("How much money do you plan on investing monthly ? ")
monthly_invest = float(input("Monthly invest : "))
print("What do you estimate the interest of this yearly investment would be ? ")
interest = (float(input("Enter the interest in decimal numbers (10% = 0.1) : ")))
print(' ')
monthly_invest = monthly_invest * 12
final_amount = 0
for i in range(0, years ):
if final_amount == 0:
final_amount = principal
final_amount = (final_amount + monthly_invest) * (1 + interest)
print("This is how much money you will have after {} years: ").format(years) + str(final_amount)
I find it a bit of a shame that no one recommended f-strings. There are only available since Python 3.6 but they are quite powerful, easy to use and the recommended string formatting option in PEP 498 (unless I'm mistaken).
If you want to get serious about python and work with other people I really recommend reading up on best practices, in this case, f-strings.
Solution using f-strings:
print(f"This is how much money you will have after {years} years: {final_amount}")
Change
print("This is how much money you will have after {} years: ").format(years) + str(final_amount)
to
print("This is how much money you will have after {} years: ".format(years)) + str(final_amount)
format() is a method of the string class. You're using it on the print() function which is of NoneType, hence the error.
You can do a normal string concatenation like this :
Print("This is how much money you will have after " + format(years) + " years: " +str(final_amount)
Or if you wish to keep the same format you can do this
print("This is how much money you will have after {} years: ".format(years) + str(final_amount))
A very basic solution would be to change the last line to:
print("This is how much money you will have after {} years:".format(years), str(round(final_amount,2)))
That will do the trick for you
You could also use Numpy's financial functions
For $1000 invested monthly for 10 years at annual rate of 4%:
>>> import numpy as np
>>> np.fv(.04/12, 10*12, -1000, 0)
147249.8047254786
With an initial principal of $100,000:
>>> np.fv(.04/12, 10*12, -1000, -100000)
296333.07296730485
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!
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
Ok so, I have an assignment to make a carsales program which is suppose to calculate how much the salesperson will make in a week. I already know how much all the cars sell for and how much commission he makes. Here is my code:
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
def calculate_total(car_number,price,commission_rate):
price = 32,500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
return calculate_total(car_number)
print('The weekly gross pay is $',calculate_total)
main()
The program isn't working for some reason but I decided to submit it to my professor anyway. He then replied by saying that I wasn't asked to create a new function and that I have to delete it and work just in main. Can someone please tell me what this means?
Two things:
'Working in main' as your professor said means that you don't define any functions. All your code just sits in the file, without any def ... statements. I know that's probably not clear. Here's an example:
import os
print "Your current working directory is:"
print os.getcwd()
This kind of programming has more the feel of a 'script' - you're not defining parts of the program that you're going to use more than once, and you're not taking the trouble to break down what the program does into single-purpose functions.
Second, you've entered price in such a way that Python thinks you're creating a tuple of numbers instead of a single value.
price = 32,500.00 is interpreted by Python as creating a tuple, with values 32 and 500.00 in it. What you actually want is: price = 32500.00.
I broke down and completed the process for you.
print ('This program will compute the comission earned for the week based on your sales for the week.')
car_number = float(input('Enter number of cars sold :'))
price = 32500.00
commission_rate = .025
calculate_total = car_number * price * commission_rate
print('The weekly gross pay is $',calculate_total)
Sorry i did not saw the complete question before but anyway this is the correct answer without a function
The keywords try and except are for error handling. If you give as input something invalid let's say a letter instead of number will throw a message
(Could not convert input data to a float.)
def main():
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
#before: car_number = float(raw_input('Enter number of cars sold :'))
car_number = float(input('Enter number of cars sold :'))
except ValueError:
#before: print 'Could not convert input data to a float.'
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
main()
If you don't even want main() function here is the answer:
print ('This program will compute the comission earned for the week based on your sales for the week.')
try:
car_number = float(input('Enter number of cars sold :'))
except ValueError:
print('Could not convert input data to a float.')
print('The weekly gross pay is ${}'.format(car_number * 32500.00 * 0.025 )))
I'm using python for the very first time and I am stuck on this stinking problem and cant for the life of me figure out why its not working. When I try and run my program I can get an answer for the yearly cost without the modification (even though its wrong and I dont know why) but not the yearly cost with the modification.
I've tried rewriting it in case I missed a colon/parenthesis/ect but that didnt work, I tried renaming it. And I tried taking it completely out (this is the only way I could get rid of that annoying error message)
payoff file
from mpg import *
def main():
driven,costg,costm,mpgbm,mpgam = getInfo(1,2,3,4,5)
print("The number of miles driven in a year is",driven)
print("The cost of gas is",costg)
print("The cost of the modification is",costm)
print("The MPG of the car before the modification is",mpgbm)
print("The MPG of the car afrer the modification is",mpgam)
costWithout = getYearlyCost(1,2)
print("Yearly cost without the modification:", costWithout)
costWith = getYearlyCost2()
print("Yearly cost with the modification:", costWith)
While I know there is an error (most likely a lot of errors) in this I cant see it. Could someone please point it out to me and help me fix it?
Also I added my mpg.py in case the error is in there and not the payoff file.
def getInfo(driven,costg,costm,mpgbm,mpgam):
driven = eval(input("enter number of miles driven per year: "))
costg = eval(input("enter cost of a gallon of gas: "))
costm = eval(input("enter the cost of modification: "))
mpgbm = eval(input("eneter MPG of the car before the modification: "))
mpgam = eval(input("enter MPG of the car after the modification: "))
return driven,costg,costm,mpgbm,mpgam
def getYearlyCost(driven,costg):
getYearlyCost = (driven / costg*12)
def getYealyCost2(driven,costm):
getYearlyCost2 = (driven / costm*12)
return getYearlyCost,getYearlyCost2
def gallons(x,y,z,x2,y2,z2):
x = (driven/mpgbm) # x= how many gallons are used in a year
y = costg
z = (x*y) # z = how much money is spent on gas in year
print("money spent on gas in year ",z)
x2 = (driven/mpgam) # x2 = how much money is spent with mod.
z2 = (x2*y)
y2 = (costm + z2)
1,1 Top
Here's your immediate problem:
costWith = getYearlyCost2()
The function you're trying to call is named getYealyCost2() (no "r").
There are other problems that you'll find as soon as you fix that, such as no return statement in getYearlyCost() and trying to return the function getYearlyCost() in getYearlyCost2() and calling getYearlyCost2() without any arguments.
On top of that, import * is frowned upon, and then there's the use of eval()... but that'll do for starters.