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:

JavaScript

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:

JavaScript

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

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement