Double a number, without crashing on bad input.
What to build
A program that handles one expected error.
Requirements
- Read a line.
- If it is a whole number, print double its value.
- Otherwise, print
Not a number.
Input
One line of text.
Output
One line.
Constraints
The line has at most 20 characters.
Example
Input:
21
Output:
42
Why it works
int raises ValueError for text it cannot read, and catching exactly that error leaves any other kind of mistake visible.
Examples
Example 1 · Input
21
Expected output
42
Example 2 · Input
abc
Expected output
Not a number
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Put the int(...) inside try.
Hint 2
except ValueError catches text that is not a whole number.
Solution
Show one correct solution (try it yourself first)
text = input()
try:
n = int(text)
print(n * 2)
except ValueError:
print("Not a number")