Is there something wrong with this code? Integer data type not recognized?


#1
def by_three(n):
    if n/3 == int:
        return "is divisible by 3"
    else:
        return False 

Why exactly doesn’t this work? I thought int was a data type recognized by Python, and if it is then this code should work right?

This is from the Functions section lesson 6/19

===================================================================================
Solution:

def by_three(n):
    if type(n/3.) == int:
        return "is divisible by 3"
    else:
        return False

#2

Haydhn,

You need to compare the type of the object vs the actual value of the object when comparing it to an int,float,string,boolean.

Example
if type(n / 3) == float or type(n / 3) == int:

class type(name, bases, dict)
With one argument, return the type of an object. The return value is a type object. The isinstance() built-in function is recommended for testing the type of an object.

With three arguments, return a new type object. This is essentially a dynamic form of the class statement. The name string is the class name and becomes the name attribute; the bases tuple itemizes the base classes and becomes the bases attribute; and the dict dictionary is the namespace containing definitions for class body and becomes the dict attribute. For example, the following two statements create identical type objects:

class X(object):
… a = 1

X = type(‘X’, (object,), dict(a=1))


#3

Just for pointing something extra for things like this, there is a function isinstance whose documentation can be found here.

The syntax is like this:

isinstance(object, classinfo)

Where object is the thing you want to check against classinfo that can be tuples, list, classes, etc.

Example:

numbers = [1, 2, 3]

result = isinstance(numbers, list)
print(numbers,'instance of list?', result)

result = isinstance(numbers, dict)
print(numbers,'instance of dict?', result)

result = isinstance(numbers, (dict, list))
print(numbers,'instance of dict or list?', result)

number = 5

result = isinstance(number, list)
print(number,'instance of list?', result)

result = isinstance(number, int)
print(number,'instance of int?', result)

# Output
[1, 2, 3] instance of list? True
[1, 2, 3] instance of dict? False
[1, 2, 3] instance of dict or list? True
5 instance of list? False
5 instance of int? True

Taken from this.


#4

Thanks for your explanation, saved me some headache.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.