Define a Number as an int Without Using type int

From the lesson - Practise makes perfect: is_int

Continuing the discussion from: How can I test if a number is an integer without using type?

The previous discussion was closed, so had to start a new thread. On the python 2 version of the exercise, the solution uses a function called round but I don’t recall learning about this function in a previous lesson, would someone be able to tell me in which previous lesson, the function was first introduced in?

Cannot say when the function is introduced, or if it even is. However, it is a simple function to learn and use, as the documentation will show.

Essentially, rounding follows one simple rule:

up on 5
down on 4

Let’s look at PI as an example:


Above there are seven decimal places showing. To reduce it to six, we round up on 6 (3.141593). To reduce to five, we round down on 2 (3.14159). For four, up on 9 (3.1416), for three, up on 5 (3.142). For two decimal places we round down on 1 (3.14).

This is the exact behavior of the round() function.

Rounding does not remove the decimal point, though.

round(pi, 0)

However, 3.0 is equal to 3 in terms of value and magnitude. That’s as close as round() can bring us.

Truth is, mathematically there is no way to tell if a number is truly an integer, since that is a type. Allowing for the decimal point zero has to be a given in solving this problem.

We can also use the modulo rule,

 n % 1 is zero, if n is an integer (or the decimal fraction is zero)

When the result is non-zero, then there must be some decimal fraction.

 print (pi % 1)
1 Like

I understand how to do it the modulo way (thanks for explaining), but with the method used in the solution using absolute and round confuses me. Based on the characteristics of how round operate (it will always round up or down to the nearest whole number), why is it if I incorporate round into my modulo solution, it returns false where it should return true?

def test(n):
  n == round(n)
  if n % 1 == 0:
    return True
    return False
print test(1.5)

Returns false, but because the round function has been used, am I not mistaken to think that 1.5 should round to 2, and 2 % 1 = 2 with 0 remainder, meaning it should return true?


Thankyou for pointing that out, I thought if you wanted to assign a new value to a variable you use: == ie

a == 6
print a

should print 6 but only work when you use a singular =, but why when I use a singular = in the function it doesn’t work?

def is_int(x):
  if x % 1 = 0:
    return True
    return False
print is_int(1.2)

= is the assignment operator
== is the comparison operator
a = 6 is an assignment
if x % 1 == 0: is a comparison

In your function:

Okay I understand now thanks for your help.

1 Like