What does it mean when you assign int to a variable in Python?

3.4k views Asked by At

i.e. x = int

I understand that this will make x an integer if it is not already one, but I'd like to understand the process behind this. In particular, I'd like to know what int is (as opposed to int()). I know that int() is a function, but I'm not sure what int is. Links to documentation about int would be helpful since I couldn't find any.

2

There are 2 answers

2
Ryan Haining On BEST ANSWER

Imagine you had a function called func

def func():
    print("hello from func")
    return 7

If you then assigned func to x you are assigning the function itself to x not the result of the call

x = func # note: no ()
x() # calls func()
y = x() # y is now 7

You're looking at a very similar thing with int in this context.

x = int
y = x('2') # y is now 2
3
BrenBarn On

x = int will not make x into an integer. int is the integer type. Doing x = int will set x to the value of the int type. Loosely speaking, x will become an "alias" for the integer type.

If you call the int type on something, like int('2'), it will convert what you give into an integer, if it can. If you assign the result of that call to a variable, it will set that variable to the integer value you got from calling int. So setting x = int('2') will set x to 2.

You should read the Python tutorial to understand how types, variables, and calling work in Python.