Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Learn Challenge: Optional Arguments | Positional and Optional Arguments
Python Functions Tutorial
Section 2. Chapter 4
single

single

bookChallenge: 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"}
]
  1. Define a function add_user(name, age, role="user", status="active").
  2. Check for existing users: Loop through the dictionaries in users_db. Check if the "name" key in any dictionary matches the name argument passed to your function.
  3. If the user exists: * Update their existing dictionary with the new age, role, and status.
    • Return the string: "User {name} updated successfully!".
  4. 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, and status.
    • Append this new dictionary to users_db.
    • Return the string: "User {name} added successfully!".

Solution

Switch to desktopSwitch to desktop for real-world practiceContinue from where you are using one of the options below
Everything was clear?

How can we improve it?

Thanks for your feedback!

Section 2. Chapter 4
single

single

Ask AI

expand

Ask AI

ChatGPT

Ask anything or try one of the suggested questions to begin our chat

some-alt