easy +10 pts

Safe Integer from String

Parse a string to an integer safely, returning a default on failure and respecting optional base.

Write a function `safe_int(s: str, default: int = 0, base: int = 10) -> int` that attempts to convert the string `s` to an integer using the given `base` (default 10). If the conversion fails for any reason (e.g., `ValueError`, `TypeError`, empty string, invalid characters), return `default`. The function should never raise an exception. Note: Only the value of `s` matters for conversion; `default` and `base` are not subject to parsing errors. However, if `base` is out of the valid range for `int()`, that should also result in returning `default`. Examples: - `safe_int('123')` → `123` - `safe_int('abc')` → `0` - `safe_int('1010', base=2)` → `10` - `safe_int('', default=42)` → `42`

Constraints

- `s` may be a string or an object of any type. If it is not a string, the function should return `default`. - `default` is an integer. - `base` is an integer between 2 and 36 (inclusive) as per `int()`'s specification; any other value causes the conversion to fail. - The function must not raise exceptions.

Example

```python
>>> safe_int('123')
123
>>> safe_int('abc')
0
>>> safe_int('1010', base=2)
10
>>> safe_int('', default=42)
42
```
10 points ~15 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a try/except block around the `int()` call.
Catch `ValueError` and `TypeError` specifically, or use a bare `except` but that is less clean.
Check that `base` is within the valid range 2–36, or let the exception be caught.
Remember that `int()` accepts a string and a base, but the string must be a valid integer literal for that base.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.