Section 2. Chapter 4
single
Challenge: Optional Arguments
Swipe to show menu
Recall that when defining a function, you can make some arguments optional by assigning them a default value. If the caller does not provide a value, the function uses the default.
def add_user(name, age, role='user', status='active'):
# Function body here
nameandageare required – must always be provided;roleandstatusare optional – if omitted, their default values are used.
Remember that optional arguments must always come after all required arguments.
add_user('Alice', 28) # role='user', status='active' by default
add_user('Bob', 25, role='admin', status='inactive') # Overriding the defaults
12345678def greet(name, greeting='Hello'): print(f'{greeting}, {name}!') # Using only the required argument greet('Alice') # Providing both arguments greet('Bob', greeting='Hi')
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