Why can't I print the result from within the function? - python

I'm working through the beginner's Python course in CodeAcademy. This is part of one of the exercises, where you're "checking out" at a grocery store, but I wanted to the code to print the final bill/"total" rather than just returning "total". I don't understand why it's not printing. I have tried putting it at the end, after the iteration, and, as here, within the recursion (before returning the total) to see if it'll print after each step. When I run this code, nothing displays.
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
food = shopping_list
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print total
return total
Edit:
These also aren't giving me a readout:
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total #tried 0-5 indentations, same blank result
Yet
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total #tried 0-5 indentations, same blank result
return total
print compute_bill(food)
Returns
Total is $ 5.5
5.5
While - I did find a solution...
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
return total
print "Total is $",compute_bill(food)
Returns
Total is $ 5.5
...but I'm confused as to why I can't just print the variable total, which should have been updated. And why it works there, but not as a feed in the function. This is just a question from an exercise, but I'm having trouble figuring out why it's doing this.

In your first example,
shopping_list = ["banana", "orange", "apple"]
stock = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
food = shopping_list
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print total
return total
You define a function def compute_bill. You never call that function. The function is executed iff it's called, e.g. compute_bill(["banana"])

I'm not sure I quite understood the problem, but you said
but I'm confused as to why I can't just print the variable total, which should have been updated.
If you try to print total from outside the function it will not work, since the total variable is only declared within the function. When you return total you allow the rest of your code to get the data from outside your function, which is why print computeBill(food) does work.
Edit, also if you want to print the total at each iteration, your code:
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total
Should definitely have this indentation, which means you'll print every time you iterate in the for loop (if you leave it as it was, it'll only print after the for).

The print statement is the part of your function compute_bill(..), it won't be executed until and unless you call the function compute_bill(..).
def compute_bill(food):
total = 0
for item in food:
if stock[item]>0:
total += prices[item]
stock[item] -=1
print "Total is $",total #this works
compute_bill(food) # call the function it has the print statement

Related

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

How to multiply each key by another key in dictionaries?

I'm doing course in codeacademy and i'm on lession Something of Value
In my final task i have to For each key in prices, multiply the number in prices by the number in stock. Print that value into the console and then add it to total.
My code:
for cena in prices:
total = prices[cena]*stock[cena]
print total
It's printing 0.
I also tried this:
for cena in prices:
for ilosc in stock:
total = prices[cena]*stock[ilosc]
print total
It's also returning 0.
EDIT: Whole code:
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
total = 0
for cena in prices:
for ilosc in stock:
total = prices[cena]*stock[ilosc]
print total
It's printing 0 because the product of the "last" items in the dictionary is 0. If you want to know the products of each item in turn then you need to print inside the loop. If you want a total then you should either add to the existing value or use sum() with a generator expression (genex).
This worked for me
prices = {
"banana" : 4,
"apple" : 2,
"orange" : 1.5,
"pear" : 3,
}
stock = {
"banana" : 6,
"apple" : 0,
"orange" : 32,
"pear" : 15,
}
for key in prices:
print key
print "price: %s" % prices[key]
print "stock: %s" % stock[key]
total = 0
for key in prices:
price_of_stock = prices[key] * stock[key]
print price_of_stock
total = total + price_of_stock
print total
What about:
from itertools import chain
results = dict()
for k, v in chain(prices.iteritems(), stock.iteritems()):
if k in results:
results[k] *= v
else results[k] = v
I am also doing this course.My ansewer as below:
total=0
sums=0
for key in price:
print key
print "price: %s" % price[key]
print "stock: %s" % stock[key]
for x in stock:
sums=stock[x]*price[x]
print sums
total+=sums
print total
Mybe can give you a ref.

Can't figure out a Python exercise with dictionaries

I have the following code:
shoppingList = ["banana","orange","apple"]
inventory = {"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15
}
prices = {"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3
}
def calculateBill(food):
total = 0
for k in food:
total += prices[k]
return total
calculateBill(shoppingList)
The exercise tells me to complete the function following these instructions:
Don't add the price of an article in your bill if it is not in your inventory.
After you buy an article, substract one from the inventory.
I don't know how to do it and I don't know if I have any other mistakes in my code.
If it isn't clear, the value in inventory is the stock of that item, and the value in "prices" is the price.
First of all, I don't see comida defined anywhere before its use. I'll assume that by comida, you mean food.
Here is a simple solution:
def calculateBill(food):
total = 0
for k in food:
if inventory.get(k, 0) > 0:
total += prices[k] # updates total
inventory[k] = inventory[k] - 1 # updates inventory
return total
You could do the following
def calculateBill(food):
total = 0
for k in food:
if k in inventory:
if inventory[k] > 0:
total += prices[k]
inventory[k] = inventory[k] - 1
else:
print 'There are no %s in stock' % k
else:
print 'dont stock %s' % k
return total
For 1)
if k in inventory:
Will check if the key is present in your inventory dict.
For 2)
inventory[k] = inventory[k] - 1
Will substract 1 from your inventory
One flaw in this code is that it does not check that the inventory count is above 0 before allowing to buy. So
if inventory[k] > 0:
Does this.
Here's a complete solution.
class Error(Exception):
"""Base class for Exceptions in this module"""
pass
class QtyError(Error):
"""Errors related to the quantity of food products ordered"""
pass
def calculateBill(food):
def buy_item(food_item, qty=1, inv_dict=None, prices_dict=None):
get_price = lambda item,price_dct: price_dct.get(item,9999999)
if inv_dict is None:
inv_dict = inventory
if prices_dict is None:
prices_dict = prices
if inv_dict.get(food_item, 0) >= qty:
inv_dict[food_item] -= qty
return sum(get_price(food_item, prices_dict) for _ in range(qty))
else:
raise QtyError("Cannot purchase item '{0}' of quantity {1}, inventory only contains {2} of '{0}'".format(food_item, qty, inv_dict.get(food_item,0)))
total = sum(buy_item(food_item, 1, inventory, prices) for food_item in food)
return total

My display module doesn't display (Python 2.7)

This is for homework. This particular school offers 0 assistance and the professor is less than helpful. I am just looking for guidance as to why this code isn't working. I have to use Python 2.7. When I run the program it asks me to enter the appropriate amount of pints but then does nothing.
# This program finds the average number of pints collected, the highest amount, and the lowest amount
# Lab 9-4 Blood drive
#the main function
def main():
endProgram = 'no'
print
while endProgram == 'no':
print
# declare variables
pints = [0] * 7
totalPints = 0
averagePints = 0
highPints = 0
lowPints = 0
# function calls
pints = getPints(pints)
totalPints = getTotal(pints, totalPints)
averagePints = getAverage(totalPints, averagePints)
highPints = getHigh(pints, highPints)
lowPints = getLow(pints, lowPints)
displayInfo(averagePints, highPints, lowPints)
endProgram = raw_input('Do you want to end program? (Enter no or yes): ')
while not (endProgram == 'yes' or endProgram == 'no'):
print 'Please enter a yes or no'
endProgram = raw_input('Do you want to end program? (Enter no or yes): ')
#the getPints function
def getPints(pints):
counter = 0
while counter < 7:
pints[counter] = input('Enter pints collected: ')
counter = counter + 1
return pints
#the getTotal function
def getTotal(pints, totalPints):
counter = 0
while counter < 7:
totalPints = totalPints + pints[counter]
counter = counter + 1
return totalPints
#the getAverage function
def getAverage(totalPints, averagePints):
averagePints = totalPints / 7
return averagePints
#the getHigh function
def getHigh(pints, highPints):
highPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] > highPints:
highPints = pints[counter]
counter = counter + 1
return highPints
#the getLow function
def getLow(pints, lowPints):
lowPints = pints[0]
counter = 1
while counter < 7:
if pints[counter] < lowPints:
lowPints = pints[counter]
counter = counter + 1
return lowPints
#the displayInfo function
def displayInfo(averagePints, highPints, lowPints):
print "The average number of pints donated is ", averagePints
print "The highest pints donated is ", highPints
print "The lowest pints donated is ", lowPints
# calls main
main()
There is an infinite loop in function getLow() because counter is incremented only when the current value is less than the previous value. e.g. entering values 1, 2, 3, 4, 5, 6, 7 will result in an infinite loop, however, the loop will terminate if you entered 7, 6, 5, 4, 3, 2, 1.
Function getHigh() has a similar problem, but the values must be ascending if the infinite loop is to be avoided. Note that one of getLow() or getHigh() will always produce a loop in your code.
Hint: look at using Python's min() and max() functions.

Categories

Resources