1

I'm a beginner trying to learn Python and decided to try an exercise where I would take an input, and distinguish its type; whether its an integer, floating point or a string.

As I understand it, Python treats all inputs as strings, so even when I enter a number/decimal point, the input is considered a string. I have overcome the first step in differentiating whether the input is a string or otherwise via this:

def get():
    prompt = 'Give a number or a word.\n'
    x = input(prompt)
    try:
        float(x)
        print('You entered a number.')

    except:
        print('You entered a string.')

I take advantage of 'try' and 'except', as float(x) will return an error if x is a string and not a number/floating point. Next, I deduce that I can use a similar method to distinguish between integers and floating point numbers, but I don't know what can cause an error for an integer that wouldn't for a floating point, vice versa. (since float(x) where x is an integer works fine)

Is there such a thing so that I can use a similar method to distinguish between decimal number inputs and integers?

3
  • By definition, all float values contain a decimal point: print (type(1.),type(1)) Commented Mar 10, 2020 at 10:50
  • @usr2564301 No, there are floats that don't contain decimal point: inf is a float without one and then there is a whole class of representation by scientific notation (3e-1 == 0.3) which doesn't contain any either. Not to speak of all the flavours of nan. Commented Mar 10, 2020 at 10:58
  • @dedObed: I meant "by OP's own definition" :P x.index('.') will "cause an error for an integer that wouldn't for a floating point", and type shows Python agrees with that definition. Commented Mar 10, 2020 at 11:04

3 Answers 3

5

There are two questions within your question.

  1. To handle the string > int/float, you could take advantage of ast.literal_eval first:
>>> import ast
>>> print(type(ast.literal_eval("2"))
int
>>> print(type(ast.literal_eval("3.4"))
float
>>> print(ast.literal_eval("3e2"))
300.0
  1. To check for type, you're looking for isinstance I think.
>>> x = 2
>>> print(isinstance(x, int))
True
>>> y = 3.4
>>> print(isinstance(y, int))
False
>>> print(isinstance(y, float))
True

So, putting these two together you could use an if statement like that:

if isinstance(ast.literal_eval(x), int):
    # do whatever you want if it's an int
elif isinstance(ast.literal_eval(x), float):
    # do whatever you want if it's a float
Sign up to request clarification or add additional context in comments.

8 Comments

Hi, sadly this does not work. In your case, you've defined x itself before using isinstance. In the specific case I'm looking for, I have to get x as an INPUT, which by default is always a string.
You're right. I was editing to add usage for ast.literal_eval to handle this string input first.
Could you explain what exactly is ast.literal_eval doing in this case such that it can differentiate the input from string/integer/float? I read the explanation on the linked paged and couldn't understand it, it was too technical.
Unfortunately the link was wrong, thanks for pointing that. Corrected it. From the docs: this can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.
What does it mean by "safely evaluating" and "parse"? What is possibly unsafe? How does this lead to us being able to distinguish whether the input is integer or a floating point?
|
2

It depends on what your definition of an integer is. Is "3.0" an integer? Or just "3"? The former is most commonly represented as a floating point number whose value happens to be a mathematical integer (but not of int type).

If you mean to include "3.0", then you can do a test which catches both "3.0" and "3":

f = float(x)
if f==int(f):
   print("really an integer value")

Otherwise you can use isinstance(f, int).

(Caveat: this is easier in Python3. In Python2 there are two kinds of integers -- int and long which you have to test for separately).

6 Comments

Then there is the issue with scientific notation.... 3e1, 3e0 and 3e-1 can be tricky.
@dedObed correct. You can't just look for the decimal point (but scientific notation technically always give floating-point numbers).
@AndrewJaffe: I consider 3e1 = 30 an integer. Alas, the rabbit hole awaits: then 3.1e1 = 31 is also an integer; but 3.11e1 is not.
Hi, I've tried this method but there's something bugging me. why does the if statement only work if I define f = float(x) first, then if f==int(f), but doesn't work for if float(x) == int(x) ? I get an error instead: ValueError: invalid literal for int() with base 10: '5.5' Shouldn't it be the same?
@usr2564301 No, 3e1 is not a python integer: print(3e1) -> 30.0
|
0

The input is alway a string.

You just want to know if that string can be converted to an int or a float value. You can easily convince yourself that most(*) integer representation can be converted to float values while the symetric is not true.

So you should

  1. try to convert to an int
  2. if it failed try to convert to a float
  3. if it still failed process input as a string

The rationale is that if the user typed 3.0 they probably intended that it should be a float value, else they would have typed 3.


Python integers are only limited by the available memory while float are 64 bits iEEE-754 floating point numbers. But Python is kind enough to convert integers greater to the max float values to inf. So even an integer that cannot be represented as a float would be converted with no exception

4 Comments

Hi, how can this distinguish whether an input is int or float? Since int(3.0) will return 3 and we won't know whether the user's input is an int or float.
@Yui: no the input will not be the float 3.0 but the string '3.0'. And int('3.0') does raise an exception.
I am thoroughly confused. In the script, x = input(prompt) y = float(x) does not seem to raise any exceptions. However when I try int('3.0') in the shell, it does indeed give an error. What gives? EDIT: it seems like I was misunderstanding int(). Then the question is, why is it that int() can only take '3' and not '3.0', when typically it will take 3.0 and simply truncate it?
@Yui: you should first try to convert to int: x = input(prompt) y = int(x) will raise.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.