Section 2. Chapter 4
single
Challenge: Optional Arguments
Swipe to show menu
Task
Swipe to start coding
You are working with a simple user management system. Your goal is to implement a function add_user() that adds new users or updates existing ones in a global list called users_db.
The users_db is a list of dictionaries. Each dictionary represents a user and looks like this:
users_db = [
{"name": "Alice", "age": 28, "role": "admin", "status": "active"}
]
- Define a function
add_user(name, age, role="user", status="active"). - Check for existing users: Loop through the dictionaries in
users_db. Check if the"name"key in any dictionary matches thenameargument passed to your function. - If the user exists: * Update their existing dictionary with the new
age,role, andstatus.- Return the string:
"User {name} updated successfully!".
- Return the string:
- If the user doesn’t exist (the loop finishes without finding a match):
- Create a new dictionary representing the user with the provided
name,age,role, andstatus. - Append this new dictionary to
users_db. - Return the string:
"User {name} added successfully!".
- Create a new dictionary representing the user with the provided
Solution
Everything was clear?
Thanks for your feedback!
Section 2. Chapter 4
single
Ask AI
Ask AI
Ask anything or try one of the suggested questions to begin our chat