π 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:
-
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.
-
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'
. -
Process additional key-value pairs:
A
for
loop iterates through theuser_info
dictionary. Each key-value pair is added to theprofile
dictionary, allowing the function to dynamically include additional information about the user. -
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.
-
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:
- ➤ Exercise 8-1 | Message
- ➤ Exercise 8-2 | Favorite Book
- ➤ Exercise 8-3 | T-Shirt
- ➤ Exercise 8-4 | Large Shirts
- ➤ Exercise 8-5 | Cities
- ➤ Exercise 8-6 | City Names
- ➤ Exercise 8-7 | Album
- ➤ Exercise 8-8 | User Albums
- ➤ Exercise 8-9 | Magicians
- ➤ Exercise 8-10 | Great Magicians
- ➤ Exercise 8-11 | Unchanged Magicians
- ➤ Exercise 8-12 | Sandwiches
- ➤ Exercise 8-13 | User Profile
- ➤ Exercise 8-14 | Cars
- ➤ Exercise 8-15 | Printing Models
- ➤ Exercise 8-16 | Imports
- ➤ Exercise 8-17 | Styling Functions
πTrending Topics
π Connect With Us:
“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
Post a Comment