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()```
Related
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.
I have been experimenting with creating an investment calculator, and I want to print the annual totals as well as the annual compounded interest. It's doing the annual totals fine, but not the annual interest. My inputs are $10000.00 principle, at 5% interest over 5 years.
start_over = 'true'
while start_over == 'true':
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate"))
addition = int(input("Type annual Addition"))
time = int(input("Enter number of years to invest"))
real_rate = rate * 0.01
i = 1
print('total', principle * (1 + real_rate))
while i < time:
principle = (principle + addition) * (1 + real_rate)
i = i + 1
print('total', principle)
for i in range(time):
amount = i * (((1 + rate/100.0) ** time)) * principle
ci = amount - principle
i += 1
print("interest = ",ci)
redo_program = input('To restart type y or to quit type any key ')
if redo_program == 'y':
start_over = 'true'
else:
start_over = 'null'
Here are my outputs:
Type the amount you are investing: 10000
Type interest rate5
Type annual Addition0
Enter number of years to invest5
total 10500.0
total 10500.0
total 11025.0
total 11576.25
total 12155.0625
interest = -12155.0625
interest = 3358.21965978516
interest = 18871.50181957032
interest = 34384.78397935548
interest = 49898.06613914064
To restart type y or to quit type any key
Give this a go:
# Calculate year's values based on inputs and the current value of the account
def calc(current, addition, rate, year):
multiplier = 1 + rate/100 # The interest multiplier
new_total = (current + addition) * multiplier # Calculate the total
interest = round((new_total - current - addition), 2) # Interest to nearest penny/cent
return new_total, interest
def main():
# Inputs
principle = int(input("Type the amount you are investing: "))
rate = float(input("Type interest rate: "))
addition = int(input("Type annual Addition: "))
invst_time = int(input("Enter number of years to invest: "))
# Sets current account value to principle
current = principle
# Prints values for each year of investment
for i in range(invst_time):
total, interest_gained = calc(current, addition, rate, i+1)
print("At the end of Year: ", i+1)
print("Total: ", total)
print("Interest: ", interest_gained)
print("------")
current = total # Updates value of account
# Restart Program check
while 1:
repeat_choice = input("Would you like to restart and check with different values? (Y/N)")
if repeat_choice == "Y":
main()
elif repeat_choice == "N":
print("Thanks for using the calculator")
break
else:
print("Enter Y or N!") # Error handler
continue
main()
so I am trying to learn python and have a csv file like this
1 product_id product_name price
2 1001 cake 15
3 1002 sprite 30
4 1003 coffee 50
5 1004 ice cream 30
6 1005 banana 10
my program is
import csv
productid=input("Enter the product ID: ")
quantity=int(input("Enter the quantity: "))
csv_file=csv.reader(open("shoppinglist.csv", "r"),delimiter=",")
for row in csv_file:
if productid==row[0]:
product_id=row[0]
product_name=row[1]
product_price=row[2]
print("\nProduct ID: {}".format(row[0]))
print("Product Name: {}".format(row[1]))
print("Product Price: {}".format(row[2]))
total=quantity*(int(product_price))
print("\nThe Total Amount Payable is: {}".format(total))
I can enter one productid at a time and get the output but i am looking for a way so that i can enter multiple productid's ad they get searched in the csv file and then the total is calculated and all the product details output.
PS: I have tried to explain my problem as best as i can but if i have made any mistake please be kind to point it out to me
my output is
Enter the product ID: 1001 Enter the quantity: 5
Product ID: 1001 Product Name: cake Product Price: 15
The Total Amount Payable is: 75
i just do not want to print the product but to search for its id in the csv file and if it exits ask the user to input the quantity for every productid entered and then print the details of the products along with the total amount.
You Need a Loop to look around to your product each time you offered a product Id
I Hope You Understand the following code.
# Author Name : Sandip Sadhukhan
import csv
def findProduct(productId):
csv_file = csv.reader(open('shoppinglist.csv', 'r'), delimiter=',')
productPrice = 0
productName = ''
isFound = False
for row in csv_file:
if productId == row[0]:
productName = row[1]
productPrice = row[2]
isFound = True
break
result = {
'isFound': isFound,
'productName': productName,
'productPrice': productPrice,
'productId': productId
}
return result
total = 0
printList = []
while(True):
productid = input("Enter a product Id: ")
result = findProduct(productid)
if not(result['isFound']):
print("Product is not found...")
continue
quantity = int(input("Enter the quantity: "))
if(quantity <= 0):
print("Please select atleast 1 quantity.")
continue
total += quantity * (int(result['productPrice']))
temp = [result['productName'], quantity, result['productPrice']]
printList.append(temp)
addMore = input("Add more Items? (Y/N) : ")
if(addMore.lower() == 'n'):
break
print("\nBill\n====\n\n[Product Name] [Product Price] [Quantity]")
for item in printList:
print("{} {} {}".format(item[0], item[2], item[1]))
print("The total Amount payable is : {}".format(total))
You can just parse your input to be the way you want. For example,
def product(id): # given product id, returns price, 0 if item does not exist
# your code goes here
id = input("Enter your product ids separated by spaces: ") # For e.g. 2 3 1
id = id.split(" ")
total = 0
for i in id:
price = product(id)
if price != 0:
quantity = print("Enter quantity of " + str(id) + ": ")
total += quantity*price
print("The total price is: " + price)
This code parses the ids so they are in an array. It then goes through each id in the array and performs your code.
You should really look into pandas, it's going to make all these kinds of operations much simpler.
My program is supposed to display the total occupancy rate and individual floor occupancy of a hotel. The total amount of rooms occupied does not accumulate with each iteration. I've attempted to dissect the issue but to no avail. I have a feeling the problem is obvious.
#Welcome message and hotel info
print("WELCOME TO THE GRAND NEW HOTEL!!!")
print("-----------------------------------")
print("Total number of floors in the hotel : 8")
print("Total number of rooms in each floor : 30")
print("Total Number of rooms in the hotel :240\n")
print("-----------------------------------\n")
#Variable for Hotel
total_in_floor = 30
total_in_hotel = 240
rented_in_floor = 0
rented_in_hotel = 0
rate_of_floor = 0
rate_of_hotel = 0
#User Input
for i in range(8):
while True:
try:
#loop until the nimber is correct
print("Please enter rented rooms in Floor No. {0}".format(i+1))
rented_in_floor = int(input())
if 0 <= rented_in_floor <= 30:
break
except ValueError:
#int() will not go past until input is a valid number
print("Retry")
rate_of_floor = int((rented_in_floor))/int((total_in_floor))*100
print("Occupancy rate of Floor No.{0} is = {1}%\n".format(i+1,round(rate_of_floor,2)))
rented_in_hotel = int(rented_in_hotel) + int(rented_in_floor)
rate_of_hotel = int((rented_in_hotel))/int((total_in_hotel))*100
print("Total rooms rented in entire hotel : {0}\n".format(rented_in_hotel))
print("Occupancy rate of the hotel is = {0} % \n".format(round(rate_of_hotel,2))
#Welcome message and hotel info
print("WELCOME TO THE GRAND NEW HOTEL!!!")
print("-----------------------------------")
print("Total number of floors in the hotel : 8")
print("Total number of rooms in each floor : 30")
print("Total Number of rooms in the hotel :240\n")
print("-----------------------------------\n")
#Variable for Hotel
total_in_floor = 30
total_in_hotel = 240
rented_in_floor = 0
rented_in_hotel = 0
rate_of_floor = 0
rate_of_hotel = 0
#User Input
for i in range(8):
while True:
try:
#loop until the nimber is correct
print("Please enter rented rooms in Floor No. {}".format(i+1))
rented_in_floor = int(input())
if 0 <= rented_in_floor <= 30:
rate_of_floor = int((rented_in_floor)) / int((total_in_floor)) * 100
print("Occupancy rate of Floor No.{0} is = {1}%\n".format(i + 1, round(rate_of_floor, 2)))
break
except ValueError:
#int() will not go past until input is a valid number
print("Retry")
rented_in_hotel = int(rented_in_hotel) + int(rented_in_floor)
rate_of_hotel = int((rented_in_hotel))/int((total_in_hotel))*100
print("Total rooms rented in entire hotel : {0}\n".format(rented_in_hotel))
print("Occupancy rate of the hotel is = {0} % \n".format(round(rate_of_hotel,2)))
Try this code.
Hope this helps.
If I understood correctly what you need, I think this modified code may help you.
I have added some comments in the parts I've modified or added.
print("WELCOME TO THE GRAND NEW HOTEL!!!")
print("-----------------------------------")
print("Total number of floors in the hotel : 8")
print("Total number of rooms in each floor : 30")
print("Total Number of rooms in the hotel :240\n")
print("-----------------------------------\n")
total_in_floor = 30
total_in_hotel = 240
rented_in_floor = 0
rented_in_hotel = 0
# rate_of_floor = 0 #not necessary at this point
rate_of_hotel = 0
list_of_floors = [] # create a list where storing "rented_in_floor" for each floor
for i in range(8):
while True:
try:
print("Please enter rented rooms in Floor No. {0}".format(i+1))
rented_in_floor = int(input())
if 0 <= rented_in_floor <= 30:
list_of_floors.append(rented_in_floor) # add the number of rented rooms in the "i+1"th floor to the list
rented_in_hotel += rented_in_floor # accumulate the total amount of rooms occupied in the hotel
break
else: # in the case the input number is larger than 30, explain what is the problem
print("Please enter a number of rented room not larger than 30")
except ValueError:
print("Retry")
for i in range(8): # print all the floors' occupancy rates
rented_in_floor_temp = list_of_floors[i] # select the number of rented room in the floor of index i inside "list_of_floors" (basically, the "i+1"th floor of the hotel)
rate_of_floor = int((rented_in_floor_temp))/int((total_in_floor))*100 # same as before, but with "rented_in_floor_temp"
print("Occupancy rate of Floor No.{0} is = {1}%\n".format(i+1,round(rate_of_floor,2)))
# rented_in_hotel = int(rented_in_hotel) + int(rented_in_floor) # delete, "rented_in_hotel" has been defined above already
rate_of_hotel = int((rented_in_hotel))/int((total_in_hotel))*100
print("Total rooms rented in entire hotel : {0}\n".format(rented_in_hotel))
print("Occupancy rate of the hotel is = {0} % \n".format(round(rate_of_hotel,2)))
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