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

3
  • i is always string. Commented Nov 10, 2020 at 19:35
  • input() always returns a string, which is neither an int nor a float. Even if it were an int or a float, you'd always go into the first if because x or y is true if either x or y are true. Commented Nov 10, 2020 at 19:35
  • so is there a way i can check if input value is either an INT or FLOAT ?? EG like a TryConvert ?? Commented Nov 10, 2020 at 19:37

1 Answer 1

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") 
Sign up to request clarification or add additional context in comments.

2 Comments

You covered why it is not working on comment so added the code explanation.
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).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.