Exercise 8-12 Solution Python Crash Course Chapter 8 : Functions

 

πŸ“˜ Python Crash Course – Chapter 8: Functions – Exercise 8-12 Solution

Welcome to another solution from Python Crash Course by Eric Matthes.


πŸ“ Exercise 8-12

Task:
Write a function that accepts a list of items a person wants on a sandwich . The function should have one parameter that collects as many items as the function call provides, and it should print a summary of the sand wich that is being ordered .
Call the function three times, using a different num ber of arguments each time

✅ Solution Code:


def make_sandwich(*items):
    print("Making a sandwich with the following items:")
    for item in items:
        print(f"- {item}")
    print("Your sandwich is ready!\n")
    print("---------------------------------------")

# Call the function three times with different number of arguments
make_sandwich("lettuce", "tomato", "cheese")
make_sandwich("ham", "turkey")
make_sandwich("peppers", "onions", "mayo", "mustard")

🧠 Code Explanation:

  1. Define the function with variable arguments:

    The function make_sandwich(*items) is defined with a parameter *items. The asterisk (*) allows the function to accept an arbitrary number of arguments, which are stored as a tuple.

  2. Iterate through the items:

    Inside the function, a for loop iterates through the items tuple. Each item represents an ingredient for the sandwich, and the loop processes all the provided arguments.

  3. Display the sandwich summary:

    The function displays a summary of the sandwich being made, listing all the ingredients provided in the function call. A separator line is printed after each sandwich for clarity.

  4. Call the function with different arguments:

    The function is called three times with varying numbers of arguments:

    • make_sandwich("lettuce", "tomato", "cheese"): Creates a sandwich with three ingredients.
    • make_sandwich("ham", "turkey"): Creates a sandwich with two ingredients.
    • make_sandwich("peppers", "onions", "mayo", "mustard"): Creates a sandwich with four ingredients.

πŸ” Output:


Making a sandwich with the following items:
- lettuce
- tomato
- cheese
Your sandwich is ready!

---------------------------------------
Making a sandwich with the following items:
- ham
- turkey
Your sandwich is ready!

---------------------------------------
Making a sandwich with the following items:
- peppers
- onions
- mayo
- mustard
Your sandwich is ready!

---------------------------------------

πŸ“š Related Exercises from Chapter 8:


“In the world of code, Python is the language of simplicity, where logic meets creativity, and every line brings us closer to our goals.”— Only Python

πŸ“Œ Follow Us And Stay Updated For Daily Updates

Comments