Calling Function in Function without Arguments - python

Quick question:
I want to call a main function without any arguments, and within the main function, I have several other functions that do have arguments. How would I go about doing this?
Here are the multiple functions:
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the total price of the shares at time of purchase
def total_purchase_price(portfolio):
totalprice = 0
totalpurprice = 0
for item in portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += purprice * numshares
totalpurprice = totalprice
return totalpurprice
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the current total value of the shares
def total_value(portfolio):
totalprice = 0
totalvalueprice = 0
for item in portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += curprice * numshares
totalvalueprice = totalprice
return totalvalueprice
# Takes the previous two functions, and subtracts them to get the total
# gain/lost of the shares
def total_gain(total_purchase_price, total_value, portfolio):
gainlost = total_value - total_purchase_price
return gainlost
ex. What I have right now (note: I know this won't work, just there for what I want, as each function returns a value):
def testQ1(total_purchase_price, total_value, total_gain, portfolio):
print("Total Cost =", total_purchase_price)
print("Current Value =", total_value)
print("Total gain/lost =", total_gain)
return
ex. What I want to achieve:
def testQ2():
total_purchase_price(portfolio)
total_value(portfolio)
total_gain(total_purchase_price, total_value, portfolio)
print("Total Cost =", total_purchase_price)
print("Current Value =", total_value)
print("Total gain/lost =", total_gain)
return
How would I do this? Thanks

Using a class might be easier:
class PortfolioParser:
def __init__(self, portfolio):
self.portfolio = portfolio
self.price = self.total_purchase_price()
self.value = self.total_value()
self.gain = self.total_gain()
def total_purchase_price(self):
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the total price of the shares at time of purchase
totalprice = 0
totalpurprice = 0
for item in self.portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += purprice * numshares
totalpurprice = totalprice
return totalpurprice
def total_value(self):
# Takes the Portfolio dictionay, unpacks the multiple tuples, and calculates
# the current total value of the shares
totalprice = 0
totalvalueprice = 0
for item in self.portfolio:
purdate, purprice, numshares, sym, curprice = item
totalprice += curprice * numshares
totalvalueprice = totalprice
return totalvalueprice
def total_gain(self):
# Takes the previous two functions, and subtracts them to get the total
# gain/lost of the shares
return self.value- self.price
def testQ2(self):
print("Total Cost = {0}\nCurrent Value = {1}\nTotal Gains = {2}".format(self.price, self.value, self.gain))
And then you would use it like so:
myPortfolio = # The portfolio to parse
parser = PortfolioParser(myPortfolio)
parser.testQ2()

portfolio is the only argument that is not calculated within testQ2. You need to have a global value for it, or read it in (maybe in another function). After they have been calculated return the values in an appropriate order.
def testQ2():
portfolio = getPortfolio()
tp = total_purchase_price(portfolio)
tv = total_value(portfolio)
tg = total_gain(tp, tv, portfolio)
print("Total Cost =", tp)
print("Current Value =", tv)
print("Total gain/lost =", tg)
return portfolio, tp, tv, tg

Related

How to produce proper total for sales tax calculator

Writing a program that takes in a shopping list of dataclass items that fit one of three categories. The function is supposed to calculate the total based on the items, quantity, and state's sales tax. The only issue is, the way my function performs now, its outputting a result that isn't what's expected. It is giving me the proper total; However, the total isn't compensating for the tax I'm trying to calculate. Any help would be greatly appreciated.
class Category(enum.Enum):
wic = 0
clothing = 1
other = 2
#dataclass
class item:
name: str
price: float
quantity: int
category: Category
def total_calculator(shopping_cart, a_state):
tax_rate, subtotal, total, cloth_total, wic_total, other_total = 0, 0, 0, 0, 0, 0
if a_state == "Massachusetts":
tax_rate = 0.0675
elif a_state == "Maine":
tax_rate = 0.0550
else:
tax_rate = 0
for item_ in shopping_cart:
if item_.category == Category.wic:
wic_total += (item_.price * item_.quantity)
# Starts the calculation sequence for clothing based on state
elif item_.category == Category.clothing:
cloth_total += item_.price * item_.quantity + (item_.price * tax_rate)
if item_.category == Category.clothing and a_state == "Massachusetts":
if item_.price >= 175:
cloth_total += item_.price * item_.quantity + (item_.price * 0.0625)
else:
cloth_total += (item_.price * item_.quantity)
# Starts the calculation sequence for other based on state
print(cloth_total)
elif item_.category == Category.other:
other_total += item_.price * item_.quantity + (item_.price * tax_rate)
total = wic_total + cloth_total + other_total
return total

I want to create a simple inventory management system using classes and data structures. I am new to OOP in python

The code should Capture products in stock (i.e. name, price, date supplied, supplier name, quantity), Retrieve the price when name is given upon each purchase and deducts the quantity in
stock, Calculate the total price for each purchase and prints value indicating date and time of
purchase, Sends an alert when quantity reaches 5 to shopkeeper and places order to supplier.
My code right now is not looping so that I can add a number of products then be able to access them, I tried using a while loop but it is running forever. Kindly help
import datetime
class Stock:
def __init__(self, name, price, supplier, quantity,date):
self.name = name
self.price = price
self.date = date
self.supplier = supplier
self. quantity = quantity
def check_item(self, name):
for i in range(len(ls)):
if (ls[i].name == name):
return i
def sale(self):
n = int(input("How many products to sale: "))
total = 0
for j in range(n):
name = input("Enter Product name : ")
quantity = int(input("Enter quantity: "))
i = obj.check_item(name)
if i and ls[i].quantity >= quantity:
ls[i].quantity -= quantity
if ls[i].quantity < 5:
print("Low Stock! Low Stock! Order Placed")
obj.place_order(name, ls[i].supplier, quantity+10)
print("....Uncle G Shop....")
print(datetime.date.today())
print("Product Name | Quantity | Cost $")
print(ls[i].name, end=" ")
print(quantity, end=" ")
print(ls[i].price * quantity)
total += ls[i].price * quantity
print("\n")
print("Total Cost----->", "$" + total)
else:
print("Product out of stock or not enough quantity")
def purchase(self):
name = input("Enter Product name: ")
date = datetime.date.today()
i = obj.check_item(name)
if i:
ls[i].quantity += int(input("Enter quantity: "))
ls[i].price = int(input("Enter product price: "))
ls[i].date = date
else:
quantity = int(input("Enter quantity: "))
price = int(input("Enter product price: "))
supplier = input("Enter Supplier: ")
ob = Stock(name, price, supplier, quantity, date)
ls.append(ob)
def place_order(self,name, supplier, quantity):
return name, supplier, quantity
def print_products(self):
def __repr__(self):
return str(self.name) + str(self.price) + str(supplier) + str(self.quantity) + str(self.date)
return __repr__
def main(self):
print("Welcome To Uncle G Shop")
print("choose an option below")
print("\n1.Enter a Product\n2.Make a sale \n3.See all Products\n4.Exit")
option = int(input("Enter option here: "))
while True:
if option == 1:
obj.purchase()
elif option == 2:
obj.sale()
elif option == 3:
obj.print_products()
elif option == 4:
print("Have a good day")
break
else:
print("Enter a valid input!")
# A list to add Products
ls = []
# an object of Stock class
obj = Stock('', 0, 0, 0, '')
obj.main()
Your main menu doesn't have a break from the while loop for option 4.
You also need to think again about how to use your class. At present, you have multiple methods referring to a variable, ls, created outside of the class. Either treat Stock as a class to deal with individual purchase records, or to deal with stock overall. You could maintain in the class itself a list of instances of the class and offer class methods, as well as instance methods, to manage that overall stock.

updating a return value within a function

The issue i am having is getting the value of a returned item to update from different functions within a main function.
I have tried syntax to see if that changed anything, but I am not sure what needs to happen to get (in this case: the count and total).
I have also tried setting the functions = count, total but that returned an error.
def main():
terminate = False
print("Welcome to the self-checkout system at Wake-Mart.")
count, total = scan_prices()
print('')
disc = discount(count, total)
print('')
promo = promotion(count, total)
balance = total
def scan_prices():
total = 0
count = 0
prices = float(input("Enter the price of the first item:"))
while prices > 0:
count +=1
total = total + prices
print("Number of items:", count, "Total:", total)
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
while prices < 0:
print("Price cannot be negative.")
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
if prices > 0:
count +=1
total = total + prices
print("Number of items:", count, "Total:", total)
prices = float(input("Eneter the price of the next item [or 0 to stop]:"))
continue
return count, total
def discount(count, total):
if count >= 10:
print("You've got a 10% discount for buying 10 items or more.")
total = total * .9
print("Number of items:", count, "Total:", total)
return total
def promotion(count, total):
if total >= 50:
card = input(print("Do you want to buy a $50 gift card for $40 [y/n]:"))
if card == 'Y' or 'y':
print("Thank you for buying a giftcard.")
count +=1
total = (total * .9) + 40
print("Number if items:", count, "Total:", total)
else:
print("Thank for your purchases.")
print("Number if items:", count, "Total:", (total * .9))
return count, total
main()
I am just wanting the total and count to be updated as I move from one function execution to the next within the main function.
It looks like your main should take the return of one function and pass it to the next:
def main():
terminate = False
print("Welcome to the self-checkout system at Wake-Mart.")
count, total = scan_prices()
print('')
total = discount(count, total)
print('')
count, total = promotion(count, total)
balance = total

How to modify the value for a key in a dictionary?

So I'm trying to create a program that can take an order, retrieve it from stock and output the cost. When I do so I get a price of all the items chosen in stock. Any help?
import time
def compute_bill(component):
total = 0
for item in component:
total += prices[item_p]
return total
def localTime():
localtime = time.asctime(time.localtime(time.time()))
return localtime
stock = {
"I7": 2,
"Keyboard": 3,
"Mouse": 2,
"GPU": 4
}
prices = {
"I7": 250,
"Keyboard": 15,
"Mouse": 12,
"GPU": 350
}
item_p = ''
item_p = input("Please input the item you would like: ")
quantity = int(input("Please input the quantity you would like: "))
if item_p in stock:
print("X ordered a ", item_p,"at", localTime()," Which comes to a total of £", compute_bill(item_p))
else:
print("Error")
Example Output:
Please input the item you would like: Keyboard
X ordered a Keyboard at Fri Feb 9 17:16:09 2018 Which comes to a total of £ 120
I'd replace:
def compute_bill(component):
total = 0
for item in component:
total += prices[item_p]
return total
with:
def update_stock(component):
global stock
stock[component] -= quantity
def compute_bill(component):
update_stock(component)
return quantity * prices[component]
Your compute_bill function should be implemented simply like this:
def compute_bill():
return prices[item_p] * quantity

python modify dic deletion while iterating

method remove_item that requires similar arguments as add_item. It should remove items that have been added to the shopping cart and are not required. This method should deduct the cost of these items from the current total and also update the items dict accordingly. If the quantity of items to be removed exceeds current quantity in cart, assume that all entries of that item are to be removed.
class ShoppingCart(object):
#constructor
def __init__(self):
self.total = 0
self.items = {}
#method to add items in the shoping cart
def add_item(self,item_name, quantity, price):
self.total += (price * quantity )
self.items[item_name] = quantity
#method to remove items
def remove_item(self,item_name, quantity, price):
keys = self.items.keys()
for keys,v in self.items.items():
if keys == item_name and quantity > self.items[keys]: #if item_name equals iterated item
self.total -= (price * quantity )
del( self.items[keys] )
del(self.items[keys])
self.total -= (quantity * price)
And there are test units to check
def test_add_item_hidden(self):
self.cart.add_item('Mango', 3, 10)
self.cart.add_item('Orange', 16, 10)
self.assertEqual(self.cart.total, 190, msg='Cart total not correct after adding items')
self.assertEqual(self.cart.items['Orange'], 16, msg='Quantity of items not correct after adding item')
The method remove_item gives an error that dictionary changed size during iteration even after trying to access via keys as shown above
I think the remove_item function could be more simple.
#method to remove items
def remove_item(self,item_name, quantity, price):
if item_name in self.item.keys():
self.total -= (price * quantity)
del self.items[item_name]
With this version, you are checking if item_name is on the dictionary, and if so, you are removing it, and removing the price from total
Trying to remove from a dict,list,typle while iterating over them, is not usually a good idea.
If item_name is a list of keys, I have to suppose that quantity and price are too.
so a possible function could be:
def remove_item(self,item_name, quantity, price):
for index, value in enumerate(item_name):
if value in self.item.keys():
self.total -= (price[index] * quantity[index])
del self.items[value]
I haven't tested but should work.
if the idea is to get an inventory of the items. The function should be something like this.
#method to remove items
def remove_item(self,item_name, quantity, price):
if item_name in self.items.keys():
#remove from total the price for the items
if quantity <= self.items[item_name]:
self.total -= (price * quantity)
else:
self.total -= (price * self.items[item_name])
#if quantity is greater or equal of the current value, item is removed.
if quantity >= self.items[item_name]
del self.items[item_name]
else:
self.items[item_name] -= quantity

Categories

Resources