Skip to content
Exercise · Exceptions · lesson 10 of 11

Exercise: a safe int

Write a function safe_int(text, default=0) that returns the integer from the string text. If int does not accept the string and raises a ValueError, the function returns default.

  • safe_int("42") → 42
  • safe_int("ten") → 0
  • safe_int("3.5", -1) → -1

Constraints: text is always a string, possibly empty; default is an integer and may be passed by position or by name.

Do not add extra imports unless the task says so explicitly.

safe_int.py — python
python · 3 lines
Ctrl+Enter run · Esc leave editor

Subscribe to take the course

The course is free. Sign in with Telegram and subscribe to the channel to open every lesson.

Sign in another way