Santosh Kumar
Santosh Kumar

Reputation: 27875

How to print something on the basis of data (input) type?

I want to print different things when input() gets different data types. I have the following script:

#!/usr/bin/env python
#-*- coding:utf-8 -*-

f = input("Please enter a number: ")

if f == type(int):
    print("That's good")
elif f == type(str):
    print("That isn't a number.")
else:
    print("BrainOverflow")

This script always returns the else part.

Upvotes: 0

Views: 2465

Answers (2)

user2665694
user2665694

Reputation:

Does not make any sense that you are trying since the result of the input() call is always a string. Your code needs some dedicated methods for checking if the string is representation of an integer or not. See

Python: Check if a string represents an int, Without using Try/Except?

Upvotes: 2

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 250961

It's not recommended to do type checking in python, so you can try something like this:

f = input("Please enter a number: ")
try:
    f=int(f)
    print("That's good")
except ValueError:
    print("That isn't a number.")

or :

f = input("Please enter a number: ")
if f.isdigit():
    print("That's good")
else:
    print("That isn't a number.")

Upvotes: 1

Related Questions