Ibrahim
Ibrahim

Reputation: 11

How to check if input is float or int?

I want to make a simple converter, to print either hexadecimal number of float or integer. My code is:

number = input("Please input your number...... \n") 
if type(number) == type(2.2):
    print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
elif type(number) == type(2):
    print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number)) 
else:
    print("you entered an invalid number")

But it is always skipping the first two statements and just print else statements. Can someone please find out the problem ?

Upvotes: 0

Views: 6270

Answers (4)

Asad Ullah
Asad Ullah

Reputation: 43

If you want to check whether an input is int, float or string, we can also use these checks to determine this:

val= input("Please enter a value: ") # string 
if val.find(".")>-1 and val[:val.find(".")].isnumeric() and 
val[val.find(".")+1:].isnumeric(): # checks if string before and after "." is int
    val=float(val)
elif y.isnumeric():
    val=int(val)

Upvotes: 0

MisterMiyagi
MisterMiyagi

Reputation: 50076

TLDR: Convert your input using ast.literal_eval first.


The return type of input in Python3 is always str. Checking it against type(2.2) (aka float) and type(2) (aka int) thus cannot succeed.

>>> number = input()
3
>>> number, type(number)
('3', <class 'str'>)

The simplest approach is to explicitly ask Python to convert your input. ast.literal_eval allows for save conversion to Python's basic data types. It automatically parses int and float literals to the correct type.

>>> import ast
>>> number = ast.literal_eval(input())
3
>>> number, type(number)
(3, <class 'int'>)

In your original code, apply ast.literal_eval to the user input. Then your type checks can succeed:

import ast

number = ast.literal_eval(input("Please input your number...... \n"))
if type(number) is float:
    print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
elif type(number) is int:
    print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number)) 
else:
    print("you entered an invalid type")

Eagerly attempting to convert the input also means that your program might receive input that is not valid, as far as the converter is concerned. In this case, instead of getting some value of another type, an exception will be raised. Use try-except to respond to this case:

import ast

try:
    number = ast.literal_eval(input("Please input your number...... \n"))
except Exception as err:
    print("Your input cannot be parsed:", err)
else:
    if type(number) is float:
        print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
    elif type(number) is int:
        print("Entered number is, ", number, "and it's hexadecimal number is:", hex(number)) 
    else:
        print("you entered an invalid type")

Upvotes: 3

Ibrahim
Ibrahim

Reputation: 11

I wanted to make a simple converter that would convert decimal or float number to Hexadecimal using Python3. But before that I wanted to add a simple check if the number entered through command prompt is decimal or hexadecimal. But after some searching I found that the problem with input() function of Python3 is that anything entered through terminal using this function will always print as string and doesn't evaluate it. So we can't apply check condition directly. Now there is one possibility to use data-conversion function like number = int(input("Enter the number")) or number = float(input("Enter the number")) but here the main problem is we can only check one condition at a time, either, float or integer. Like the one shown below:

number = float(input("Enter the number"))
if type(number) == float:
    print("Entered number is float and it's hexadecimal is:", float.hex(number))
else:
    print("you entered an invalid number") 

Or the same method can be used for int with little modification like:

number = int(input("Enter the number"))
if type(number) == int:
    print("Entered number is, ", number,"and it's hexadecimal is:", hex(number))

else:
    print("you entered an invalid number")

But here we can only enter integer because float can not be converted into integer using int() function. It will give the following error:

invalid literal for int() with base 10: '2.2'

Upvotes: -1

L3viathan
L3viathan

Reputation: 27273

input returns a string, you are trying to check whether it looks like a float or an integer:

number = input("Enter your number? ")
try:
    number = int(number)
    print("Entered number is, ", number,"and it's hexadecimal number is:", hex(number))
except ValueError:
    try:
        number = float(number)
        print("Entered number is float and it's hexadecimal number is:", float.hex(number)) 
    except ValueError:
        print("You entered an invalid number")

Upvotes: 2

Related Questions