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

 

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

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


πŸ“ Exercise 8-14

Task:
Write a function that stores information about a car in a diction ary . The function should always receive a manufacturer and a model name .
It should then accept an arbitrary number of keyword arguments .
Call the func tion with the required information and two other name-value pairs, such as a color or an optional feature .
Your function should work for a call like this one:
car = make_car('subaru', 'outback', color='blue', tow_package=True)
Print the dictionary that’s returned to make sure all the information was stored correctly

✅ Solution Code:


ef make_car(manufacturer, model, **additional_info):
    car_info = {}
    car_info['manufactured by'] =manufacturer
    car_info['model no'] = model

    for name , value  in additional_info.items():
        car_info[name] = value  
    return car_info      
    
# Call the function with the required information and two other name-value pairs
car = make_car('subaru', 'outback', color='blue', tow_package=True)
print(car)

🧠 Code Explanation:

  1. Define the function with flexible arguments:

    The function make_car(manufacturer, model, **additional_info) is defined with three parameters:

    • manufacturer: Represents the car's manufacturer.
    • model: Represents the car's model name.
    • **additional_info: Allows the function to accept an arbitrary number of keyword arguments, which are stored as a dictionary.
  2. Create a dictionary:

    Inside the function, an empty dictionary named car_info is created to store the car's information. The manufacturer and model are added to the dictionary with keys 'manufactured by' and 'model no'.

  3. Process additional key-value pairs:

    A for loop iterates through the additional_info dictionary. Each key-value pair is added to the car_info dictionary, allowing the function to dynamically include additional details about the car.

  4. Call the function with car details:

    The function is called with the required manufacturer and model, along with additional keyword arguments:

    • make_car('subaru', 'outback', color='blue', tow_package=True): Creates a dictionary for a Subaru Outback with additional details such as color and tow package availability.
  5. Display the car information:

    The resulting dictionary, which contains all the car's details, is displayed to confirm that the information has been stored correctly.

πŸ” Output:


{'manufactured by': 'subaru', 'model no': 'outback', 'color': 'blue', 'tow_package': True}

πŸ“š 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