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

book
Challenge: Positional Arguments

Oppgave

Swipe to start coding

Implement the register_user function that checks the user's age, adds their details to a database (users_db), and returns a success or failure message.

  1. Define the function register_user that takes parameters username, email, and age.
  2. Inside the function register_user, check if age is less than 18. If it is, return the message "Registration failed: age must be 18 or older."
  3. Create a dictionary user with the keys username, email, and age, and assign the corresponding values.
  4. Add the user dictionary to the users_db list using the appropriate method.
  5. If everything is successful, return the message "User {username} registered successfully!", where {username} is the actual username.
  6. Call the register_user function with example parameters for a user, either by passing arguments directly or as a dictionary.

Løsning

users_db = []

def register_user(username, email, age):
if age < 18:
return "Registration failed: age must be 18 or older."
user = {"username": username, "email": email, "age": age}
users_db.append(user)
return f"User {username} registered successfully!"

# Pass the parameters in any way to register a user
result1 = register_user(username="Alice", email="alice@example.com", age=22)

# Testing the result
print(result1)
print(users_db) # List of registered users
Alt var klart?

Hvordan kan vi forbedre det?

Takk for tilbakemeldingene dine!

Seksjon 2. Kapittel 2
users_db = []

def register_user(___):
if ___:
___ "Registration failed: age must be 18 or older."
user = {"username": ___, "email": ___, "age": ___}
users_db.___(___)
___ f"User {username} registered successfully!"

# Pass the parameters in any way to register a user
result1 = register_user(___)

# Testing the result
print(result1)
print(users_db) # List of registered users

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