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.
- Define the
add_user
function with parametersname
,age
,role
(default is "user"), andstatus
(default is "active"). - Check if a user with the same
name
exists in theusers_db
list. - If the user exists, update their
age
,role
, andstatus
with the values received as arguments in theadd_user
function. - Return the string
"User {name} updated successfully!"
after updating the user. - If the user doesn't exist, create a new user (
new_user
) with the provided details(name
,age
,role
,status
). - Add the new user (
new_user
) to listusers_db
. - Return the string
"User {name} added successfully!"
after adding the new user.
Løsning
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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?
Takk for tilbakemeldingene dine!
Seksjon 2. Kapittel 4
99
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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
Spør om hva du vil, eller prøv ett av de foreslåtte spørsmålene for å starte chatten vår