2
\$\begingroup\$

Is there any room for improvements in this code. I am new to programming (python3), learning and practicing functions related to arguments recently.

def make_pizza(*toppings, **pizza_info):

    """Creating a dictionary for pizza information"""
    pizza = {}

    pizza_toppings = [topping for topping in toppings]
    pizza['toppings'] = pizza_toppings

    for key, value in pizza_info.items():
        pizza[key] = value

    return pizza



def show_pizza(pizza):

    """Showing the order with the information provided by make_pizza() function."""

    print("You've ordered " + str(pizza['size']) + " inches size " + pizza[
        'crust'].title() + " crust pizza with the toppings of:")

    for topping in pizza['toppings']:
        print("-" + topping.title())

# Taking order in a form of dictionary structure 
order = make_pizza('cheese', 'mushroom', size=12, crust='thin')

# Show the order message 
show_pizza(order)
\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

You can use standard copy functions instead of manually copying:

from copy import copy

def make_pizza(*toppings, **pizza_info):
    pizza = pizza_info.copy()
    pizza['toppings'] = copy(toppings)    
    return pizza

And maybe use a dict-comprehension for merging information, instead of mutating the pizza:

def make_pizza(*toppings, **pizza_info):
    return {
        **pizza_info,
        'toppings': copy(toppings)    
    }

For printing, use f-strings for easier formatting:

print(f"You've ordered {pizza['size']} inches size {pizza[
    'crust'].title()} crust pizza with the toppings of:")
\$\endgroup\$
3
  • \$\begingroup\$ Thank you for your guidance. I gained a lot of insight from this. Gotta apply those practise real quick. :) \$\endgroup\$ May 3, 2021 at 7:06
  • 1
    \$\begingroup\$ Maybe I answered too fast. Please note that: - the copy function will give you the same type as the input you give it, so you will end up with a tuple for toppings, not a list (which might be as fine) - the copies here are actually not needed, as *args and **kwargs are already created anew when the function is called - the copies are only shallow. It makes no difference when the contents are only strings, as these are immutable, but if you had anything mutable it could cause trouble - but if you avoid mutating anything in your programs, this will not be a problem \$\endgroup\$
    – Gnurfos
    May 4, 2021 at 5:16
  • \$\begingroup\$ Thank you so much for giving me such efforts and being considerate about my codes. I will keep on working on your suggestions. Big thanks to you. :) \$\endgroup\$ May 6, 2021 at 10:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.