EasyPython

Early Return

PythonClean CodeReadabilityRefactoring

Deep nesting is hard to read. Replace nested if blocks with guard clauses that return early.

# dirty — 4 levels deep
def solve(user):
    if user:
        if user['is_active']:
            if user['age'] >= 18:
                if user['has_premium']:
                    return 'full-access'
                else:
                    return 'basic-access'
            else:
                return 'age-restricted'
        else:
            return 'inactive'
    else:
        return 'no-user'

Refactor using guard clauses so the happy path is at the end with minimal nesting.

Sample tests

Test #1None user
Input: [null]
Output: "no-user"
Test #2Inactive user
Input: [{"age":25,"is_active":false,"has_premium":true}]
Output: "inactive"
Test #3Under 18
Input: [{"age":16,"is_active":true,"has_premium":true}]
Output: "age-restricted"
Test #4Adult, no premium
Input: [{"age":18,"is_active":true,"has_premium":false}]
Output: "basic-access"
Test #5Full access
Input: [{"age":30,"is_active":true,"has_premium":true}]
Output: "full-access"