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()
Related
class Toptanci:
def __init__(self):
self.fruits = dict(apple=30, pear=40, cherry=20, banana=10, strawberry=15)
self.vegetables = dict(garlic=40, Tomatoes=30, Eggplant=40, Onion=25, Potato=15)
self.all_list = self.fruits and self.vegetables ## YANLIS OLABILIR !
def report(self): ### RAPOR
print(self.fruits and self.vegetables)
def is_resource_sufficient(self, purchase): ### YETERLI VAR MI DIYE BAK
can_purchase = True
for item in purchase.all_list:
if purchase.all_list[item] > self.all_list[item]:
print(f"Sorry there is not enough {item}")
can_purchase = False
return can_purchase
def order_purchase(self, order): ### GEREKLI AMOUNUT"U CIKAR
for item in order.all_list:
self.all_list[item] -= order.all_list[item]
print(f"Here is your {order}")
def main(self):
question1 = input("Fruits or Vegetables?").lower()
question2 = int(input("Please enter the KG amount you want ="))
question3 = input("Would you like something else? 'y' or 'n'").lower()
if question1 == 'fruits':
print(question2)
Basically, I am trying to get input from the user and deduct the amount from the base values. In addition, I want to add the amount I get from the Toptanci class into the Manav class. So when in Manav section the amount gathered will be added. In the Manav Class we should have the amount of vegetable or fruits bought and it should display the bought amount. So when another user tries to buy from Manav. It will see Manav's stock and the stock will be reduced accordingly.
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.
I'm trying to write code that will collect the number of individuals attending an event. Based on the number of people entered, I will ask that many times a) the name of the individual, b) the number of toys they have donated. I want the information to be entered into a dictionary which i will pass to another function. The second function will select individuals who have donated more than 20 toys and print their name and the number of toys the donated as "level 1" and then everyone else as "level 2".
I've checked to make sure that the data is being passed from one function to another correctly. I'm having issues printing the donation amount without the []. Also, it keeps printing the level above each entry instead of listing the entries underneath the level. In other words, I'm trying to get:
Level 1
Selena Gomez 50
Beyonce 40
Level 2
Will Smith 5
What am I doing wrong?
Here is my code:
def data():
people = int(input("How many individuals are attending? "))
attendees = {}
for i in range(people):
name = str(input('Please enter name: '))
amount = int(input('Number of toys donated:'))
attendees[name]= [amount]
return attendees
def print_data():
attendees = data()
for i in attendees:
if attendees[i][0] > 20:
print('Level 1')
print(i, attendees[i])
else:
print('Level 2')
print(i, attendees[i])
print_data()
And here is my output:
How many individuals are attending? 3
Please enter name: Will Smith
Number of toys donated:5
Please enter name: Selena Gomez
Number of toys donated:50
Please enter name: Beyonce
Number of toys donated:40
Level 2
Will Smith [5]
Level 1
Selena Gomez [50]
Level 1
Beyonce [40]
you did two mistakes, you were taking input as list as value of each dictionary element and you have to run two different loops to find the all the values greater than 20 and another one to print all the values less than 20
def data():
people = int(input("How many individuals are attending? "))
attendees1 = {}
attendees2 = {}
for i in range(people):
name = str(input('Please enter name: '))
amount = int(input('Number of toys donated:'))
#amount should be just a variable not list
if amount > 20:
attendees1[name]= amount
else:
attendees2[name] = amount
return attendees1, attendees2
def print_data():
attendees1, attendees2 = data()
if len(attendees1) > 0:
print('Level 1')
for i in attendees1:
print(i, attendees1[i])
if len(attendees2) > 0:
print('Level 2')
for i in attendees2:
print(i, attendees2[i])
print_data()
These two lines should be edited:
attendees[name]= [amount]
#into
attendees[name]= amount
#and
if attendees[i][0] > 20:
#into
if attendees[i] > 20:
Does something like this work for you?
def data():
people = int(input("How many individuals are attending? "))
attendees = {}
for i in range(people):
name = str(input('Please enter name: '))
amount = int(input('Number of toys donated:'))
attendees[name]= amount
return attendees
def print_data(attendees):
level_one = []
level_two = []
for name, count in attendees.items():
if count >= 20:
level_one.append((name, count))
else:
level_two.append((name, count))
print('Level 1')
for name, count in level_one:
print(name, count)
print('\nlevel 2')
for name, count in level_two:
print(name, count)
attendees = data()
print_data(attendees)
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.
My name is Jamie, I'm a Yr 12 student currently living in NZ. At school, in our computer science class we were tasked with creating a program for house points. A house is sort of like the Houses in Harry Potter, each student is assigned to one. These houses then compete in events and earn points, at the end of the year the house with the most points wins the trophy.
Now we have only been taught about 2-D arrays and parallel lists, as these need to be incorporated plus it must be modular.
The program must be fully user inputed as requirements for excellence (equivalent of A) must be user inputed.
The program must also have these inputs and outputs:
Inputs: House Names, House Events, and Points earned in events for the house
Cancel house name and house event entry when XXX is entered.
Outputs: Winner of each event, house with best average, house with most wins, and overall winner.
I am currently trying to figure out how to do the points to go with house and events.
Appreciate all help,
Jamie :)
EDIT: Posted Code
def number_house():
global numhouse
print("Welcome!")
print()
Flag = True#loop
while Flag:
try:
numhouse = int(input("Please enter the number of events there is: "))
print()
if numhouse < 1 or numhouse > 100:
print("WOW, thats a lot of events, please be reasonable. Thanks.")
else:
Flag = False
except ValueError:
print("Enter only a number, Thanks.")
def event_names():
global event
print("Enter XXX when finished entering event names")
Flag = True
for e in range(numhouse):
e = input("Event name: ")
if e == 'XXX' or e == 'xxx':
Flag = False
else:
event.append(e)
print()
def getData():
global data
global inputlist
global event
lower_bound = 0
upper_bound = 100
k=0
n=str(input("Please enter house names <<<Enter XXX when finished>>> :"))
while n != 'XXX' :
if n == 'XXX' or n == 'xxx':
exit
data = [n]
print()
print ("Please enter the event points in ascending order. ",event,"Thanks")
for k in range(len(event)):
s = getScore(n,lower_bound,upper_bound)
data=data+[s]
inputlist = inputlist + [data]
n=str(input("Please enter house names <<<Enter XXX when finished>>> :"))
def getScore(name,min,max):
global event
sc= -1
while sc < min or sc > max :
try :
sc = int(input("Please enter score for "+ name + " :"))
except ValueError :
print("Invalid Input please enter an interger. Thanks")
return sc
score =[]
getscore = []
data = []
inputlist = []
event = []
number_house()
event_names()
getData()
print()
print(inputlist)
LOWER_BOUND = 0
UPPER_BOUND = 100 # both in caps because this is a constant
def get_score(house_name, event_name):
# an extra argument so you can tell which event is being scored.
# removed the min, max cause we are using the constants!
score = -1
while score < LOWER_BOUND or score > UPPER_BOUND:
try:
score = int(input("Please enter score for %s in the event %s:" % (house_name, event_name)))
if score < LOWER_BOUND :
print ("Score is too low, minimum score is %i.\nPlease try again." % min_score)
if score > UPPER_BOUND:
print ("Score is too high, maximum score is %i\nPlease try again." % max_score)
except ValueError:
print("Invalid Input please enter an integer. Thanks")
return score # note the use of return to avoid using global
def get_number_of_events():
print("Please enter the number of events there is.")
while True:
try:
n_events = int(input(">>"))
except ValueError:
print("Enter only a number, Thanks.")
if n_events > 100:
print("WOW, that's a lot of events, please be reasonable. Thanks.")
elif n_events < 1:
# this is a different condition that would get a wrong error in your program,
# note the use of 'elif', in Python this an 'else if'.
print ("That's too few events! Try Again.")
else:
# no need to use Flag, just use break when you want to leave a loop.
break
return n_events
def get_events_names(n_events):
print ("Please enter the events names")
events = []
for n in range(1, n_events + 1):
# starting at 1 to give a better display
event_name = input("Event %i name: " % n)
events.append(event_name)
return events
def get_data(events):
data = []
while True:
house_name = input("Please enter house names <<<Enter XXX when finished>>> :")
if house_name.upper() == "XXX":
# using .upper() to avoid checking twice for either 'xxx' or 'XXX'.
# I would ask the user for how many houses are there instead, but your choice ;)
break
print ("Please enter the events points in ascending order.")
# not actually need to be in ascending order, you can sort them later if you want.
scores = []
for event_name in events:
# don't use range(len(something)), loops in Python are easy!
score = get_score(house_name, event_name)
scores.append([event_name, score])
data.append([house_name, scores])
# use .append() instead of data = data + [...]
return data
def main():
print("Welcome!\n")
n_events = get_number_of_events()
events_names = get_events_names(n_events)
print()
data = get_data(events_names)
print()
for house_name, event_data in data:
print ("House " + house_name)
for event_name, score in event_data:
# note the use of tuple unpacking
print ("\tEvent: %s Score: %i" % (event_name, score))
if __name__ == '__main__':
main()
This time maintaining the same structure as your program.
Check comments for some tips and tricks.
Also, try to keep your variable names with meaning and check the PEP 8 guidelines for naming conventions (variables and functions should be snake_case,
Output:
Welcome!
Please enter the number of events there is.
>>2
Please enter the events names
Event 1 name: Quidditch Match
Event 2 name: Duels
Please enter house names <<<Enter XXX when finished>>> :Gryffindor
Please enter the events points in ascending order.
Please enter score for Gryffindor in the event Quidditch Match:100
Please enter score for Gryffindor in the event Duels:30
Please enter house names <<<Enter XXX when finished>>> :Slytherin
Please enter the events points in ascending order.
Please enter score for Slytherin in the event Quidditch Match:40
Please enter score for Slytherin in the event Duels:50
Please enter house names <<<Enter XXX when finished>>> :XXX
House Gryffindor
Event: Quidditch Match Score: 100
Event: Duels Score: 30
House Slytherin
Event: Quidditch Match Score: 40
Event: Duels Score: 50
I'll try to give you a different approach, see if that helps you.
def main():
events = []
houses = []
scores = {} # key = House name, value = scores
print "Welcome!\n"
# create the houses
print "Please enter how many houses there is:"
n_houses = int(raw_input(">>"))
print "Please enter houses names:"
for n in range(n_houses):
print "House", n+1
house_name = raw_input(">>")
houses.append(house_name)
# create the events
print "Please enter the number of events there is"
n_events = int(raw_input(">>"))
print "Please enter the event names"
for n in range(n_events):
print "Event", n+1
event_name = raw_input(">>")
events.append(event_name)
# get the scores for each house for each event
for event in events:
for house in houses:
print "Please enter the score for House %s in the event %s"%(house, event)
score = int(raw_input(">>"))
# initialize the score with a empty list
if house not in scores:
scores[house] = []
# add the score list
scores[house].append(score)
print "\nThe result is:"
# process the result
for house, score in sorted(scores.items(),
key=lambda x: sum(x[1]),
reverse=True):
print "House %s. Total Score: %i"%(house, sum(score))
if __name__ == "__main__":
main()
First thing you should notice is that I'm not using global, using global is usually frowned upon, it can lead to undesired interactions on data.
Also, instead of asking for inputs like "XXX" to break the loop, I asked the user for the number of inputs he wants to deal before, so I can loop over this number and process each separately.
I do the same thing with the house, I ask for how many houses are there, and then their names.
Next I do a nested for loop with the event names and house names. The order matters, we deal with each event first. You can change it to deal with each house first.
And finally I process the scores. the line for house, score in sorted(scores.items(), key=lambda x: sum(x[1]), reverse=True): is a bit clogged and advanced but it means this: I want to loop over a sorted list of items, giving me two items at a time, the items are named house and score, they will be sorted by the function sum(x[1]), and I want this in the reversed order (or else the last would show in first).
key=lambda x: sum(x[1]) is a bit of a hack, it could be done better. lambda means a function, it takes x as input, x in this case is a tuple of house, score, so I want the score, so I access it using x[1], and since I want the sum I use sum(x[1]).
Usage:
Welcome!
Please enter how many houses there is:
>>2
Please enter houses names:
House 1
>>Gryffindor
House 2
>>Slytherin
Please enter the number of events there is
>>2
Please enter the event names
Event 1
>>Quidditch Match
Event 2
>>Duels
Please enter the score for House Gryffindor in the event Quidditch Match
>>100
Please enter the score for House Slytherin in the event Quidditch Match
>>90
Please enter the score for House Gryffindor in the event Duels
>>250
Please enter the score for House Slytherin in the event Duels
>>240
The result is:
House Gryffindor. Total Score: 350
House Slytherin. Total Score: 330
Notice that this was made on Python 2.7, to port to Python 3 just change raw_input to input and print to print()