Skip to content
Advertisement

How does int() in Python know if a number is a float?

Usually if you put int(a) or int(b) it will convert “a” and “b” into integers

If I try print(int(4.5)) it will print 4

But if I try it in a try statement:

def zero_dev(num1, num2):
    try:
        a = int(num1)/int(num2)
        return int(a)
    except ZeroDivisionError:
        return 'Zero Division Exception: integer division or modulo by zero'
    except ValueError:
        try:
            val = int(num1)
            pass
        except ValueError:
            return f"Input Exception: invalid literal for int() with base 10: '{num1}'"
        try:
            val1 = int(num2)
        except ValueError:
            return f"Input Exception: invalid literal for int() with base 10: '{num2}'"
    
    
num_a = input()
num_b = input()
print(zero_dev(num_a, num_b))

Edit: If num1 = 4 and num2 = 4.5

How come Python didn’t convert num2 into an integer?

Previously int() would convert a float into an integer.

But here it doesn’t convert it, it tells me “num2” has a base of 10, it is not an integer.

Advertisement

Answer

input() always returns a string. So num_a = input(...) makes num_a a string.

int() won’t convert floats-as-strings to integers:

>>> int(3.4)  # ok
3
>>> int("3")  # ok
3
>>> int("3.4")  # not ok
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '3.4'

But float() has no problems with string inputs of floats or ints:

>>> float("3.4")
3.4
>>> float("3")
3.0

So combine that to get the behaviour you want – first convert the input (which is a string) to a float and then to an int:

>>> int(float("3.4"))
3
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement