Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
Write a function safe_int(text, default=0) that returns the whole number in the text, or the default if the text is not a number. What are safe_int("42"), safe_int("abc") and safe_int("abc", -1)?
try int(text), except ValueError: return the default.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, compare your working with the solution.
Plan. Try int(text). If a ValueError happens, return the default.
safe_int("42") is 42.safe_int("abc") is 0, the default.safe_int("abc", -1) is -1.Log in to join the discussion.
Loading…