0

I am gradually learning Python, using version 3.9.

I want to check if an input() is an INT or FLOAT, i have the following script but whatever i enter the first IF always runs.

i = input("Please enter a value: ")


if not isinstance(i, int) or not isinstance(i, float):
    print("THis is NOT an Integer or FLOAT")

elif isinstance(i, int) or isinstance(i, float):
    print("THis is an Integer or FLOAT")

could someone explain what i am doing wrong please

MattDMo
  • 100,794
  • 21
  • 241
  • 231
Rob
  • 59
  • 1
  • 12

1 Answers1

4

You can check with something like this. Get the input and covert it to float if it raises value error then it's not float/int. then use is_integer() method of float to determine whether it's int or float

Test cases

-22.0 -> INT
22.1 -> FLOAT
ab -> STRING
-22 -> INT

Code:

i = input("Please enter a value: ")       
try:
    if float(i).is_integer():
        print("integer")
    else:
        print("float")
except ValueError:
    print("not integer or float")
Equinox
  • 6,483
  • 3
  • 23
  • 32
  • You covered why it is not working on comment so added the code explanation. – Equinox Nov 10 '20 at 19:46
  • Note that the check does not correctly separate integer-valued float literals from integer literals (i.e. what Python itself would do). Compare ``float("1").is_integer()`` and ``float("1.0").is_integer()`` to ``type(1)`` and ``type(1.0)``. – MisterMiyagi Nov 10 '20 at 19:52