Data types · 29 / 29 Exercise Medium

Safe conversion to integer

Objective

int() raises ValueError if the text is not an integer. A function can catch that error and return None to signal that the conversion was not possible.

Instructions

  • Write to_int(text) that returns the integer or None if it cannot be converted.
  • Read n and then n texts; for each one show 'text': number with the result, or 'text': invalid if it is not valid (use !r to show the text).
Input
3
12
abc
-7
Output
'12': 12
'abc': invalid
'-7': -7

Open the editor in full screen: the statement on the left and your code, the output and the tests on the right.

Start exercise