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

 

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

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


πŸ“ Exercise 8-13

Task:
Build a profile of yourself by calling build_profile(), using your first and last names and three other key-value pairs that describe you

✅ Solution Code:


def build_profile(first, last, **user_info):
    """Build a dictionary containing everything we know about a user."""
    profile = {}
    profile['first_name'] = first
    profile['last_name'] = last
    for key, value in user_info.items():
        profile[key] = value
    print(profile)  
# Build a profile of yourself
user_profile = build_profile('John', 'Doe', location='New York', age=30, occupation='Engineer')

🧠 Code Explanation:

  1. Define the function with flexible arguments:

    The function build_profile(first, last, **user_info) is defined with three parameters:

    • first: Represents the user's first name.
    • last: Represents the user's last name.
    • **user_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 profile is created to store the user's information. The first and last names are added to the dictionary with keys 'first_name' and 'last_name'.

  3. Process additional key-value pairs:

    A for loop iterates through the user_info dictionary. Each key-value pair is added to the profile dictionary, allowing the function to dynamically include additional information about the user.

  4. Call the function to build a profile:

    The function is called with the user's first and last names, along with additional keyword arguments:

    • build_profile('John', 'Doe', location='New York', age=30, occupation='Engineer'): Builds a profile for a user named John Doe, including their location, age, and occupation.
  5. Display the profile:

    The resulting dictionary, which contains all the user's information, is displayed to confirm that the profile has been built correctly.

πŸ” Output:


{'first_name': 'John', 'last_name': 'Doe', 'location': 'New York', 'age': 30, 'occupation': 'Engineer'}

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