Editor

Build a Safe Defaults Function

Intermediate · Write the code · from 15 Python Pitfalls That Trip Up Even Experienced Developers

From the lesson: 15 Python Pitfalls That Trip Up Even Experienced Developers

Python is famous for being readable and beginner-friendly. But lurking beneath that clean syntax are several traps that catch even experienced developers. These aren't bugs in Python - they're features that behave differently than you'd expect.

Read the lesson

Write a function build_profile(name, hobbies=None, scores=None) that:

  • Creates a new list for hobbies if None, otherwise uses the given list
  • Creates a new dict for scores if None, otherwise uses the given dict
  • Returns a dictionary: {'name': name, 'hobbies': hobbies, 'scores': scores}
  • Create two profiles independently:

    1. p1 = build_profile('Alice') then add 'reading' to p1['hobbies']

    2. p2 = build_profile('Bob') then add 'gaming' to p2['hobbies']

    Print p1['hobbies'] and p2['hobbies'] to show they're independent.

    # Write build_profile with safe defaults
    # Create two profiles, add hobbies, print them

    More Common Pitfalls exercises

    All Python exercises · 50 practice problems · Advanced Python quiz