-2

I'm just trying to understand what is the difference between int and int(). Here is my code:

def function(define):
    if type(define) == int:
        return 'sorry'
    else:
        return len(define)

print(function(10))

and it returns: sorry

File "exercise2.py", line 14, in <module>
    print(function(10))
  File "exercise2.py", line 12, in function
    return len(define)
TypeError: object of type 'int' has no len()
Jimmy Hoho
  • 37
  • 1
  • 4

3 Answers3

3

int - a numeric type

int() - a method that return an integer object from any number or string

both are not sequences/collections so they do not have length thus you can't use len() on them.

A better way to check if the variable is an int is:

def function(define):
    if isinstance(define, int):
        return 'sorry'
    else:
        return len(define)

print(function(10))
Dani G
  • 1,202
  • 9
  • 16
1

To answer your question, technically int is a class but you can also think of it as a data type as others have noted. Since it is a callable object int() would invoke the __call__ method for the int class. For the sake of this question, you can think of it as a constructor that takes a string representation of an integer and returns an int.

Here's an example in the Python REPL for clarity.

Python 3.7.0 (default, Sep 22 2018, 18:29:00)
[Clang 9.1.0 (clang-902.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> int
<class 'int'>
>>> int('1')
1
>>> int('a')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
>>> int.__call__('1')
1
>>> isinstance(int('1'), int)
True
>>> type(1) is int
True
Skam
  • 7,298
  • 4
  • 22
  • 31
0

int is used to do things like determine the type of a variable (as you've done in your example). int() is used to convert a non-int variable to an int (i.e. "45" becomes 45). I'm not really sure what you're getting at with your example. Everything seems to be running correctly and then you just pasted the errors without any kind of explanation.

tkiral
  • 49
  • 1
  • 9