LearnFrenzy
Sign in Take a free test

Variables and Data Types · Variables and Data Types Coding Problems · Question 1

Detect whether input is an integer, a decimal or text in Python Solution, output & explanation

  • Program
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 1 Back to Exercise

For each line of input, print whether it is an integer, a decimal number or plain text.

Solution
main.py Run
import sys

for line in sys.stdin.read().split("\n"):
    text = line.strip()
    try:
        int(text)
        kind = "integer"
    except ValueError:
        try:
            float(text)
            kind = "decimal number"
        except ValueError:
            kind = "text"
    print(f"{text!r} is {kind}")

Output Verified by running it on Python 3

'42' is integer
'-7' is integer
'3.14' is decimal number
'1e3' is decimal number
'hello' is text
'12abc' is text

Try the strictest conversion first: int() fails on "3.14", float() accepts it (and scientific notation like 1e3), and anything that fails both is text.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links