How do I implement a finance function into this program? - python

I'm having trouble implementing a function into this program. The program I have currently works fine on its own without the function but I still need to find a way to put def finance(income, salesPrice): into it. I also need to invoke the function with this: print(finance(income, salesPrice)). I tried different ways but whenever I try to invoke the function, it says that income is not defined.
This is what I have to make:
The function will test whether a person is qualified to finance an expensive car. They are qualified if their annual income is greater than $100,000 and the sales price is less than $1,000,000. The function returns a message to the program stating whether the person is qualified or not. The program invokes the finance() function with this print statement: print (finance (income, salesPrice)) and the user input the income and sales price.
def finance(income,salesPrice):
income = float(input("Please enter annual income: "))
while (income <= 0):
income = float(input("Invalid input! Please enter positive value: "))
income += 1
salesPrice = float(input("Please enter sales price of car: "))
if (income>100000 and salesPrice<1000000):
print("You are qualified to purchase this car.")
else:
print("You are not qualified to purchase this car.")
result = print(finance(income,salesPrice))

The problem is indentation + You need to return a variable. EDIT: I edited the code based on your problem
def finance(income, sales_price):
if income > 100000 and sales_price < 1000000:
return "You are qualified to purchase this car."
else:
return "You are not qualified to purchase this car."
salesPrice = float(input("Please enter sales price of car: "))
income = float(input("Please enter annual income: "))
while income <= 0:
income = float(input("Invalid input! Please enter positive value: "))
income += 1
print (finance (income, salesPrice))

You make an indentation error, your line while (income <= 0) is outside of your function, you have to indent it.
More informations about indentation in python here.

Related

Im having and issue with printing the result of my code, no matter what I have tried im not back to get it to print my overspending or underspending

Assignment description, code below.
Im having and issue with printing the result of my code, no matter what I have tried im not back to get it to print my overspending or underspending
budget = float(input('Enter the allocated budget for this month: '))
expenses = 0
check = 0
while check >= 0:
check = float(input('Enter a cost (<0 stops the loop): '))
if check != -1:
expenses += check
balance = budget - expenses
if balance < 0:
print ("Your expenses are within budget by $")
else:
print ("Your expenses are over budget by $")
As Myousefi said, you are not passing the variable balance to the print command (I'm considering you refer Overspending or underspending to that variable)
You can print string texts using "" or variables of different kind (int, float, strings itselfs), or both. However, you have to separate them with commas (,). Take a look on this:
a="world"
print("Hello",a,"!")
You will get this
>>>Hello world !
Just a reminder that each comma adds a blank space.
So, for your problem, you just have to add the variable balance on the print instruction, like this
#Your instruction
print ("Your expenses are within budget by $")
#The solution
print ("Your expenses are within budget by $",balance)
However, you will get something like this
>>Your expenses are within budget by $ -15.0
I guess you want the number before the dollar sign, so you will have to put that at the end, as i did with the ! sign on the example
#Previous sentence
print ("Your expenses are within budget by $", balance)
#With $ sign at the end
print ("Your expenses are within budget by", balance,"$")

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!

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

Python car sales code issue

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 )))

Break Outside Loop with Previous Example

UPDATED:
This Code Works:
# North Carolina Sales Tax Estimator
# Estimates the Amount of Tax You Should Pay in North Carolina
# Defines the Current 2012 Tax Rate
nctaxrate = 0.07
# Defines the tax variable by multipling subtotal by the current nc tax rate
# tax = subtotal * nctaxrate
# Defines the total variable by adding the tax variable to the subtotal variable
# total = subtotal + tax
# Defines the Subtotal from an Input of the User's Purchase Amount
def main():
print("\t\t\tThis is the NC Sales Tax Estimator")
print("\t\t Input Your Total Purchases Below\n")
while True:
subtotal = float(input("Enter the total price of your purchases:\t$").strip())
if subtotal == -1: break
tax = subtotal * nctaxrate
total = subtotal + tax
print("\tSUBTOTAL: $", subtotal)
print("\t TAX: $", tax)
print("\t TOTAL: $", total)
# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
main()
Here is the Original Question:
So I am learning Python and asked a previous question yesterday and was supplied with an awesome set of code that I decided to modify to work with an NC Sales Tax Estimator Program I wanted to create.
The one thing is that I am getting a break out loop error that I don't quite understand. I've searched and tried to understand the meaning but I know the code worked before. Also the tax code program I created from scratch :) worked before trying to add the fancy ability to submit many inputs in a loop until the user wanted to 'exit'.
Here is the Code:
# North Carolina Sales Tax Estimator
# Estimates the Amount of Tax You Should Pay in North Carolina
# Defines the Current 2012 Tax Rate
nctaxrate = 0.07
# Defines the tax variable by multipling subtotal by the current nc tax rate
tax = subtotal * nctaxrate
# Defines the total variable by adding the tax variable to the subtotal variable
total = subtotal + tax
# Defines the Subtotal from an Input of the User's Purchase Amount
def main():
print("\t\t\tThis is the NC Sales Tax Estimator")
print("\t\t Input Your Total Purchases Below")
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
try:
subtotal = int(subtotal)
except ValueError:
print("That wasn't a number!")
try:
print("\tSUBTOTAL: $", subtotal)
print("\t TAX: $", tax)
print("\t TOTAL: $", total)
except KeyError:
print("")
# if this script is called directly by Python, run the main() function
# (if it is loaded as a module by another Python script, don't)
if __name__=="__main__":
main()
P.S. I only added the KeyError because I researched that you must have an error statement after a try. I'm just a beginner so I'm attempting to create programs myself and reading "Python for the Absolute Beginner".
UPDATE:
I fixed the indentation but now I get the following traceback error:
Traceback (most recent call last):
File "C:/LearningPython/taxestimator.py", line 30, in <module>
tax = subtotal * nctaxrate
NameError: name 'subtotal' is not defined
I thought I defined it in the input ie.
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
Is it because the other defines (tax and total) that use the defined subtotal are defined before subtotal is defined? I tried moving them below the defined subtotal but it didn't work still.
Thanks for any Advice.
Best,
Steven
The main issue that you have is that Python requires whitespace to scope methods. Without that, then statements will run not as intended - for example:
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
will not break out of the loop with valid input (it will if you put a string there, but that's another matter). Also, if everything is to be in the scope of main(), every statement requires one level of indentation (or four lines of whitespace, if you prefer). As it stands, your while won't run in the scope of main().
Also, you make reference to subtotal before you actually give it a value. Since subtotalwasn't properly initialized, you won't have a value to use for it.
You would want to rewrite your code such that tax and total are defined after you define subtotal.
while True:
subtotal = float(input("Enter the total price of your purchases (or 'exit' to quit) :\$").strip())
if subtotal.lower()=='exit':
break
tax = subtotal * nctaxrate
total = subtotal + tax
Finally, if subtotal, total, and tax are properly defined (which, after the above, they will be), there will be no need for the superflous try...except statement when you wish to print the values out.
if subtotal.lower()=='exit':
break
needs to be indented probably ... unless that was just a typo when entering the question

Categories