Below is my code. the issue is in MAIN. The code works as a person trying to buy items into a cart and you can see the total price of those items. They have to enter in the price for each item that they want. If a person inputs a number to two decimal places, it rounds it to the nearest whole number.
import locale
class CashRegister:
def __init__(self):
mself.items = 0
self.price = int(float(0.00))
def addItems(self,price): #keeps track of total number of items in cart
self.price += price
self.items += 1
print(self.price)
def getTotal(self): #returns total price
return self.price
def getCount(self): #return the item count of the cart
return self.items
def clearCart(self): #clears cart for another user or checkout
self.items = 0
self.price = int(float(0.00))
def main():
user_name = input('What is your name?\n') #weclomes user
print("Hello",user_name)
locale.setlocale(locale.LC_ALL, 'en_US')
user_name = CashRegister() #user is using the cash register
while True:
line = input ("Would you like to add another food item to your cart? Choose y or n \n")
if line == "y":
** price = int(float(input("please input the price of the item\n")))
print(price)**
user_name.addItems(price) #user adds prices to cart
elif line == "n":
print("Your total checkout price:", locale.currency(user_name.getTotal()) )
# int(float(locale.currency(user_name.getTotal())))
print("Your total item count", user_name.getCount())
user_name.clearCart() #clears cart for another user/checkout
break
else:
print("Error")
if __name__ == '__main__':
main()
As soon as the person inputs the number, I printed it to see if that's where the problems lies. I'll enter 3.20 but it automatically converts it to 3. I have no idea how to force it to keep those decimals. I even tried printing it with the int/float and it still doesn't work.
The int() function always returns an integer. An integer never has any decimal points. So use only
float(input("please input the price of the item\n"))
instead of
int(float(input("please input the price of the item\n")))
Related
I am coding a program that simulates someone making a purchase in a grocery store. I am displaying all the products and the price and I am prompting the user to input all the products they went to buy separated by commas. I want the program to check if the input is in the dictionary of product and add it to the cart with the use of a loop. Before adding it to cart the program needs to check if the input is valid, meaning if the item is in the list of products to buy. When the user selects an item to buy, I want the program to ask the user for the quantity of that item, so how many of the item they want to buy. At the samThen the program will calculate the total of all the products, then calculate the tax value, 24% of the total, and then return a subtotal that includes tax. Here is what I have so far:
def calculatetotal(slist, produce):
# for each item on the shoping list look up the cost & calculate total price
item_price = 0
subtotal = 0
VAT = 0
final_total = 0
basket = {}
for item in slist:
item_price = produce.get(item)
basket[item] = item_price
subtotal = subtotal + item_price
basket["Subtotal"] = subtotal
#calculating VAT
VAT = subtotal * 0.24
basket["VAT"] = VAT
#calculating price with tax
final_total = subtotal + VAT
basket["Total"] = final_total
# print off results
return basket
def main():
# set up grocery list with prices
produce={"Rice":5.00, "Bread":2.00, "Sugar":1.5, "Apple":0.75, "Cereal":3.75, "Gum": 1.00, "Water": 1.75, "Soda": 2.00}
# process input from the user - get a shopping list
item = input("Please enter the items that you want to buy: ")
slist = []
while(item != 'stop'):
if not (item in slist):
slist.append(item)
item = input("Please enter the items that you want to buy: ")
result = calculatetotal(slist, produce)
print(result)
main()
I've gotten most of it, but the small changes that I mentioned above, I can't figure out what to do. I forgot to mention that asking for the quantity of the item and checking if the user input has to be done with a loop. Any input is very much appreciated. Please show the change of code. Thank you in advance.
In this case I would simply go for a while loop
while True:
item = input("Please enter the items that you want to buy: ")
if item == 'Stop':
break
elif item not in produce or item in slist:
# error message or whatever
else:
num = int(input("Enter Quantity"))
# other operations
I am trying to print the total of the shopping list but every time i call on the string it prints 0 instead of what it should be.
cash_due = 0
import pickle
picklee = open('Store_stuff.pickle', 'rb')
contents = pickle.load(picklee)
picklee.close()
shopping_list = ['Name price quantity total']
store_contents ='''Store Contents
Name Price GTIN-8 Code
Butter £1.20 70925647
Chocolate £1.00 11826975
Bread £1.00 59217367
Cheese £2.80 98512508
Bacon £2.40 92647640
Lamb £4.80 49811230
Ham £2.59 53261496
Potatoes £2.00 11356288
Chicken £3.40 89847268
Eggs £1.29 21271243'''
def item(barcode, quantity, cash_due, shopping_list):
shopping_list.append(contents[barcode]['name']+' £'+(str((int(contents[barcode]['price']))/100))+' '+str(quantity)+' £'+str((int(quantity)*int(contents[barcode]['price']))/100))
print(cash_due)
print(contents[barcode]['price'])
print(quantity)
cash_due += ((int(contents[barcode]['price'])*(int(quantity)))/100)
print(cash_due)
def shopkeeper_ui():
print('Welcome to Stanmore\'s Food Emporium! Feel free to browse.')
print(store_contents)
user_input = ''
while user_input != 'finish':
user_input = input('''Welcome to the checkout.
instructions -
if you are entering text make sure your \'CAP\'s Lock\' is turned off
if you are entering a barcode number, please enter it carefully
if you want to print your current recipt, enter \'recipt\'
if you want to see your current total, enter \'total\'
and if you are finished, enter \'finish\'
You can see the stores contents below
Thanks for shopping: ''')
if len(user_input) == 8:
quantity = int(input('Enter the quantity that you want: '))
item(user_input, quantity, cash_due, shopping_list)
elif user_input == 'recipt':
count8 = 0
for i in shopping_list:
print(shopping_list[count8])
count8 += 1
elif user_input == 'finish':
print('Your shopping list is',shopping_list,' \nand your total was', total,'\n Thank you for shopping with Stanmore\'s Food Emporium')
elif user_input == 'total':
print('your total is, £',cash_due)
else:
print('User_input not valid. Try again...')
shopkeeper_ui()
If i enter the code and my first entry is 21271243 (the barcode for eggs). then i enter 4 for the quantity. i can get the shopping_list list to understand the total and if I print the string cash_due from inside the item function it understands it but as soon as i try to call cash_due from the shopkeeper_ui function it prints 0 instead of what should be 5.12?
cash_due is not mutable. Changes in item function are lost when leaving the function.
Generally, the way out of this is to let the function (item) return the value.
In this case, I would just keep cash_due out of item function and let item only return the cost for that item. Something like this:
def item(barcode, quantity, shopping_list):
shopping_list.append(contents[barcode]['name']+' £'+(str((int(contents[barcode]['price']))/100))+' '+str(quantity)+' £'+str((int(quantity)*int(contents[barcode]['price']))/100))
print(contents[barcode]['price'])
print(quantity)
cost = ((int(contents[barcode]['price'])*(int(quantity)))/100)
print(cost)
return cost
[...]
if len(user_input) == 8:
quantity = int(input('Enter the quantity that you want: '))
cash_due += item(user_input, quantity, shopping_list)
You don't have the same issue with shopping_list because it is a mutable: it is changed in place. Read about mutables to understand the concept.
However, it could be better design to not let item modify the list. It could just return both the list element and the cost, and the caller would modify the list.
def item(barcode, quantity):
stuff = (contents[barcode]['name']+' £'+(str((int(contents[barcode]['price']))/100))+' '+str(quantity)+' £'+str((int(quantity)*int(contents[barcode]['price']))/100))
cost = ((int(contents[barcode]['price'])*(int(quantity)))/100)
return stuff, cost
[...]
if len(user_input) == 8:
quantity = int(input('Enter the quantity that you want: '))
stuff, cost = item(user_input, quantity, shopping_list)
shopping_list.append(stuff)
cash_due += cost
So my friend and I have been working on this problem for a few days now for our Intro to Python class at our college, but we are a bit stuck due to the fact we didn't spend much time on this topic in class. Our problem is this, "Every product ID must be six characters long and starts with three upper case letters followed by three digits. For example ABE123 and PPL334 are valid product IDs but ABE1.2 and P1L3R4 are not. The auction site has a minimum bid price of 5 dollars and caps bids at 500 dollars. Bids with dollars and cents are acceptable. For example 6.78 is a valid bid. The following code reads in bids from the prompt (keyboard inputs) and loads the product ids and bidding prices into two lists products and bids. Unfortunately the code contains no input validation which is your job to complete." Our teacher gave us the code, we just have to validate the inputs. But it has to be done outside of her code, as in its own function. Here is the code:
`def getbids():
products = []
bids = []
answer = "yes"
while answer == "yes":
productid = input("Enter the productID ")
bid = float(input("Enter the bid for one item "))
products.append(productid)
bids.append(bid)
answer = input("Are there more bids? ")
return products, bids`
Basically, our job is to validate the productid and the bid in separate functions. I have our code here but what we have doesn't work completely and is not correct.
Here is the one for productId:
`def validprod(n):
caps="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
nums="0123456789"
m="Error"
if len(n)!=6:
print("Error, productID must be 6 digits,3 capital letters followed by 3 numbers")
return m
else:
while len(n)==6:
for i in range(3):
if n[i] not in caps or n[i+3] not in nums:
print("Error, productID must be 6 digits,3 capital letters followed by 3 numbers")
return m
else:
return n`
Here is the one for bids:
`def validbid(x,y):
bid="Error"
while x=="Error":
return bid
while x!="Error":
if y>500 or y<5:
print("Error, bid must be between 5 and 500(do not include a dollar sign with your bid).")
return bid
else:
return y`
We know there is probably a much simpler way to do it, we just don't know it.
import re
pid_regex = re.compile(r'^[A-Za-z]{3}\d{3}$')
def is_valid_pid(pid):
if pid_regex.match(pid):
return True
return False
def is_valid_bid(bid):
return bid >= 5 and bid <= 500
def getbids():
products = []
bids = []
answer = "yes"
while answer == "yes":
productid = input("Enter the productID ")
products.append(productid)
bid = float(input("Enter the bid for one item "))
bids.append(bid)
answer = input("Are there more bids? ")
return products, bids
products = dict(zip(*getbids()))
for pid in products:
bid = products[pid]
if not is_valid_pid(pid):
print('PID {} is invalid.'.format(pid))
break
elif not is_valid_bid(bid):
print('PID {} has an invalid bid {}'.format(pid, bid))
break
else:
print('PID {} to bid {} seems OK.'.format(pid, bid))
Note: I needed to fix your getbids() function, because products were not being appended to the products list.
Another note: If you believe I was wrong to provide a complete solution, please let me know. I'm completely open to feedback from the public.
So I basically created my functions ( def main(), load(), calc(), and print().
But I do not know how I can allow the user to input the information as many times as he/she wants until they want to stop. Like I they input 5 times, it would also output 5 times. I have tried putting the while loop in the def main() function and the load function but it won't stop when I want it to. Can someone help? Thanks!
def load():
stock_name=input("Enter Stock Name:")
num_share=int(input("Enter Number of shares:"))
purchase=float(input("Enter Purchase Price:"))
selling_price=float(input("Enter selling price:"))
commission=float(input("Enter Commission:"))
return stock_name,num_share,purchase,selling_price,commission
def calc(num_share, purchase, selling_price, commission):
paid_stock = num_share * purchase
commission_purchase = paid_stock * commission
stock_sold = num_share * selling_price
commission_sale = stock_sold * commission
profit = (stock_sold - commission_sale) - ( paid_stock + commission_purchase)
return paid_stock, commission_purchase, stock_sold, commission_sale, profit
def Print(stock_name,paid_stock, commission_purchase, stock_sold, commission_sale, profit):
print("Stock Name:",stock_name)
print("Amount paid for the stock:\t$",format(paid_stock,'10,.2f'))
print("Commission paid on the purchase:$", format(commission_purchase,'10,.2f'))
print("Amount the stock sold for:\t$", format(stock_sold,'10,.2f'))
print("Commission paid on the sale:\t$", format(commission_sale,'10,.2f'))
print("Profit(or loss if negative):\t$", format(profit,'10,.2f'))
def main():
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
main()
You have to give the user some kind of way to declare their wish to stop the input. A very simple way for your code would be to include the whole body of the main() function in a while loop:
response = "y"
while response == "y":
stock_name,num_share,purchase,selling_price,commission = load()
paid_stock,commission_purchase,stock_sold,commission_sale,profit = calc(num_share, purchase, selling_price, commission)
Print(stock_name, paid_stock,commission_purchase, stock_sold, commission_sale, profit)
response = input("Continue input? (y/n):")
an even simpler way would be two do the following....
while True:
<do body>
answer = input("press enter to quit ")
if not answer: break
alternatively
initialize a variable and avoid the inner if statement
sentinel = True
while sentinel:
<do body>
sentinel = input("Press enter to quit")
if enter is pressed sentinel is set to the empty str, which will evaluate to False ending the while loop.
So first I'm trying to make a class, which holds an item's name, price, and quantity available. Then I wanted to make a function that will deduct the quantity sold to a buyer after they enter the amount they are buying, and then calculate the total price.
Now to add on top of that, I am trying to have the user select from a list of items.
The problem is it seem I seem to be getting errors around the time the program starts running the 'buy' function.
class Retail:
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy (self):
print ("How many are you buying?")
quant = int(input("Amount: "))
unitsOnHand -= quant
subto = price * quant
total = subto * 1.08
print ("There are now ", unitsOnHand, " left")
print ("The total price is $", total)
box = Retail(4.95, 20, "Boxes")
paper =Retail(1.99, 50, "Big Stacks of Paper")
staples =Retail(1.00, 200, "Staples")
ilist = (box, paper, staples)
print ("Which are you buying? ", [box.description, paper.description, staples.description])
ioi = input("Please use the exact word name: ")
if ioi == 'box':
Retail.buy(ilist[0])
elif ioi == 'paper':
Retail.buy(ilist[1])
elif ioi == 'staples':
Retail.buy(ilist[2])
The error I get when I tried to run it is
Traceback (most recent call last):
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 22, in <module>
Retail.buy(ilist[0])
File "C:/Users/XXXXXX/XXXX/Code/Retailclass", line 9, in buy
unitsOnHand -= quant
UnboundLocalError: local variable 'unitsOnHand' referenced before assignment
I'm guessing is that it doesn't see the values I already assigned to the item, and if that is the case, how do I get it to?
Others have pointed out your error, but the other thing that is wrong is your buy call needs to be done on an instance of the object, not the class itself. In other words, right now you are executing buy on the Retail class where you need to execute it on instance (objects) of the class.
I have another suggestion to help organize your code. Use a dictionary to map the keys to the various objects to make your loop a bit cleaner. Putting all that together (and some other checks), here is an updated version of your class:
class Retail(object):
def __init__(self, price, unitsOnHand, description):
self.price = price
self.unitsOnHand = unitsOnHand
self.description = description
def buy(self):
if self.unitsOnHand == 0:
print('Sorry, we are all out of {} right now.'.format(self.description))
return
print("How many are you buying? We have {}".format(self.unitsOnHand))
quant = int(input("Amount: "))
while quant > self.unitsOnHand:
print('Sorry, we only have {} left'.format(self.unitsOnHand))
quant = int(input("Amount: "))
self.unitsOnHand -= quant
subto = self.price * quant
total = subto * 1.08
print("There are now {} left".format(self.unitsOnHand))
print("The total price is ${}".format(total))
return
stock = {}
stock['box'] = Retail(4.95, 20, "Boxes")
stock['paper'] = Retail(1.99, 50, "Big Stacks of Paper")
stock['staples'] = Retail(1.00, 200, "Staples")
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
while ioi not in stock:
print("Sorry, we do not have any {} right now.".format(ioi))
print("Which are you buying? {}".format(','.join(stock.keys())))
ioi = input("Please use the exact word name: ")
stock[ioi].buy()