updating a return value within a function - python

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

Related

I'm trying to get specific results from my Lucky Sevens program, but I'm not sure where to go from here

I'm trying to calculate the number of rolls it takes to go broke, and the amount of rolls that would have left you with the most money. The program is split into several functions outside of main (not my choice) so that makes it more difficult for me.
I'm very new to python, and this is an exercise for school. I'm just not really sure where to go from here, and I realize I'm probably doing some of this wrong. Here's the code I have so far:
import random
def displayHeader(funds):
print ("--------------------------")
print ("--------------------------")
print ("- Lucky Sevens -")
print ("--------------------------")
print ("--------------------------")
funds = int(input("How many dollars do you have? "))
def rollDie(newFunds):
#this function is supposed to simulate the roll of two die and return results
while funds > 0:
diceRoll = random.randint(1,6)
totalRoll = (diceRoll + diceRoll)
if totalRoll == 7:
funds = funds + 4
else:
funds = funds - 1
if funds == 0:
newFunds = funds
def displayResults():
#this function is supposed to display the final results.
#the number of rolls, the number of rolls you should have stopped at, and the max amount of money you would have had.
def main():
#everything gathered from the last function would be printed here.
main()
import random
maxmoney = []
minmoney = []
def displayHeader():
print ("--------------------------")
print ("--------------------------")
print ("- Lucky Sevens -")
print ("--------------------------")
print ("--------------------------")
funds = int(input("How many dollars do you have? "))
return funds
def rollDie():
#this function is supposed to simulate the roll of two die and return results
funds = displayHeader()
while funds > 0:
diceRoll1 = random.randint(1,6)
diceRoll2 = random.randint(1,6)
totalRoll = (diceRoll1 + diceRoll2)
if totalRoll == 7:
funds = funds + 4
maxmoney.append(funds)
else:
funds = funds - 1
minmoney.append(funds)
def displayResults():
#this function is supposed to display the final results.
#the number of rolls, the number of rolls you should have stopped at, and the max amount of money you would have had.
rollDie()
numOfRolls = len(maxmoney) + len(minmoney)
numOfRolls2Stop = (len(maxmoney) - 1 - maxmoney[::-1].index(max(maxmoney))) + (len(minmoney) - 1 - minmoney[::-1].index(max(maxmoney)-1)) + 1 if maxmoney and minmoney else 0
maxAmount = max(maxmoney) if maxmoney else 0
return numOfRolls, numOfRolls2Stop, maxAmount
def main():
#everything gathered from the last function would be printed here.
a, b, c = displayResults()
print('The number of total rolls is : ' + str(a))
print("The number of rolls you should've stopped at is: " + str(b))
print("The maximun amount of money you would've had is: $" + str(c))
main()
Your program use variables that can only be accessed in certain scopes, so I think that the most recommended thing is that you use a class.
displayHeader input method it could stop the execution of the program since if you do not introduce a numerical value it will raises an exception called ValueError, if this does not help you much, I advise you to read the code carefully and add missing variables such as the input amount and the final amount and others...
class rollDiceGame():
def __init__(self):
self.funds = 0
self.diceRollCount = 0
def displayHeader(self):
print ("--------------------------")
print ("--------------------------")
print ("- Lucky Sevens -")
print ("--------------------------")
print ("--------------------------")
self.funds = int(input("How many dollars do you have? "))
def rollDice(self):
while self.funds > 0:
diceRoll = random.randint(1,6)
totalRoll = (diceRoll + diceRoll)
self.diceRollCount += 1
if totalRoll == 7:
self.funds += 4
else:
self.funds -= 1
def displayResult(self):
print('Roll count %d' % (self.diceRollCount))
print('Current funds %d' % (self.funds))
def main():
test = RollDiceGame()
test.displayHeader()
test.rollDice()
test.displayResult()
main()

Discount on a price

So this is my code so far but at the end there i am trying to add a discount option. I am not sure how to add it to multiple products. Please let me know how i can improve because i am sort of new to coding.
def best_cost():
while True:
num_of_products = int(input('How many products are there? '))
if num_of_products < 1:
print(f'Enter valid number for number of products')
else:
print(f'Finding best value out of {num_of_products} products')
all_prices = []
for i in range(1, num_of_products+1):
cost = float(input(f'Enter cost of product {i} $'))
mass = float(input(f'Enter mass of product {i} in grams:'))
print(f'Product {i} at ${cost / mass} per gram')
price = cost/mass
all_prices.append(price)
for prod in all_prices:
if prod == min(all_prices):
best_prod = all_prices.index(prod)+1
return print(f'Best product is Product {best_prod}')
best_cost()
discount_question=input('Is there a discount on any of the products? ')
if 'yes' in discount_question:
print("Enter in 0 if there isn't a discount on thet item.")
discount_a= float(input(f'Discount for product {a} (%): '))
You need to save the original prices first:
def best_cost():
num_of_products = int(input('How many products are there? '))
if num_of_products < 1:
print(f'Enter valid number for number of products')
else:
print(f'Finding best value out of {num_of_products} products')
all_prices = []
for i in range(1, num_of_products+1):
cost = float(input(f'Enter cost of product {i} $'))
mass = float(input(f'Enter mass of product {i} in grams:'))
# Make an if function here to make sure mass is not 0.
# Maybe force the user to enter a valid mass with a while True loop
if mass != 0:
price = cost/mass
print(f'Product {i} at ${price} per gram')
# Append list (price, product)
all_prices.append([price, i])
else:
print("error, no mass")
print(
f'Best product is Product {min(all_prices,key=lambda x:x[0])[1]}')
# Send back all prices
return all_prices
Then save them as prices, and iterate over each product:
prices = best_cost()
discount_question = input(
'Is there a discount on any of the products? (yes, no)\n> ')
if discount_question.strip().lower() == "yes":
print("Enter discount% for aech product. No discount = 0")
for i, j in enumerate(prices):
# Unpack list
price, product = j
discount = float(input(f"{product}: {price}\n> %"))
prices[i][0] = prices[i][0]*(1-(discount/100))
print(f" - New price of {prices[i][0]}")
while True:
products = int(input('How many products are there? '))
if products < 1:
print(f'Enter valid number for number of products')
else:
print(f'Finding best value out of {products} products')
all_prices = []
for i in range(1, products+1):
cost = float(input(f'Enter cost of product {i} $'))
mass = float(input(f'Enter mass of product {i} in grams:'))
print(f'Product {i} at ${cost / mass} per gram')
price = cost/mass
all_prices.append(price)
for product in all_prices:
if product == min(all_prices):
best_product = all_prices.index(product)+1
print(f'Best Product is Product {best_product}')
discount_question=input('Is there a discount on any of the products? ')
if 'yes' in discount_question:
print("Enter in 0 if there isn't a discount on thet item.")
else
print(f'Best product is Product {best_product}')
for i in range(1, products+1):
discount_1 = float(input(f'Discount for Product {i} (%): '))
discount1 = (({cost}*discount_1)/100)
print(f'Best product is Product {best_product}')
best_cost()```

Donation system loop where the system will ask again until the fixed target amount is reached

I wrote this code but I don't know how to add all donations for each donor when the loop runs several times.
It should print like this:
Donor 1 has donated £10 in total
Donor 2 has donated £15 in total...
import random
number_of_staff = (random.randint(3,5))
suggested_donation = (random.randint(10, 20))
amount_to_be_raised = number_of_staff * suggested_donation
a = []
def amount():
print('Amount to be raised by team number ______is £', amount_to_be_raised, '.')
print('Number of staff that will contribute is', number_of_staff)
print('Suggested donation is', suggested_donation)
def donation_loop(number_of_staff):
for j in range(number_of_staff):
print('Donor', j + 1)
actual_donation = int(input('Please enter donation £'))
a.append(actual_donation)
global b
b = sum(a)
print('The total sum donated is', b)
def stop():
while b < amount_to_be_raised:
donation_loop(number_of_staff)
else:
pass
amount()
donation_loop(number_of_staff)
stop()
Your code is almost correct, you have several ways to fix it, my favorite one is as follows:
import random
number_of_staff = (random.randint(3,5))
suggested_donation = (random.randint(10, 20))
amount_to_be_raised = number_of_staff * suggested_donation
a = {}
def amount():
print('Amount to be raised by team number ______is £', amount_to_be_raised, '.')
print('Number of staff that will contribute is', number_of_staff)
print('Suggested donation is', suggested_donation)
def donation_loop(number_of_staff):
global total_donations
for j in range(number_of_staff):
print('Donor', j + 1)
actual_donation = int(input('Please enter donation £'))
total_donations += actual_donation
if f'Donor{j + 1}' not in a:
a[f'Donor{j + 1}'] = []
a[f'Donor{j + 1}'].append(actual_donation)
print('The total sum donated is', total_donations)
def stop():
while total_donations < amount_to_be_raised:
donation_loop(number_of_staff)
amount()
total_donations = 0
stop()

Calling Function in Function without Arguments

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

Python Repetition Structures and Files

I have a question about my python program . I have trouble finding the total and ntotal in this program. Rest works fine. Is there any way i can fix this? I have this program due soon. I'd appreciate any tips I can get :D Thanks
midSalary = 50000
maxSalary = 60000
def main():
inFile = open('program7.txt', 'r')
lineRead = inFile.readline()
total = 0.0
ntotal = 0.0
count = 0
while lineRead != '':
words = lineRead.split()
for word in words:
num = float(word)
total += num
count += 1
print("\nFaculty Member # ",count, ": $" , format(num, '.2f'), sep ="")
if num >= maxSalary:
payIncrease(num, .04)
elif num >= midSalary:
payIncrease(num, .07)
else:
payIncrease(num , .055)
lineRead = inFile.readline()
#averagePayRaise = (ntotal - total) / count
inFile.close()
for divider in range(45):
print("-", end ='')
print("\nTotal Faculty payroll : $", format(total , ",.2f"),sep ="")
print("The New Total Faculty payroll : $", format(ntotal , ",.2f"),sep ="")
print("Average Pay Raise : $", format(averagePayRaise, ",.2f"), sep ="")
def payIncrease(amount, prcnt):
print("Pay Raise Percent : ", format(prcnt*100, ".1f")+"%")
total = 0.0
ntotal = 0.0
count = 0
salRaise = amount * prcnt
newSal = amount + salRaise
print("Pay Raise : $", format(salRaise, ',.2f'), sep ="")
print("New Salary : $", format(newSal, ',.2f'), sep = "")
total += amount
count += 1
ntotal += newSal
averagePayRaise = (ntotal - total) / count
main()
By default, names that you assign to in Python are local to the function in which they are declared. So, if you have:
def main():
total = 0
def payIncrease():
total = 0
total += amount
then you have two independent values named total. One way to solve this is to make it global:
total = 0
def main():
global total
total = 0
def payIncrease():
global total
total += amount
Note that you don't want to assign total = 0 inside payIncrease(), because that would reset your running total to 0. You probably added that when you broke out your code into the payIncrease() function because Python gave you an error without that.
def payIncrease(salary):
if current_sal >= maxSalary: return 0.04
if current_sal >= midSalary: return 0.07
return 0.055
def processSalaryData(line):
"""take a line and return current salary and new salary (note that a line is actually just a float)"""
try:
current_sal = float(line)
except ValueError:
return None
return current_sal,current_sal + current_sal*payIncrease(current_sal)
def main():
salaryData = [processSalaryData(line) for line in open("salaries.txt")]
salaryData = filter(None,salaryData) #filter out invalid data
adjustments = [b-a for a,b in salaryData]
old_salaries,new_salaries = zip(*salaryData)
print "OLD TOTAL PAYROLL :",sum(old_salaries)
print "NEW TOTAL PAYROLL :",sum(new_salaries)
print "AVG ADJUSTMENT:",sum(adjustments)/len(adjustments)
print "MAX SALARY:",max(new_salaries)
print "MIN SALARY:",min(new_salaries)

Categories

Resources