Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Challenge: Optional Arguments | Positional and Optional Arguments
Python Functions Tutorial

book
Challenge: Optional Arguments

Oppgave

Swipe to start coding

Implementing a function add_user to manage users in a database. If the user exists in users_db, their fields should be updated instead of creating a new entry. If the user is not found, a new user should be added with the provided details.

  1. Define the add_user function with parameters name, age, role (default is "user"), and status (default is "active").
  2. Check if a user with the same name exists in the users_db list.
  3. If the user exists, update their age, role, and status with the values received as arguments in the add_user function.
  4. Return the string "User {name} updated successfully!" after updating the user.
  5. If the user doesn't exist, create a new user (new_user) with the provided details(name, age, role, status).
  6. Add the new user (new_user) to list users_db.
  7. Return the string "User {name} added successfully!" after adding the new user.

Løsning

users_db = []

def add_user(name, age, role="user", status="active"):
# Check if the user already exists
for user in users_db:
if user["name"] == name:
# Update the user if they already exist
user["age"] = age
user["role"] = role
user["status"] = status
return f"User {name} updated successfully!"
# Add a new user if they don't exist
new_user = {
"name": name,
"age": age,
"role": role,
"status": status
}
users_db.append(new_user)
return f"User {name} added successfully!"

# Testing the result
print(add_user("Alice", 30))
print(add_user("Bob", 25, role="admin"))
print(add_user("Alice", 31, status="inactive"))

# Check the list of users
print(users_db)
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 4
users_db = []

def add_user(___):
# Check if the user already exists
for user in users_db:
if ___:
# Update the user if they already exist
user[___] = ___
user[___] = ___
user[___] = ___
return f"User {name} updated successfully!"
# Add a new user if they don't exist
new_user = {
"name": ___,
"age": ___,
"role": ___,
"status": ___
}
users_db.___(___)
return f"User {name} added successfully!"

# Testing the result
print(add_user("Alice", 30))
print(add_user("Bob", 25, role="admin"))
print(add_user("Alice", 31, status="inactive"))

# Check the list of users
print(users_db)

Spør AI

expand
ChatGPT

Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår

some-alt