FAQ: Function Arguments: *args and **kwargs - Review

This community-built FAQ covers the “Review” exercise from the lesson “Function Arguments: *args and **kwargs”.
Paths and Courses
This exercise can be found in the following Codecademy content:
Learn Intermediate Python 3

FAQs on the exercise Review

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

Hello! I’ve completed the Review exercise, my version doesn’t return errors, but probably it’s bad written and there must be a lot of places to be improved. Could you please share in this thread (or attach to the exercise a good example of solution?)

tables = { 1: { 'name': 'Jiho', 'vip_status': False, 'order': { 'drinks': 'Orange Juice, Apple Juice', 'food_items': 'Pancakes', 'total': [534.50, 20.0, 5] } }, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {}, } def assign_table(table_number, name, vip_status=False): if tables[table_number].get('queue'): tables[table_number]['name'] = tables[table_number]['queue']['name'] tables[table_number]['vip_status'] = tables[table_number]['queue']['vip_status'] tables[table_number]['order'] = {} # tables[table_number]['queue'].pop(0) keep_queue(table_number, name, vip_status) else: tables[table_number]['name'] = name tables[table_number]['vip_status'] = vip_status tables[table_number]['order'] = {} def keep_queue(table_number, name, vip_status=False): tables[table_number]['queue'] = {} tables[table_number]['queue'].update({'name': name, 'vip_status': vip_status}) print(tables) def assign_food_items(table_number, **order_items): food = order_items.get('food') drinks = order_items.get('drinks') tables[table_number]['order']['food_items'] = food tables[table_number]['order']['drinks'] = drinks def calculate_price_per_person(table_number, tip, split): total = 0 table_total = tables[table_number]['total'] for item in table_total: total += item total_tip = total * (tip/100) split_price = (total + total_tip) / split print("Price per person: ", split_price) return split_price def leave_table(table_number, name): if tables[table_number]['name'] == name: tables[table_number] = {} print("Guest from table ", {table_number}, "has left!") def add_food_items(table_number, **order_items): if not (order_items.get('food') == None): if not tables[table_number]['order']['food_items']: tables[table_number]['order']['food_items'] = order_items.get('food') else: tables[table_number]['order']['food_items'] += ', ' + order_items.get('food') if not (order_items.get('drinks') == None): if not tables[table_number]['order']['drinks']: tables[table_number]['order']['drinks'] = order_items.get('drinks') else: tables[table_number]['order']['drinks'] += ', ' + order_items.get('drinks') def remove_food_items(table_number, **item): ordered = tables[table_number]['order']['food_items'].lower() ordered_drinks = tables[table_number]['order']['drinks'].lower() if item.get('food'): if item['food'].lower() in ordered: revised = ordered.split(', ') revised.remove(item['food'].lower()) ordered = '' for i in revised: if i == revised[-1]: ordered += i else: ordered += i + ', ' tables[table_number]['order']['food_items'] = ordered else: print("No such item in order!") elif item.get('drinks'): if item['drinks'].lower() in ordered_drinks: revised = ordered_drinks.split(', ') revised.remove(item['drinks'].lower()) ordered_drinks = '' for i in revised: if i == revised[-1]: ordered_drinks += i else: ordered_drinks += i + ', ' tables[table_number]['order']['drinks'] = ordered_drinks else: print("No such item in order!") else: print("No such item in order!") keep_queue(2, "Peter", vip_status=False) keep_queue(2, "Maria", vip_status=False) assign_table(2, "Ann", vip_status=True) assign_food_items(2, food='Pasta, Ice-cream') add_food_items(2, drinks='Coffee', food='Salad') add_food_items(2, drinks='Tea') tables[2]['total'] = [430.0] tables[2]['total'].append(55.0) remove_food_items(2, drinks='Coffee') calculate_price_per_person(2, 10, 2) leave_table(2, "Ann")
1 Like

Hi! I’m pretty new, too. I struggled most with writing the function to remove an item from the order. Your solution was actually super helpful! I did notice a way to improve it though…when you get around to turning your list back into a string to update the dictionary, I think it would be simpler to use ', '.join(list).

def remove_item(table_number, **item): food_order = tables[table_number]['order']['food_items'].lower() drinks_order = tables[table_number]['order']['drinks'].lower() if item.get('food'): if item.get('food').lower() in food_order: revised = food_order.split(',') revised.remove(item.get('food').lower()) new_food_order = ', '.join(revised) tables[table_number]['order']['food_items'] = new_food_order else: print("Item was not ordered.") if item.get('drinks'): if item.get('drinks').lower() in drinks_order: revised = drinks_order.split(',') revised.remove(item.get('drinks').lower()) new_drinks_order = ', '.join(revised) tables[table_number]['order']['drinks'] = new_drinks_order else: print("Item was not ordered.")

Thank you!! With ', '.join(list) this part of the code got shorter and cleaner :grinning:

I added more methods to the exercise and structured it as object. I wanted to push further and use more concepts I learnt the last months.
Any feedback, critics to improve is warmly welcome!

class Reservation:
    tables   = {"table: 1": {}, "table: 2": {}, "table: 3": {}, "table: 4": {}, "table: 5": {}, "table: 6": {}, "table: 7": {}}
    vips     = ["Bob Squat", "Roger Belly", "Frank Slim"]
    schedule = ["17h","18h","19h","20h","21h"]
    prices = {"burger": 10.0, "pancake": 15.0, "fries": 7, "fish": 12, "coke": 3.0, "water": 5.0}

    def __init__(self, name, table_number, resa_time, vip_status= False):

        for key in Reservation.tables["table: "+str(table_number)].keys():
            if key == str(resa_time)+"h":
                print("This schedule is not available, here are available: "+str(Reservation.schedule))

        self.resa_time    = resa_time
        self.name         = name
        self.table_number = table_number
        self.status       = (False, True)[self.name in Reservation.vips]
        self.food_items   = None
        self.drinks       = None

        Reservation.tables["table: "+str(self.table_number)][str(self.resa_time)+"h"]               = {}
        Reservation.tables["table: "+str(self.table_number)][str(self.resa_time)+"h"]["name"]       = self.name
        Reservation.tables["table: "+str(self.table_number)][str(self.resa_time)+"h"]["vip_status"] = self.status
        Reservation.tables["table: "+str(self.table_number)][str(self.resa_time)+"h"]["order"]      = {}

    def assign_food_items(self, **items_ordered):
        if items_ordered.get("food"):
            self.food_items                         = items_ordered.get("food")
        if items_ordered.get("drinks"):
            self.drinks                             = items_ordered.get("drinks")

        Reservation.tables["table: "+str(self.table_number)][str(self.resa_time)+"h"]["order"]["drinks"]     = self.drinks
        Reservation.tables["table: "+str(self.table_number)][str(self.resa_time)+"h"]["order"]["food_items"] = self.food_items

    def calculate_price_per_person(self, tip, split):
        self.total            = 0
        self.total            = [Reservation.prices.get(item) for item in (self.food_items.replace(" ", "")).split(",")]
        self.total           += [Reservation.prices.get(item) for item in (self.drinks.replace(" ", "")).split(",")]
        self.price_per_person = (sum(self.total) + tip) /split
        print("Total price without tip: " + str(sum(self.total)) + "\n" + "Price per person: " + str(self.price_per_person) + "$")

    def remove_reservation(self):
        Reservation.tables["table: "+str(self.table_number)][str(self.resa_time)+"h"] = {}
        print("Table number " + str(self.table_number) + " removed")

    def order_update(self, **items):

    def __str__(self):
        return "Name: "+ str(self.name) +"\nVip: "+ str(self.status) +"\nTable number: "+ str(self.table_number)\
        +"\nReservation time: "+ str(self.resa_time)+"h"\
        +"\nFood: "+ str(self.food_items)+"\n" + "Drinks: "+ str(self.drinks)

#object reservation creation
reservation_01 = Reservation("Bob Squat", 1, 19)
reservation_02 = Reservation("Frank Slim", 5, 19)
reservation_03 = Reservation("Joe Do", 1, 20)
reservation_04 = Reservation("Mr jeans", 1, 19)
reservation_05 = Reservation("Coco nut", 1, 20)

#food assignement
reservation_01.assign_food_items(food= "fish, fries", drinks= "water")
reservation_02.assign_food_items(food= "burger, pancake", drinks= "coke")
reservation_03.assign_food_items(food= "pancake, fries", drinks= "water")
print("###############\n"+ str(reservation_01) + "\n###############")
print("###############\n"+ str(reservation_02) + "\n###############")
print("###############\n"+ str(reservation_03) + "\n###############")

#Update an order
reservation_01.order_update( drinks= "water", food= "burger, fries")
print("order after modification")
print("###############\n"+ str(reservation_01) + "\n###############")

bill_01 = [5, 1]

#removing a table's guest
print("###############\nBefore reservation is removed:\n", Reservation.tables)
print("after removing reservation:\n", Reservation.tables)

1 Like

Here is my code for the review. The only thing I did not do dealt with the price total.
Otherwise, I set it up to automatically transfer the next person in queue(if there is one) to assign them a table.
I used a lot of try/except to handle different possible errors.
Any comments or advice is welcome!

tables = { 1: { 'name': 'Jiho', 'vip_status': False, 'order': { 'drinks': 'Orange Juice, Apple Juice', 'food_items': 'Pancakes', 'total': [534.50, 20.0, 5] } }, 2: {}, 3: {}, 4: {}, 5: {}, 6: {}, 7: {}, } # Assign table with name, vip_status, order(food and drink details) # if table has a guest, pass information to table_queue() def assign_table(table_number, name, vip_status=False): if tables[table_number]: table_queue(table_number, name, vip_status) else: tables[table_number]['name'] = name tables[table_number]['vip_status'] = vip_status tables[table_number]['order'] = {} tables[table_number]['order']['food_items'] = '' tables[table_number]['order']['drinks'] = '' # Adds information to a queue for that table. # If table is empty, passes to assign_table. queue = {1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: []} def table_queue(table_number, name, vip_status=False): if tables[table_number]: print("Table currently taken. Added {} to queue for table {}.".format(name, table_number)) if not queue[table_number]: queue[table_number] = [{'name': name, 'vip_status': vip_status}] else: queue[table_number].append({'name': name, 'vip_status': vip_status}) else: assign_table(table_number, name, vip_status) def calculate_price_per_person(total, tip, split): total_tip = total * (tip/100) split_price = (total + total_tip) / split return split_price, total # Emptys table and checks to see if someone is in queue. # If someone in queue, passes their information to assign_table. def leave_table(table_number): try: guest = tables[table_number]['name'] print("{} has left. Table {} is now empty.".format(guest, table_number)) tables[table_number] = {} if queue[table_number]: name = queue[table_number][0]['name'] vip_status = queue[table_number][0]['vip_status'] assign_table(table_number, name, vip_status) print("Please seat {} at table {} now.".format(name, table_number)) queue[table_number].remove(queue[table_number][0]) except: print("Table {} is already empty.".format(table_number)) # Add food or drinks to tables order. def add_food_drinks(table_number, **order_items): if tables[table_number]: try: food = order_items.get('food') if tables[table_number]['order']['food_items']: tables[table_number]['order']['food_items'] += ', ' + food else: tables[table_number]['order']['food_items'] = food except: print("No food to add.") try: drinks = order_items.get('drinks') if tables[table_number]['order']['drinks']: tables[table_number]['order']['drinks'] += ', ' + drinks else: tables[table_number]['order']['drinks'] = drinks except: print("No drinks to add.") else: print("Table is empty.") #Removes food or drinks from tables order. def remove_food_drinks(table_number, **order_items): if tables[table_number]: try: food_ordered = tables[table_number]['order']['food_items'].split(', ') food_to_remove = order_items.get('food').split(', ') for food in food_to_remove: if food not in food_ordered: print("{}: Not in food list.".format(food)) else: food_ordered.remove(food) tables[table_number]['order']['food_items'] = ', '.join(food_ordered) except: print("No food needs to be removed.") try: drinks_ordered = tables[table_number]['order']['drinks'].split(', ') drinks_to_remove = order_items.get('drinks').split(', ') for drink in drinks_to_remove: if drink not in drinks_ordered: print("{}: Not in drinks list.".format(drink)) else: drinks_ordered.remove(drink) tables[table_number]['order']['drinks'] = ', '.join(drinks_ordered) except: print("No drinks need to be removed.") else: print("Table is empty.") ## Testing assign_table(2, 'Bob', True) add_food_drinks(2, food='Burger, Fries', drinks='Sweet Tea') add_food_drinks(2, drinks='Beer') assign_table(2, 'Sarah', True) leave_table(2)

I struggled with the remove order item task. The main problem I encoutered was the whitepace before the second item getting **kwargs values. I figured out this workaround to build a function that accept values in any given order. I’m pretty new and would aprreciate any feedback

def remove_order_items(table_number,**remove_items): food_lst = [] drinks_lst =[] #making drinks_lst if 'drinks' in remove_items.keys(): drinks = remove_items.get('drinks') drinks_lst.extend(drinks.split(',')) drinks_lst = [x.strip(' ')for x in drinks_lst] #making food_lst if 'food' in remove_items.keys(): food = remove_items.get('food') food_lst.extend(food.split(',')) food_lst = [x.strip(' ')for x in food_lst] #getting already ordered_list ordered_drinks = tables[table_number]['order']['drinks'].split(',') ordered_drinks = [x.strip(' ') for x in ordered_drinks] ordered_food = tables[table_number]['order']['food_items'].split(',') ordered_food = [x.strip(' ') for x in ordered_food] #getting corrected list corrected_list_drinks=[x for x in ordered_drinks if x not in drinks_lst] corrected_list_food=[x for x in ordered_food if x not in food_lst] #appending changed list in table tables[table_number]['order']['drinks']=','.join(corrected_list_drinks) tables[table_number]['order']['food_items']=','.join(corrected_list_food) #test function remove_order_items(1, drinks='Apple Juice, Water', food='Bananen, Pancakes' ) print(tables)