net gain/loss in python - python

I'm doing a project where I need to figure if my transactions will earn me a profit or hit me for a loss. It's based on buying and selling stocks with commission. I got the basic math concept all worked out. What I am struggling with is the last equation where I subtract the sale price from the purchase price. I need a statement (or two) that if the answer is positive, it will go to output saying I gained x amount of money. If the answer is negative, it will go to output saying I lost x amount of money.
What statements could I use where the Python program will know to send positive number to gain output and negative number to loss output?
Here's the code I wrote with your suggestion for if statement
number_of_shares = input("Enter number of shares: ")
purchase_price = input("Enter purchase price: ")
sale_price = input("Enter sale price: ")
price = number_of_shares * purchase_price
first_commission = price * .03
final_price = price - first_commission
sale = number_of_shares * sale_price
second_commission = sale * .03
last_price = sale - second_commission
net = final_price - last_price
if (net > 0):
print("After the transaction, you gained", net, "dollars.")
if (net < 0):
print("After the transaction, you lost", net, "dollars.")
I didn't realize I was putting the loss as a gain and vice versa so I swapped it around and changed the wording to make it more clear. I'm still stuck here's my updated code
number_of_shares = input("Enter number of shares: ")
purchase_price = input("Enter purchase price: ")
sale_price = input("Enter sale price: ")
price = number_of_shares * purchase_price
first_commission = price * .03
buy_price = price - first_commission
sale = number_of_shares * sale_price
second_commission = sale * .03
sell_price = sale - second_commission
net = sell_price - buy_price
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net, "dollars.")
After doing the code on paper, I saw my mistake (with the commission) and made changes. Now my issue is when the net is for a loss, the output gives me an negative number. How do i make it not negative? since I already have the statement- you lost x dollars. Hmm multiplying by negative 1? Here's what I did
number_of_shares = int(input("Enter number of shares: "))
purchase_price = float(input("Enter purchase price: "))
sale_price = float(input("Enter sale price: "))
buy = float(number_of_shares * purchase_price)
first_commission = float(buy * .03)
sale = float(number_of_shares * sale_price)
second_commission = float(sale * .03)
net = float(sale - buy - first_commission - second_commission)
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net * -1, "dollars.")

Without seeing the code you have so far it's a bit hard to give you help, but I'll try anyways.
It sounds like you're looking for an if statement. The following will probably do what you want:
# Assuming total_money is the output of everything before
# positive number is gain, negative is loss
if total_money > 0:
print 'You gained ${}'.format(total_money)
else:
print 'You lost ${}'.format(total_money)
This is part of a concept called flow control. To learn more about it, you can look at https://docs.python.org/2/tutorial/controlflow.html

Try the following format:
net_change = sell_price - buy_price - commission
if (net_change >0):
print('Money! Money in the bank!\nYou have made $'+str(net_change))
else if (net_change <0):
print('Oh, sad deleterious day!\nYou have lost $'+str(net_change))
else:
print('You did not accomplish anything. You have broken even.')
This is a flow control path for three outcomes, Positive, Negative, and Neutral.
You'll find that flow control such as this is key to creating robust programs, it prevents the program from going to a place that it shouldn't.

Here is the code that worked
number_of_shares = int(input("Enter number of shares:"))
purchase_price = float(input("Enter purchase price:"))
sale_price = float(input("Enter sale price:"))
buy = float(number_of_shares * purchase_price)
first_commission = float(buy * .03)
sale = float(number_of_shares * sale_price)
second_commission = float(sale * .03)
net = float(sale - buy - first_commission - second_commission)
if net > 0:
print("After the transaction, you gained", net, "dollars.")
if net < 0:
print("After the transaction, you lost", net * -1, "dollars.")

Related

calculate mortgage in python?

so i have this program that calculate that calculates the total amount that Dave will have to pay over the life of the mortgage:
# mortgage.py
principal = 500000.0
rate = 0.05
payment = 2684.11
total_paid = 0.0
while principal > 0:
principal = principal * (1+rate/12) - payment
total_paid = total_paid + payment
print('Total paid', total_paid)
and later the exercise ask me Suppose Dave pays an extra $1000/month for the first 12 months of the mortgage?
Modify the program to incorporate this extra payment and have it print the total amount paid along with the number of months required.
what can i modify to make the changes to the program ? I am lost
principal=500000.0
rate= 0.0
payment = 2684.11
total_paid = 0.0
extra_payment = 1000.0
num_periods = 0
while principal > 0:
if num_periods < 12:
principal = principal * (1+rate/12) - (payment+extra_payment)
total_paid += payment + extra_payment
else:
principal = principal * (1+rate/12) - (payment)
total_paid += payment
num_periods += 1
print('Total paid: $', total_paid)
Total paid = 929965.6199999959,
but principal = -1973.205724763917
You have overpayed the final payment
remember to add 'principal' to 'total_paid' to get the actual amount:
927992.414275232
Also, the numbers are not rounded to 2 decimal places
you can round them by using:
def twoDecimalPlaces(answer):
return("%.2f" % answer)
twoDecimalPlaces(927992.414275232)
>>> 927992.41
Here you need to ask again to the user "Do Dave has paid anything extra in principal amount?" if Yes then create new variable for updated principal
update_principal = principal + dave_paid_extra
and then re run the code with same eqaution.

Compound Interest calculator has problems in Python

I have been experimenting with creating an investment calculator, and I want to print the annual totals as well as the annual compounded interest. It's doing the annual totals fine, but not the annual interest. My inputs are $10000.00 principle, at 5% interest over 5 years.
start_over = 'true'
while start_over == 'true':
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate"))
addition = int(input("Type annual Addition"))
time = int(input("Enter number of years to invest"))
real_rate = rate * 0.01
i = 1
print('total', principle * (1 + real_rate))
while i < time:
principle = (principle + addition) * (1 + real_rate)
i = i + 1
print('total', principle)
for i in range(time):
amount = i * (((1 + rate/100.0) ** time)) * principle
ci = amount - principle
i += 1
print("interest = ",ci)
redo_program = input('To restart type y or to quit type any key ')
if redo_program == 'y':
start_over = 'true'
else:
start_over = 'null'
Here are my outputs:
Type the amount you are investing: 10000
Type interest rate5
Type annual Addition0
Enter number of years to invest5
total 10500.0
total 10500.0
total 11025.0
total 11576.25
total 12155.0625
interest = -12155.0625
interest = 3358.21965978516
interest = 18871.50181957032
interest = 34384.78397935548
interest = 49898.06613914064
To restart type y or to quit type any key
Give this a go:
# Calculate year's values based on inputs and the current value of the account
def calc(current, addition, rate, year):
multiplier = 1 + rate/100 # The interest multiplier
new_total = (current + addition) * multiplier # Calculate the total
interest = round((new_total - current - addition), 2) # Interest to nearest penny/cent
return new_total, interest
def main():
# Inputs
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate: "))
addition = int(input("Type annual Addition: "))
invst_time = int(input("Enter number of years to invest: "))
# Sets current account value to principle
current = principle
# Prints values for each year of investment
for i in range(invst_time):
total, interest_gained = calc(current, addition, rate, i+1)
print("At the end of Year: ", i+1)
print("Total: ", total)
print("Interest: ", interest_gained)
print("------")
current = total # Updates value of account
# Restart Program check
while 1:
repeat_choice = input("Would you like to restart and check with different values? (Y/N)")
if repeat_choice == "Y":
main()
elif repeat_choice == "N":
print("Thanks for using the calculator")
break
else:
print("Enter Y or N!") # Error handler
continue
main()

Python raw input function for tax calculation

I am trying to make a simple calculator for working out the tax due on a salary. Please see the code below:
I keep getting this error and I don't know what is wrong, please help :) thanks!
Traceback (most recent call last):
File "python", line 13
elif salary > 11000 and salary < 43000:
^
SyntaxError: invalid syntax
CODE:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax
Steps to correct your code
step1 : the salary data type should be of int, to correct..use the following code
step 2: Indentation is compulsory in python, so indent your code very well
step 3: Add an else statement after the conditional statements
step 4: indent return statement
change your code to this one
salary = int(raw_input ("What is your salary?"))
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
salary >= 0
while true:
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
else :
tax = undefined
return tax
It felt like there was a better way of doing this, so I came up with an alternative route:
tax_bands = [11000, 43000, 150000]
tax_amts = [0.2, 0.4, 0.45]
salary = 43001
Placing the thresholds and amounts into a list means that you can change them more easily if you need to.
The function below creates a list of the tax calculations, tax_list, and then a separate list of the maximum tax liability in each band called max_tax (the upper band has no maximum).
It then compares the values in the lists, and overwrites the tax_list if the corresponding value is larger than the maximum.
Then it calculates the sum of all values in tax_list greater than zero and returns it.
def taxes(salary, tax_bands, tax_amts):
tax_list = [(pct * (salary - band)) for (band, pct) in zip(tax_bands, tax_amts)]
max_tax = []
for index, sal in enumerate(tax_bands[:-1]):
max_tax.append(tax_bands[index + 1] - sal)
max_tax = [segment * tax for segment, tax in zip(max_tax, tax_amts[:-1])]
for index, value in enumerate(tax_list):
try:
if value > max_tax[index]:
tax_list[index] = max_tax[index]
except:
pass
tax_to_pay = sum([x for x in tax_list if x > 0])
return tax_to_pay
print taxes(salary, tax_bands, tax_amts)
salary = input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nYour net annual salary is: {} GBP".format(salary - taxes(salary, tax_bands, tax_amts))
To be super safe, you could also have the first line in the function call int(salary) using a try except just to check that it's the right type and that someone hasn't entered 43,000.
That because there are indent error in line number 12, now you can just copy pust this :
note : salary > 11000 and salary < 43000 equivalent to 11000 < salary < 43000 in python:
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
def taxes(salary):
while true:
if salary < 11000:
tax = 0
elif 11000 < salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
return tax
As the comments have already stated, your indentation is incorrect. See below:
def taxes(salary):
salary >= 0
tax = 0
if salary < 11000:
tax = 0
elif salary > 11000 and salary < 43000:
tax = (0.2 * income) - 2200
elif salary > 43000 and salary < 150000:
tax = (0.4 * (salary - 43000)) + 6400
elif salary > 150000:
tax = ((salary - 150000) * 0.45) + 6400 + 42800
print("Value of tax is: " + str(tax))
return tax
salary = raw_input ("What is your salary?")
print "So your gross annual salary is %r GBP" % (salary)
print "\nNow we need to calculate what your net salary is."
print("\nHere is your net salary after taxes: %r" % (taxes(int(salary))))
With python, indentations are how you tell the interpreter which blocks of code fall where (unlike with Java for example with semicolons being the end of line delimiter). By not indenting properly on your elif statements, you are essentially telling the program there is an elif without an if hence your syntax problem.

Applying a discount and showing discounted rate in Python 2.7

I have a quick question for you all. I'm currently working on an sample Airline reservation system and I'm having difficulties displaying the total amount discounted if the user is a frequent flyer (10% discount rate). Below is my code:
user_people = int(raw_input("Welcome to Ramirez Airlines! How many people will be flying?"))
user_seating = str(raw_input("Perfect! Now what type of seating would your party prefer?"))
user_luggage = int(raw_input("Thanks. Now for your luggage, how many bags would you like to check in?"))
user_frequent = str(raw_input("Got it. Is anyone in your party a frequent flyer with us?"))
user_continue = str(raw_input("Your reservation was submitted successfully. Would you like to do another?"))
luggage_total = user_luggage * 50
import time
print time.strftime("Date and time confirmation: %Y-%m-%d %H:%M:%S")
seats_total = 0
if user_seating == 'economy':
seats_total = user_people * 916
print ('The total amount for your seats is: $'),seats_total
elif user_seating == 'business':
seats_total = user_people * 2650
print ('The total amount for your seats is: $'),seats_total
else:
print ('The total amount for your seats is: $'),user_people * 5180
print ('The total amount of your luggage is: $'),luggage_total
print ('Your subtotal for your seats and luggage is $'), luggage_total + seats_total
discount_amount = 0
discount_rate = 0.10
if user_frequent == 'yes':
before_discount = luggage_total + seats_total
after_discount = before_discount * discount_rate
discount_amount = before_discount - after_discount
print discount_amount
else:
print ('Sorry, the discount only applies to frequent flyers!')
While I'm not receiving an error, my output is incorrect. This is what is being displayed:
Discount amount of 1738.8
This obviously is incorrect as that is the price after the discount. I'm trying to display the total DISCOUNT as well as the price AFTER the discount has been applied.
Any help would be appreciated! Thanks!
You have more than one bug. First, in the else of the first if, you don't compute seat_total, so following computations will crash -- you just do
print ('The total amount for your seats is: $'),user_people * 5180
rather than the obviously needed
seat_total = user_people * 5180
print ('The total amount for your seats is: $'), seat_total
(the parentheses are useless but they don't hurt so I'm letting them be:-).
Second, look at your logic for discounts:
discount_rate = 0.10
if user_frequent == 'yes':
before_discount = luggage_total + seats_total
after_discount = before_discount * discount_rate
discount_amount = before_discount - after_discount
You're saying very explicitly that with a discount the user pays 1/10th of the list price -- then you complain about it in your Q!-)
It is, again, obvious (to humans reading between the lines -- never of course to computers:-), that in sharp contrast to what you say, what you actually mean is:
discount_rate = 0.10
if user_frequent == 'yes':
before_discount = luggage_total + seats_total
discount_amount = before_discount * discount_rate
after_discount = before_discount - discount_amount

Not getting right output...logic correct

My code is giving right results except for balance=3926. Lowest Payment: 370 whereas it should be 360.The program should print lowest monthly payment for given annual interest rate .Given an initial balance, code should compute the balance at the end of the year. we are trying our initial balance with a monthly payment of $10. If there is a balance remaining at the end of the year, we write code that would reset the balance to the initial balance, increase the payment by $10, and try again (using the same code!) to compute the balance at the end of the year, to see if this new payment value is large enough
annualInterestRate = 0.2
balance = 3926
monthlyinterestrate = annualInterestRate/12.0
remainingBalance = balance
month = 1
total = 0
payment = 10
def CheckMinimumPayment(payment,balance):
"Checking if payment is in correct balance"
while(payment*12 < balance):
payment += 10
return payment
payment = CheckMinimumPayment(payment,balance)
while(month <= 12):
remainingBalance = remainingBalance - payment + (annualInterestRate / 12.0) * (remainingBalance - payment)
month += 1
total += payment
payment = CheckMinimumPayment(payment,total+remainingBalance)
print("Lowest Payment: " + str(payment))
The problem is that you're not re-iterating through the interest loop (what you have as while(month <= 12)) each time you try a new payment. Write that loop into a function, and call it each time you try a new payment. The total owed balance depends on the payment, since a larger payment each month means less interest added each month. Here's what I used:
annualInterestRate = 0.2
init_balance = 3926
monthlyInterestRate = annualInterestRate/12.0
init_payment = 10
def owedBalance(payment,balance):
""" Calculate total owed balance after one year
given an initial balance and montly payment"""
for month in range(12):
balance = (balance - payment) * (monthlyInterestRate + 1)
return payment*12 + balance
def CheckMinimumPayment(payment,balance):
"Checking if payment is in correct balance"
while (payment*12 < owedBalance(payment, balance)):
payment += 10
return payment
min_payment = CheckMinimumPayment(init_payment,init_balance)
print("Lowest Payment: {}".format(min_payment))

Categories

Resources