Python "format" syntax error - python

#Get the user's name.
Name = input('Enter your name.')
#Get number of stocks purchased.
Stocks_P = int(input('Enter the number of stocks purchased.'))
#Get purchase price of stocks.
Price_P = float(input('Enter the price of stocks purchased.'))
#Calculate total price.
Total_price = Stocks_P * Price_P
#Calculate Commission.
Com1 = Total_price * 0.03
#Calculate Cost.
Cost = Com1 + Total_price
#Get number of stocks sold.
Stocks_S = int(input('Enter the number of stocks sold.'))
#Get sale price of stocks.
Price_S = float(input('Enter the sale price of stocks.'))
#Calculate sale.
Sale = Stocks_S * Price_S
#Calculate sale Commission.
Com2 = Sale * 0.03
#Calculate profit or loss.
Profit = Sale - (Cost + Com2)
print('Your end total is: $' format(Profit, ',.2f') Name, sep='')
that's what i'm using for my first assignment in my python class, and in the last line, anything after the "print('You end total is: $' returns a syntax error no matter how i change it.

Indeed, just listing a string, a format() call and a variable name in a row is not valid Python syntax.
Either pass those three things in as separate arguments, using commas, or create a str.format() template for the values to be interpolated into:
print('Your end total is: $', format(Profit, ',.2f'), Name, sep='')
or
print('Your end total is: ${:,.2f}{}'.format(Profit, Name))

Related

Why is my program outputting 178 instead of 183?"

Write a program to calculate how many months it will take you to save up enough money for a down
payment. You will want your main variables to be floats, so you should cast user inputs to floats.
Your program should ask the user to enter the following variables:
The starting annual salary (annual_salary)
The portion of salary to be saved (portion_saved)
The cost of your dream home (total_cost)
Call the cost of your dream home total_cost.
Call the portion of the cost needed for a down payment portion_down_payment. For
simplicity, assume that portion_down_payment = 0.25 (25%).
Call the amount that you have saved thus far current_savings. You start with a current
savings of $0.
Assume that you invest your current savings wisely, with an annual return of r (in other words,
at the end of each month, you receive an additional current_savings*r/12 funds to put into
your savings – the 12 is because r is an annual rate). Assume that your investments earn a
return of r = 0.04 (4%).
Assume your annual salary is annual_salary.
Assume you are going to dedicate a certain amount of your salary each month to saving for
the down payment. Call that portion_saved. This variable should be in decimal form (i.e. 0.1
for 10%).
At the end of each month, your savings will be increased by the return on your investment,
plus a percentage of your monthly salary (annual salary / 12).
Expected case
Enter your annual salary: 120000
Enter the percent of your salary to save, as a decimal: .10
Enter the cost of your dream home: 1000000
Number of months: 183
My code text output
Number of months = 178
r = 0.04
current_savings = 0
potion_down_payment = 0.25
annual_salary = input('Enter your annual salary: ')
print(int(annual_salary))
monthly_salary = (int(annual_salary) / 12)
potion_saved = input('Enter the percent of your salary to save, as a decimal: ')
print(float(potion_saved))
cost_dream_home = input('Enter the cost of your dream home : ')
print(int(cost_dream_home))
invest_return = ((float(r) * float(annual_salary)) / 12)
amount_to_save = (float(potion_down_payment) * int(cost_dream_home))
potion_saved_f = (float(monthly_salary) * float(potion_saved))
total_saved = (float(invest_return) + potion_saved_f)
number_of_months = (float(amount_to_save) // float(total_saved))
print(int(number_of_months))
I did this quickly, but you need a while loop, like:
months = 0
target = 250000
monthly_save = 1000.0
saved = 0.0
rate = .04
subtotal = 0.0
while subtotal < target:
saved += monthly_save
subtotal = (subtotal + monthly_save) * (1+(rate/12))
months += 1
print(months), print(int(subtotal))
OK, I have more time now. I think that you are just lucky that your code came out so close to the expected answer because your computations are off base. Unless you know of a better formula, you really need a loop in order to compute compound interest month by month. I have analyzed your method below.
invest_return = ((float(r) * float(annual_salary)) / 12) #.04*120000/12=400
amount_to_save = (float(potion_down_payment) * int(cost_dream_home))#.25*1000000=250000
potion_saved_f = (float(monthly_salary) * float(potion_saved))#10000*.1=1000
total_saved = (float(invest_return) + potion_saved_f) #400+1000
number_of_months = (float(amount_to_save) // float(total_saved)) #250000//1400 = 178
print(int(number_of_months))

Working on a Python project for a salesman. Getting "cannot assign to operator" error

I'm working on a project in Python for a salesman. The project takes the pay from hours worked for the week and the percentage from commission of sales per week and adds them together to give the total weekly pay of the salesman. The problem I'm running into is dividing the sales amount with the percent they receive from each sale. The error is "cannot assign to operator"
#Prompt user for the number of hours worked that week
hours_worked = int(input("How many hours did you work this week? \n"))
#Define hourly wage
per_hour = 30
#Multiply the hourly wage and hours worked that week
total_hours_pay = hours_worked * per_hour
#Prompt user for the number of sales made that week
sales_made = int(input("How many sales did you make this week? \n"))
#Amount of each sale
sales = 250
#Determine commission of each sale
25 / sales = commission
#Multiply the commission times the amount of sales made to retrieve amount of total commission pay
total_sales_pay = sales_made * commission
#Add total commission pay from sales with the total hours pay to get the weekly total
total_week_pay = total_sales_pay + total_hours_pay
print(total_week_pay)
You wrote:
25 / sales = commission
But when assigning something to a variable, you need to put the variable at the start of the statement.
Try
commission = 25 / sales
25 / sales = commission this line throws the error. I think it should be comission = 25 / sales. You try to assign the value of comission to the result of 25 / sales which does not work.

Building a calculator with set of input values and fixed interest rate

Assuming, I am running a weekly business and making profits every week at a constant interest rate of 5% per week and assuming my investment is recursive every week, I want to print all values for first 21 weeks. How do i right a code in python to achieve this?
Note: Investment is recursive, (i.e) every week my investment will be previous investment plus profit made in that week and also I am my rounding off the values and I have written this code but For loop I am struggling to write the logic , could some one help please. I have written the logic /calculations in excel - please check for expected results the excel screenshot.
maximum_number_of_weeks = int(input("maximum_number_of_weeks:"))
Initial_investment_Amount = int(input("Enter Initial Investment Amount Value ($) : "))
Interest_rate = float(input("Enter Interest Rate Value (%) : "))
Amount_Earned = Initial_investment_Amount * Interest_rate
Total_Amount_at_Disposal = Initial_investment_Amount + Amount_Earned
print("Total_Amount_at_Disposal ($) : ",Total_Amount_at_Disposal)
I suggest using a more simple approach:
Amount at disposal = Initial investment * (1 + interest rate) ^ (number of weeks)
maximum_number_of_weeks = int(input("maximum_number_of_weeks:"))
Initial_investment_Amount = int(input("Enter Initial Investment Amount Value ($) : "))
Interest_rate = float(input("Enter Interest Rate Value (%) : "))
for week in range(1, maximum_number_of_weeks + 1):
Total_Amount_at_Disposal = Initial_investment_Amount * (1 + Interest_rate/100) ** week
print("Total_Amount_at_Disposal ($) : ",round(Total_Amount_at_Disposal, 2))

Python loan table trouble

I'm currently trying to figure out how to iterate over over columns and rows at the same time [if possible]. Or wondering what the best way to approach this is. The biggest problem that I'm having is creating for loops with floats in simple ways. Our professor specifically asks for us to do that and then when we have to fill out the rest of the information basically accessing those loops. He doesn't want us to be importing different libraries and says there are simple ways for us to do this but doesn't really gives us guidance :/ Our table is supposed to be formatted to look like this:
this is what i have in total already..
Supporting Code:
def main():
print("This program is used to analyze commercial real estate loans.")
#function variables
purchase_price = input("Please input original purchase price: ")
down_payment = input("Please input total down payment: ")
APR = float(input("Please input APR: "))
periods_year = input("Please input the number of payments per year: ")
term = float(input("Please input loan length in years: "))
first_payment = input("Please input date of first payment in form MM/DD/YYYY: ")
#seperating str
dates = first_payment.split('/')
day = int(dates[0])
month = int(dates[1])
year = int(dates[2])
#part 1 calculations with main variables
total_payments = float(term) * float(down_payment)
loan_amount = float(purchase_price) - float(down_payment)
total_amount = loanCalc(APR, periods_year, loan_amount, total_payments)
end_date = str(day) + "/" + str(month) + "/" + str(year + int(term))
total_interest = r*total_payments
#print("End day of loan : %s" %end_date) [do not need to print this right now]
#loancalc function
def loanCalc(APR, period_year, loan_amount, total_payments):
#interest charged per period
r = (APR)/(period_year)
#amount paid in each period
P = (r * loan_amount)/(1- (1+r) ** (-(total_payments)))
#amount paid over life of loan
final_value = (P * total_payments)
#remember to return not print
return final_value
Code that needs a loop
#loan payment table part 3/table will display
def pmtOptions(APR,period_year, term,loan_amount):
#headers, each column will be 10
print("{0:^80}".format("Alternative Loan Payment Table"))
print("{0:^80}".format("=============================="))
print("{0:^80}".format("Interest Rates"))
#interest rate loop
##for APR in range(3,6):
## if APR == 3:
## print("3.25",)
## APR = 3.25
## while APR <= 5.75:
## APR +=.5
## print("{0:>3}".format(""),"{0:<3}".format(APR), end="")
#printing interest rate loop
print("{0:>10}".format(""),"{0:>10}".format("3.25%"),"{0:>10}".format("3.75%"),
"{0:>10}".format("4.25%"),"{0:>10}".format("4.75%"),"{0:>10}".format("5.25%"),
"{0:>10}".format("5.75%"),"{0:>10}".format("6.25%"))
#never ending column headings
print("{0:>10}".format("# Payments"),"{0:>10}".format("="*len("3.25%")),"{0:>10}".format("="*len("3.75%")),
"{0:>10}".format("="*len("4.25%")),"{0:>10}".format("="*len("4.75%")),"{0:>10}".format("="*len("5.25%")),
"{0:>10}".format("="*len("5.75%")),"{0:>10}".format("="*len("6.25%")))
#attempting calculations
#payments column
for term in range(12,37,6):
print("{0:^10}".format(term))
#column 1
for term in range(12,37,6):

How do I call my Python function?

Here is my assignment:
Write a program to calculate the credit card balance after one year if
a person only pays the minimum monthly payment required by the credit
card company each month.
The following variables contain values as described below:
balance - the outstanding balance on the credit card
annualInterestRate - annual interest rate as a decimal
monthlyPaymentRate - minimum monthly payment rate as a decimal
For each month, calculate statements on the monthly payment and
remaining balance, and print to screen something of the format:
Month: 1
Minimum monthly payment: 96.0
Remaining balance: 4784.0
Finally, print out the total amount paid that year and the remaining
balance at the end of the year in the format:
It should not specify the values for the variables balance,
annualInterestRate, or monthlyPaymentRate - our test code will define
those values before testing your submission.
And here is the code I wrote:
def minpayment(balance, annualInterestRate, monthlyPaymentRate):
totalPaid = 0
month = 1
while month <= 12:
minPayment = monthlyPaymentRate * balance
balance -= minPayment
balance += (annualInterestRate/12.0)*balance
print 'Month:',month
print 'Minimum monthly payment:',round(minPayment,2)
print 'Remaining balance:',round(balance,2)
totalPaid += minPayment
month += 1
print 'Total paid:', round(totalPaid,2)
print 'Remaining balance:', round(balance,2)
Now, my question is, now that I've created the function, how do I call it?
You can call it like:
minpayment(10000, 0.1, 0.3)
or in general:
# You can modify the values below
balance = 10000
annualInterestRate = 0.1
monthlyPaymentRate = 0.3
minpayment(balance, annualInterestRate, monthlyPaymentRate)

Categories