Gamification Gamification - 1 month ago 7
Python Question

Running total won't print properly

def load():
global name
global count
global shares
global pp
global sp
global commission
name=input("Enter stock name OR -999 to Quit: ")
count =0
while name != '-999':
count=count+1
shares=int(input("Enter number of shares: "))
pp=float(input("Enter purchase price: "))
sp=float(input("Enter selling price: "))
commission=float(input("Enter commission: "))
calc()
display()
name=input("\nEnter stock name OR -999 to Quit: ")

def calc():
totalpr=0
global amount_paid
global amount_sold
global profit_loss
global commission_paid_sale
global commission_paid_purchase
global totalpr
amount_paid=shares*pp
commission_paid_purchase=amount_paid*commission
amount_sold=shares*sp
commission_paid_sale=amount_sold*commission
profit_loss=(amount_sold - commission_paid_sale) -(amount_paid + commission_paid_purchase)
totalpr=totalpr+profit_loss

def display():
print("\nStock Name:", name)
print("Amount paid for the stock: $", format(amount_paid, '10,.2f'))
print("Commission paid on the purchase: $", format(commission_paid_purchase, '10,.2f'))
print("Amount the stock sold for: $", format(amount_sold, '10,.2f'))
print("Commission paid on the sale: $", format(commission_paid_sale, '10,.2f'))
print("Profit (or loss if negative): $", format(profit_loss, '10,.2f'))

def main():
load()


main()

print("\nTotal Profit is $", format(totalpr, '10,.2f'))


The last line of code is indicative of the problem. The display for "totalpr" is not a running tally of, say, 3 entered stocks. It's merely the profit_loss restated. How do I get it to accurately display the running total for however many times someone decides to enter stock data? The way it works: someone enters the sentinel '-999' then the program adds up all the profit_loss from every instance and prints it out. That's it.

Answer

You are resetting totalpr every time calc is called.

def calc():
    totalpr=0  # resets to zero every time
    # ...
    totalpr=totalpr+profit_loss  # same as `totalpr = 0 + profit_loss`

Instead, you have to initialize totalpr outside of calc:

totalpr = 0  # set to zero only once
def calc():
    # ...
    totalpr = totalpr + profit_loss  # same as `totalpr += profit_loss`
Comments