In python, the data type is a property of data which tells the compiler how to handle it in the python program. The data type defines the type of data that a variable is holding in python script. We are going to learn in details about various Python data types such as numeric data type, float data type, string data type, how they are used in python and the data type conversion as well.
Table of contents
- Introduction to Python Data types
- A real-world example of data types
- Python built-in data types
- Numeric datatype
- String datatype
- Boolean datatype
- Complex datatype
- Data type conversion
- YouTube video – Datatypes in Python
Introduction to Python data types
Each variable that is used in Python is associated with some datatype. In Python, programmers do not need to define the type. This is why Python is a dynamically typed language. However, most of the programming languages require to declare the datatype during its declaration stage itself whereas Python has the advantage of explicit datatype conversion ( automatically takes datatype based on the context ).
We can use the type ( ) method to know the data type of any variable in Python. See the code below to understand how the data type of variable is automatically assigned and it also changes based on the context (meaning assignment with a different type of value).
Let us consider,
x = 20 # integer type (x) <class 'int'> x = 20.56 # float type(x) <class 'float'>
A real-world example of data types
In real-world, we see materials of several types (the various state). We can coincide these with the datatype (although too much non-similarities). We tried putting some objects & their state from real-world scenarios. As you can see Honey has a semi-thick liquid type of state whereas Sand holds a free flow solid state. The Rock poses a solid hard shape and Water is in the liquid state. Although real-world data type does not help to understand program data type it will provide an intuition about the same. Python has several data types such as Numeric, Floating, Boolean and complex.
Built-in Python data types
By default, Several data types arrive with basic python installation and to use them in the program one doesn’t need to import a library in python. They are known as built-in data types. A comprehensive list of built-in data types and built in functions are available at online python documentation. We will see some of the common data types here.
Broad categories of built-in data types in python are –
- Numeric – Deals with all numerical data
- Sequence – Operating on the collection of more than one number
- Python tuples
- Binary – Deals with binary level representation
- Set – Manage various set operations
- String – For string conversion
- Map – Deals with key-value pair as one collection
Numeric Data types in Python
To deal with numeric (both Negative and Positive number including zero) value in python. Each number related data, calculation and modification are taken care of by numeric datatype. There are two subcategories of numeric datatype i.e., Integers and floats (or Floating-Point numbers).
YouTube video explaining Datatypes
To handle all numbers from negative to positive including 0. Integer also referred to as int in python. There is practically no limit on the size of integer that can be written, it is only limited by the available memory on your system. This category of datatype does not handle decimal value at all. However, an integer can be typed cast into float type by using python inbuilt data type conversion known as a float ().
x = -7 type (x) <class 'int'>
x = 8 type (x) <class 'int'>
Type conversion from int to float
x = 23 float (x) 23.0 type (23.0) <class 'float'>
Binary to Decimal conversion
Python allows us to convert a binary number to Integer using a specific syntax, just prefix 0b (zero b in lower case) or 0B (zero B in upper case) before the binary number.
print (0b1001) 9 print (0B1001) 9
Hexadecimal to Decimal conversion
Similar to Binary-Integer conversion, We can also convert a hexadecimal value to integer value for easy & quick understanding of us. Conversion is simple, just prefix the hexadecimal value with 0x (zero x). Hexadecimal value can be written in either upper case or lower case like df or DF.
print (0x4df) 1247 print (0X4DF) 1247
Handles decimal (float) values in python. Float means integer with the decimal point and other integers like 23.67. Alike Integer to float conversion, Floating point number can also be typed cast into an integer using int () method. When a floating number is typed-cast into an integer, anything after the decimal point will be ignored.
x = 23.67 type (x) <class 'float'>
Type conversion from float to int
x = 23.67 int (x) 23 type (23) <class 'int'
Short Representation of long number
Python, like mathematics, gives freedom to represent the long number to a convenient form. We can represent it using e symbol which means 10. Let say, we want to represent 31400000.
x = 3.14e7 """ Simplifying -> 3.14*10**7 ** means raised to the power 3.14*10000000 31400000 """
String Data type in Python
Designed to handle strings, texts, characters and words. They are mostly used to hold the string and to display the information using some function such as print statement. Strings are always defined and displayed under the single quotation (‘ ‘) or the double quotation (“ ”).
There is no difference between representing them in a single or double quote. However, there are some reasons to choose one over others, depending on the use case. Both single and double quotes represent the same class that is ‘str’ (string data type). The output of type () function returns <class ‘str’> which means string class & it can be understood as string datatype.
Python follows OOP (Object Oriented Programming) paradigm which means everything in python is an object associated with a class. You can learn about Python List which uses square brackets [ ] to write elements and all elements are separated by comma. Strings in Python are also a List (array in another programming language) or sequences of character, and various slicing operations holds true for strings as well. Check out our List Tutorial for more info.
print ("aipython") # with double quotes aipython type ("aipython") <class 'str'>
print ('aipython') # with single quotes aipython type ('aipython') <class 'str'>
During representing Python strings in the program, some time programmer wants to display string the way it should be (without any alteration in the output). In such a scenario, Raw string comes handy and will serve the purpose. To pass the string as a raw string in the program we can put character r in upper or lower case (r / R). Raw strings are helpful when passing absolute file paths, location or strings with forward-slash (/) or backwards-slashes ( \ ). Example code below will provide more insights.
print ("Welcome to \aipython") Welcome to ipython" # forward-slash removed the next immediate character, which is a print (r"Welcome to \aipython") # passing it as a raw string Welcome to \aipython # printed as it is (no alteration) print ("C:\aipython") C: ipython # \a is removed because of escape character print (r"C:\aipython") # passing a raw string print C:\aipython
Triple quote strings (as docstrings)
In certain situations, we need to write both single quote (‘) and double quote (“) inside a complete string. Tripple quote can be written using single type triple quote ( ”’ ”’) or double type triple quote (“”” “””). However, the escape sequencing or escape character (with forward-slash or backslash) can’t be ignored under triple quote strings. Additionally, a triple quote can be used to write a long description in between the code block and these blocks are not executed by the python compiler. The example below shows both the scenario
print (""" Welcome to (') aipython (") - Learn & Innovate """) Welcome to (') aipython (") - Learn & Innovate # triple quote for writing long descriptions x = 10 y = x+10 """ This code is written to add a value of 10 to to variable y and """ print (y) 20
Boolean Data types in Python
Boolean datatype handles True & False value I.e., 1 & 0. There is no grey area to represent in between (just kidding). These data types are mostly used to represents the evaluation results in the concrete of True or False. True equates to 1 and False equates to 0 in integer.
print (7 > 2) True print (4 < 1) pFalse
Complex Data types in Python
A complex number is composed of a Real Part (+/-) Imaginary part conjugated with j (you might have used i in place of j, in elementary mathematics, that’s okay both are same). Python facilitates the usage of the complex number and a special class is specified for working with them.
Format for the complex number: a+bj or a-bj
print (3+4j) 3+4j type (3+4j) # to know the datatype/class <class 'complex'>
Real and imaginary part of a complex number can be obtained by using .real and .imag methods respectively. The output from these two methods are always floating number.
z = 3+4j print (z.real) # to get the real part 3.0 print (z.imag) # to get the imaginary part 4.0
Data type conversion in Python
As we have seen earlier, certain data types can be converted to other types such as int to float and float to int. Similarly, there are other type conversions possible in python. Given below are some examples of data type conversion.
Returns string version of any object
ascii ( ) ascii (23) '23'
bin () bin (8) 'ob1000'
chr () chr (9) '\t'
ord ( ) ord ('D') 68
>>> str ( ) >>> str (3.5) >>> '3.5'
Keep Learning and Keep Growing !!