Python: modify a table attribute from the options generated in another table - python

I have created two different functions, one to create an inventory of available products:
def create_piece():
print(Colour().blue('Creating a new piece'.center(200)))
piece_name = input(Colour().orange('Name of the piece: '))
piece_registration = input(Colour().orange('Piece registration number: '))
piece_date = input(Colour().orange('Date of manufacture: '))
piece_location = input(Colour().orange('Manufacturing location: '))
piece_price = input(Colour().orange('Price: '))
Parts.create(Name=piece_name , Parts_registration_number=piece_registration ,
Date_of_manufacture=piece_date ,
Manufacturing_locality=piece_location , Price=piece_price ,
Number_of_parts_sold='0')
print(Colour().green(('Part created satisfactorily')))
As you can see the option "Number_of_parts_sold" has the marker to 0.
Then I have created an option to execute purchase orders:
def order_purchase():
print(Colour().blue('Purchase order portal'.center(200))
Seller_name = input(Colour().orange('Who are you?: '))
number = int(input(Colour().orange('Number of items?: '))
pieces_list=[]
total_cost = 0
for i in range (0, number):
while True:
piece_name = input(Colour().orange('Name of the piece to buy: '))
try:
piece = Pieces.get(Pieces.Name == piece_name)
break
except DoesNotExist:
print(Colour().red('This piece does not currently exist in the system, ')
please enter a correct name.'))
ID = input(Colour().orange('Purchase ID: '))
for price in Piezas.select().where(Pieces.Name == piece_name):
price_orders = (price.price)
total_cost += price_orders
name_piece=str(name_piece)
parts_list.append(part_name)
Orders.create(ID_buy_orders=ID, Date_buy_orders=datetime.now(),
Order_Seller=Seller_name , Order_People = pieces_list,
Price_orders=total_cost)
print(Colour().green('Pieces sold satisfactorily'))
This last function fills in another table in which it stores the number of pieces that each seller buys. However, I would like to know how to relate the second table with the first so that for each piece that is sold (generated in the tuple "lista_piezas") change the marker and add in the first table how many pieces have been sold. How could I do this? Thanks in advance

Related

How to reduce repeated code with different variable names (python)

class Budget:
def __init__(self):
self.wants_perc = 0
self.wants_amt = 0
self.wants_left = 0
self.needs_perc = 0
self.needs_amt = 0
self.needs_left = 0
self.food_perc = 0
self.food_amt = 0
self.food_left = 0
while True:
try:
self.monthly_income = float(input("Enter your monthly income after taxes: "))
break
except ValueError:
print("Invalid Input : Please enter a number")
continue
while True:
print("Enter desired percentage of income spent for each category (do not include %): ")
try:
self.wants_perc = float(input("Wants: "))
self.needs_perc = float(input("Needs: "))
self.food_perc = float(input("Food: "))
if self.wants_perc + self.needs_perc + self.food_perc not in range(95, 105):
print("Invalid Input : Must add to 100%")
continue
else:
break
except ValueError:
print("Invalid Input : Please enter a number")
continue
def deposit(self):
dep_loc = input("Where would you like to deposit? ")
while True:
try:
if dep_loc.lower() == "wants":
self.wdep_amt = float(input("Deposit amount: "))
self.wants()
break
elif dep_loc.lower() == "needs":
self.ndep_amt = float(input("Deposit amount: "))
self.needs()
break
elif dep_loc.lower() == "food":
self.fdep_amt = float(input("Deposit amount: "))
self.food()
break
else:
print("Invalid Input")
break
except ValueError:
print("Invalid Input : Please enter a number")
continue
def wants(self):
self.wants_max = (self.wants_perc / 100) * self.monthly_income
self.wants_amt += self.wdep_amt
self.wants_left = self.wants_max - self.wants_amt
print(f"Amount spent on wants: ${self.wants_amt} \nAmount left to spend: ${round(self.wants_left,2)}")
def needs(self):
self.needs_max = (self.needs_perc / 100) * self.monthly_income
self.needs_amt += self.ndep_amt
self.needs_left = self.needs_max - self.needs_amt
print(f"Amount spent on needs: ${self.needs_amt} \nAmount left to spend: ${round(self.needs_left,2)}")
def food(self):
self.food_max = (self.food_perc / 100) * self.monthly_income
self.food_amt += self.fdep_amt
self.food_left = self.food_max - self.food_amt
print(f"Amount spent on food: ${self.food_amt} \nAmount left to spend: ${round(self.food_left,2)}")
wyatt = Budget()
while True:
wyatt.deposit()
I know this is a very general question, but is it possible to reduce the amount of repeated code I use? I feel like there has to be a way to use one general variable in a loop for each of the categories. My three functions that use the food, wants, and needs variables are all the exact same besides the names. I thought of getting user input and adding it to a list and indexing that list to get each category, but I couldn't fully figure it out. This may be too broad for stack overflow and if it is I apologize. Thanks!
In general there is no mechanism for reducing the amount of code - if there was, it would already be part of the language. Making a dictionary instead of member variables doesn't really help, because all it will do is replace your 9 member variables with 9 dictionary items.
However, there is an opportunity for factoring out repeated operations. Your instinct is correct that repeated blocks of code are a sign of poor design. I would suggest you start with a class structure something like this:
class BudgetItem:
def __init__(self, name):
self.name = name
self.perc = 0
self.amt = 0
self.left = 0
def get_perc(self):
self.perc = float(input(f"{self.name}: "))
class Budget:
def __init__(self, monthly_income):
self.monthly_income = monthly_income
self.wants = BudgetItem("Wants")
self.needs = BudgetItem("Needs")
self.food = BudgetItem("Food")
self.all_items = (self.wants, self.needs, self.food)
def gather_percentages(self):
print("Enter desired percentage of income"
" spent for each category (do not include %): ")
for b in self.all_items:
b.get_perc()
if 95.0 <= sum(b.perc for b in self.all_items) <= 105.0:
print("Precentages must sum to 100")
# etc.
Create a separate class to represent a budget category, since the logic for each is identical. Add methods to the little class to capture that logic. Now re-write your main class in terms of those three individual items. I won't take the time to refactor your whole program, but I hope you get the idea. You should end up with a much shorter program and no significant repeated logic.
One other thing: I think that putting an "input" statement in a class constructor is a terrible idea. Constructors should not contain complicated loops or extended logic. I would put it outside the class and pass the data into the class as arguments, or as method calls.

Extracting a tuple value from a dictionary in python

am working on a restaurant project, and I need a hand :)
so the program will display the main dishes, and the user has to enter which dish he/she wants..
and then the choice will be taken and then added to the bill (dish name, price, num of items)...
so far I chose a dictionary so when the user enters 1 (key), the program will display Mashroum Risto...
this what've created:
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:['Spagehtie',4.850]}
now my question is how to get the dish name without the price (the price is 3.950) and extract it! and also how to get the price without the name so then I can send it into the bill function to calculate it? and if you have any suggestions please go ahead, because i don't know if using dictionary was the right choice
def MainDish():
dishes = {1 : ('Mashroum Risito', 3.950), 2 : ['Tomato Pasta', 2.250],3:
['Spagehtie',4.850]}
dishes.values
print("1. Mashroum Risito 3.950KD")
print("2. Tomato Pasta 2.250KD")
print("3. Spagehtie 4.850KD")
choice = eval(input('Enter your choice: '))
NumOfItem = eval(input('How many dish(es): '))
while(choice != 0):
print(dishes.get(choice)) #to display the item only without the
price
a = dishes.values()
recipient(a)
break
The way you have implemented it:
print (dishes[1][0]) #will give you name
print (dishes[1][1]) #will give you price
where [x][y]
x = key in the dict (input in your case)
y = element of the value in the dict (0 = name, 1=price in your case)
You should probably create the dictionary better as below:
Follow up question is not so clear but I think this is what you are after roughly. You will need to tweak the returns to your usage:
def MainDish():
NumOfItem = float(input('How many dish(es): '))
dish = list(dishes)[choice-1]
cost_of_dish = dishes[dish]
totalcost = cost_of_dish * NumOfItem
print (f"\n\tOrdered {NumOfItem}x {dish} at {cost_of_dish}KD each. Total = {totalcost}KD\n")
return dish, cost_of_dish, totalcost
dishes = {'Mashroum Risito': 3.950, 'Tomato Pasta': 2.250}
for key,val in dishes.items():
print (f"{list(dishes).index(key)+1}. {key}: {val}KD")
keepgoing = True
while keepgoing:
choice = int(input('Enter your choice: '))
if choice == 0:
keepgoing = False
break
else:
dish, cost_of_dish, totalcost = MainDish()

python classes, def __init__(): and input statements

I am trying to define a class called 'Vacation' to store information about the user once they have answered a set of input statements (my project is a vacation program where the user answers a set of questions in order to receive a randomly generated vacation itinerary). My professor told me to put all of my questions (aka input statements) within my constructor, however I keep getting an error saying I have a syntax error although I am not sure why. I have tried putting the different variable names in the () of my constructor but this does nothing (I thought maybe I had a syntax error because I forgot to include one of the variable names - specifically the error is coming from 'excursions'). I am fairly new to Python (just started in January) so my knowledge of the programming language is very limited (plus I just learned classes about 2 weeks ago). Any and all help/feedback/ideas would be greatly appreciated!
class Vacation:
def __init__ (self, num_guests, max_price, vacay_len, excursions, user_input, excursions_price, excursions_num, user_preference):
user_input = input("Would you like a (R)andomly generated vacation or a (T)ailored vacation?: ")
num_guests = int(input("Please enter number of guests: "))
max_price = float(input("Please enter your maximum willingness to pay (ie. 700): "))
vacay_len = int(input("Please enter how many days you would like your vacation to be: ")
excursions = (input("Would you like to include excursions while on vacation? (Y/N) : ")).upper()
if excursions == "Y":
excursions_num = int(input("How many excursions would you like to sign up for (up to 2): "))
excursions_price = float(input("How much would you like to spend on each excursion? : "))
else:
print("Let's get to exploring!")
user_preference = user_input
self.user_preference = user_preference
self.num_guests = num_guests #number of guests
self.max_price = max_price #maximum price range
self.housing_price = .3(self.max_price) #housing budget allocation
self.vacay_len = vacay_len #vacation length
self.excursions_price = excursion_price #price for each excursion
self.excursions_num = excursions_num #number of excursions
You are missing closing bracket on this line:
vacay_len = int(input("Please enter how many days you would like your vacation to be: "))
You have a typo excursion_price should be excursions_price as below:
self.excursions_price = excursions_price #price for each excursion
You also need to add * for multiplication here:
self.housing_price = .3*(self.max_price)
You can remove the variables from the __init__ function in this case since they will be provided by the users input to the programme.
I would recommend using a python IDE which will highlight the issues for you in red.
Not sure if this is what you want but the following code seems to work:
class Vacation:
def __init__ (self):
user_input = input("Would you like a (R)andomly generated vacation or a (T)ailored vacation?: ")
num_guests = int(input("Please enter number of guests: "))
max_price = float(input("Please enter your maximum willingness to pay (ie. 700): "))
vacay_len = int(input("Please enter how many days you would like your vacation to be: "))
excursions = (input("Would you like to include excursions while on vacation? (Y/N) : ")).upper()
if excursions == "Y":
excursions_num = int(input("How many excursions would you like to sign up for (up to 2): "))
excursions_price = float(input("How much would you like to spend on each excursion? : "))
else:
print("Let's get to exploring!")
user_preference = user_input
self.user_preference = user_preference
self.num_guests = num_guests #number of guests
self.max_price = max_price #maximum price range
self.housing_price = .3(self.max_price) #housing budget allocation
self.vacay_len = vacay_len #vacation length
self.excursions_price = excursion_price #price for each excursion
self.excursions_num = excursions_num #number of excursions
As suggested by Steve I removed your variables from the constructors parameters as you probably won't be passing arguments. At the Excursions line you were simply missing a closing )

Create a list of strings with intiger value from user input

First of all, I would like to apologize to anyone if there was a similar topic, but I've been looking for a solution on this for hours now and couldn't find anything. Perhaps I don't know exactly how to ask the question. I am quite new to python and programming in general.
So my issue is the following. I am currently working on my first little "project" that is not just following a guide or an example program. What I am trying to do is create a list string from user input bit the list must have an integer value this is what I am trying:
s1 = []
product = []
menu = 1
while menu > 0:
print("1. Add employee.")
print("2. Add a product.")
print("3. Add a sale")
print("4. quit")
action = int(input("what would you like to do? Select a number: "))
if action == 1:
name = input("Employee name: ")
s1.append(name)
elif action == 2:
temp = input("Select the name of the product: ")
value = int(input("What is the price of the product: "))
int_temp = temp
product.append(int_temp)
temp = value
elif action == 4:
menu = -1
I also tried the following:
temp = input("Select the name of the product? ")
product.append(temp)
value = int(input("What is the price of the product? "))
product[-1] = value
But then it just replaces the string of the product with the integer of the input I can't seem to make it a list of strings that can be referenced later in a calculation. I hope I was clear enough in my explanation of my problem and goal.
Based on your comments i think you can use a dictionary instead of a list if you want to have a mapping of product name and product price. So the code would look like below
employees = []
products = {}
menu = 1
while menu > 0:
print("1. Add employee.")
print("2. Add a product.")
print("3. Add a sale")
print("4. quit")
action = int(input("what would you like to do? Select a number: "))
if action == 1:
name = input("Employee name: ")
employees.append(name)
elif action == 2:
product_name = input("Select the name of the product: ")
product_price = int(input("What is the price of the product: "))
products[product_name] = product_price
elif action == 4:
menu = -1
Then later in your code you can simply do like this.
sales = products['apples'] * 100
or
sales = products.get('apples', 0) * 100
Hope this helps !!
Your code contains some errors, which I have mentioned below. Remove them and try again
Remove print from your input statements:
Like change this line:
name = input(print("Employee name: "))
to this:
name = input("Employee name: ")
Before this line of code:
product.append(int_temp)
make sure the product list is initiated like:
product = list()
And this line below:
product[-1] = value
will change the last value in the product list since -1 will refer to the last index, -2 will refer to second last and so on.

Creating a sales list that allows users to enter multiple items

I've been working on a project for my class in python and I feel like no matter what I do I can't get it right. We're supposed to create a program that captures 3 items and then 4 bits of information for each item. AKA: Item: x, Quantity: x, price $x, weight x pounds. Then it should print out a subtotal, shipping & handling cost, tax total, and final total. The issue I'm having is that we're not allowed to create a variable for each item and must do everything in a loop. No matter what I've tried all I can do is get everything to print out the last data entered.
Here's my code so far:
def main():
#Range of 3 so that user may enter 3 seperate items
for i in range(3):
#Grabs user input for item description and/or name
strDescription = str(input("Enter description of item: "))
#Grabs user input for price of item
fltPrice = float(input("Enter price of item: $ "))
#Grabs user input for quanitity of item
intQuantity = int(input("Enter quantity of item: "))
#Grabs user input for weight of item in pounds
fltWeight = float(input("Enter weight of item in pounds: "))
#Subtotal is equal to price times number of items purchased
fltPriceSub = fltPrice*intQuantity
#Shipping 25 cents per pound
intShipping = (.25*fltWeight)
#There is a base fee of $5 per order applied to shipping
intBaseRate = 5
#Tax is 9 cents per dollar
fltTax = 0.09*fltPriceSub
fltPriceSubTotal = fltPriceSub+fltPriceSub+fltPriceSub
intShippingTotal = intShipping+intShipping+intShipping+intBaseRate
fltTaxTotal = fltTax+fltTax+fltTax
#Order total is the subtotal+shipping+tax added together
fltOrderTotal = fltPriceSubTotal+intShippingTotal+fltTaxTotal
print("You have purchased ", strDescription, "")
print("Your subtotal is ", fltPriceSubTotal, "")
print("Shipping and handling is ", intShippingTotal, "")
print("The tax is ", fltTaxTotal, "")
print("The order total is ",fltOrderTotal, "")
main()
If anyone could steer me in the right direction I would really appreciate it.

Categories

Resources