Tuesday, March 17, 2015

Why There is No Type Declaration in Python - Python Variables - Python Tutorial

Why There is No Type Declaration in PythonWhy There is No Type Declaration in Python


If you have learned other programming languages like Java or C you may a bit confused why we can declare a variable without giving that variable a type.  If Python is your first language, then you may not. Python is smart enough to find out our types when we declare a variable in our programs. If Python can find out what type of data we are using in our code then why would we waste our time declaring types of variables?


The Reason Why There is No Type Declaration in Python


The reason why we do not have to give a variable a type declaration is because the variable does not contain any information.  In the previous tutorial, we discussed that variables are just pointers or they just reference a section of memory called an object. The object contains the type information, the value that was given and a reference counter.


Why Does The Object Hold Type Information?


The object holds the type information to save memory and accelerate your programs. If we created several variables with the exact same value then these variables are just pointing to one memory space. If the variables held the type information and values then we would be using a lot more memory in our programs which would slow down the program. In this day and age everyone wants programs to run at high speed.  So when an object holds the information we can cut down on memory used.


How to Access Python Objects Type Information?


We can access the type information in our objects by using a built-in function called type(). Let’s take a look at some examples.


Access Python Objects Type Information Examples


#Type integer
>>> a = 9
>>> type(a)
<class 'int'>

#Type Float
>>> b = 6.7
>>> type(b)
<class 'float'>

#Type String
>>> c = "String"
>>> type(c)
<class 'str'>

#Type List
>>> d = [123, 456, 789]
>>> type(d)
<class 'list'>

#How about first object contained in the list
>>> type(d[0])
<class 'int'>

Now that we have seen Why There is No Type Declaration in Python the understanding of how variables work should become clear as we move on with our Python Variable tutorials.  If you have any questions about Why There is No Type Declaration in Python leave a comment below we will be sure to help you out.



No comments:

Post a Comment