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

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
  • name and age are required – must always be provided;
  • role and status are 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
12345678
def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") # Using only the required argument greet("Alice") # Providing both arguments greet("Bob", greeting="Hi")
copy
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