You are on page 1of 21

Topic 9: Data types in Python

Python Data Types


Data types are the classification or categorization of data items or data elements or data
value. It represents the type that tells what operations can we perform on specific data.
Every value in Python has a datatype. Since everything is an object in Python programming,
data types are actually classes and variables are instance (object) of these classes.

There is no need specify the datatype while creating or defining a variable in Python. But we
do have different data types available in Python
Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it. The
interpreter implicitly binds the value with its type.

In Python, the data types are associated with the values and not with the variable. Every
value in Python has a data type.

The explicit values which we use in our python code (script or program) are known as
literals.
Examples like : 36, 75.25 and 'Science' are called literals

print(36)
print(75.25)

print('Science')
print(20+80)

Each literal value has a data type associated with it.

For example the literals 36, 20 and 80 are of Integer data type, 75.25 is of Float data type
and the value 'Science' is of String data type

Everything in Python is an object. That means even the data types are classes and variables
are instances (objects) of these classes
There are various data types in Python.

Basic Data Types in Python

Now you know how to interact with the Python interpreter and execute Python code and
Now let us see the basic data types that are built into Python.

Python Numbers

Integers, floating point numbers and complex numbers fall under Python numbers category.

They are defined as int, float and complex classes in Python.

We can use the type() function to know which class a variable or a value belongs to.

Similarly, the isinstance() function is used to check if an object belongs to a particular class.

a=5
print(a, "is of type", type(a))

a = 2.0

print(a, "is of type", type(a))

a = 1+2j
print(a, "is complex number?", isinstance(1+2j,complex))

Output

5 is of type <class 'int'>


2.0 is of type <class 'float'>

(1+2j) is complex number? True


Integers can be of any length, it is only limited by the memory available.

A floating-point number is accurate up to 15 decimal places. Integer and floating points are
separated by decimal points. 1 is an integer, 1.0 is a floating-point number.

Complex numbers are written in the form, x + yj, where x is the real part and y is the
imaginary part.

>>> a = 1234567890123456789

>>> a
1234567890123456789

>>> b = 0.1234567890123456789
>>> b
0.12345678901234568

>>> c = 1+2j
>>> c

(1+2j)

Notice that the float variable b got truncated.


Numeric Data Type:

In Python, numeric data type represents the data that has a numeric value. The numeric
value can be an integer, floating number, or even complex number. These values are defined
as int, float, and complex classes in Python.

1. Integers :
It consists of positive or negative whole numbers (without fraction or decimal).
Integers are zero, positive or negative whole numbers without a fractional part and having
unlimited precision, e.g. 0, 100, -10. The followings are valid integer literals in Python.

Integers can be decimal, binary, octal, and hexadecimal values.


All integer literals or variables are objects of the int class.

Integers in Python 3 are of unlimited size. There is no maximum limit or bounds for the
integer datatype in Python. So effectively Integer has no limit as how large an integer value
can be. The integer type is unbounded

But of course, it is limited or constrained by the amount of memory available on your


System.

In python 3 there is no sys.maxint There is a sys.maxsize

>>> import sys

>>> sys.maxsize

2147483647

That does not mean that the maximum int is limited to 2 billion! It means that the size of the
object containing the integer has a maximum size of 2 billion bytes. I.e. a very very large
number

It varies from system machine to system machine


>>> import sys

>>> sys.maxsize

9223372036854775807
Python can handle arbitrarily large integer numbers in computation

numx=958731963267543298132764509873506365343428250233984398382362323623265
3625212798963

print(num)

print(type(num))

In Python, integer variables are defined by assigning a whole number to a variable. Python's
type() function can be used to determine the data type of a variable.
Examples : 2, 0, -12

>>> 0
0

>>> 100
100
>>> -10

-10
>>> 1234567890

1234567890
>>> y=5000000000000000000000000000000000000000000000000000000

5000000000000000000000000000000000000000000000000000000

Python interprets a sequence of decimal digits without any prefix as a decimal value number
Integers can be binary, octal, and hexadecimal values.

>>> 0b11011000 # binary

216
>>> 0o12 # octal

10

>>> 0x12 # hexadecimal


15

All integer literals or variables are objects of the int class. Use the type() method to get the
class name

This data type is represented with the help of int class.

>>>type(100)
<class 'int'> # type of x is int

>>> x=1234567890
>>> type(x)

<class 'int'> # type of x is int

>>> y=5000000000000000000000000000000000000000000000000000000
>>> type(y) # type of y is int

<class 'int'>

Leading zeros in non-zero integers are not allowed e.g. 000123 is invalid number, 0000 is 0.

>>> x=01234567890
SyntaxError: invalid token
Python does not allow comma as number delimiter. Use underscore _ as a delimiter instead.

>>> x=1_234_567_890

>>> x
1234567890

Note that integers must be without a fractional part (decimal point). It it includes a fractional
then it becomes a float.

>>> x=5

>>> type(x)

<class 'int'>

>>> x=5.0
>>> type(x)

<class 'float'>

>>> int('100')
100

>>> int('-10')
-10

>>> int('5.5')

5
Binary
A number having 0b with eight digits in the combination of 0 and 1 represent the binary
numbers in Python. For example, 0b11011000 is a binary number equivalent to integer 216.

>>> x=0b11011000
>>> x

216
>>> x=0b_1101_1000

>>> x
216

>>> type(x)

<class 'int'>

Octal
A number having 0o or 0O as prefix represents an octal number. For example, 0O12 is
equivalent to integer 10.

>>> x=0o12

>>> x

10

>>> type(x)

<class 'int'>

Hexadecimal
A number with 0x or 0X as prefix represents hexadecimal number. For example, 0x12 is equivalent to
integer 18.

>>> x=0x12
>>> x

18

>>> type(x)

<class 'int'>
Float :

In Python, floating point numbers (float) are positive and negative real numbers with a
fractional part denoted by the decimal symbol . or the scientific notation E or e, e.g. 1234.56,
3.142, -1.55, 0.23.

The decimal point in a real number is called floating point because it can be placed
anywhere. The decimal point is not fixed at a particular position. It can be floating at any
position

A floating point number is accurate up to 15 decimal places

Integer numbers and floating pointing numbers are differentiated by the presence of
decimal point. 1 is an integer number and 1.0 is a floating-point number

Optionally the character 'e' or 'E' followed by a positive number or a negative number can be
appended to specify scientific notation (or exponential notation)

>>> f=1.2

>>> f

1.2

>>> type(f)

<class 'float'>

Floats can be separated by the underscore _, e.g. 123_42.222_013 is a valid float.

>>> f=123_42.222_013

>>> f

12342.222013
Scientific notation is used as a short representation to express floats having many digits. For
example: 345.56789 is represented as 3.4556789e2 or 3.4556789E2

>>> f=1e3

>>> f

1000.0

>>> f=1e5
>>> f

100000.0
>>> f=3.4556789e2

>>> f
345.56789 # 3.4556789 x 100

>>> f=1e-2

>>> f

0.01 # 1/100

Use the float() function to convert string, int to float.

>>> float('5.5')
5.5

>>> float('5')
5.0

>>> float(' -5')

-5.0
>>> float('1e3')

1000.0
The float beyond its maximum size referred as "inf", "Inf", "INFINITY", or "infinity".

>>> float('-Infinity')

-inf

>>> float('inf')

inf

We found out the maximum value that a float variable can hold with the sys.float_info.max
The output shows that the upper limit of a float variable is 1.7976931348623157e+308

>>> import sys


>>> sys.float_info.max

1.7976931348623157e+308
>>>

>>> sys.float_info.min

2.2250738585072014e-308

>>> import sys


>>> sys.float_info

sys.float_info(max=1.7976931348623157e+308, max_exp=1024, max_10_exp=308,


min=2.2250738585072014e-308, min_exp=-1021, min_10_exp=-307, dig=15, mant_dig=53,
epsilon=2.220446049250313e-16, radix=2, rounds=1)
Python will indicate a number greater than 1.7976931348623157e+308 by 'inf' which means
infinity

>>> 1.79e308

1.79e+308

>>> 1.8e308
inf

The closest non-zero number is approximately 5.0X10to power-324

>>> 5e-324

5e-324

anything closer to zero than 5e-324 is effectively zero (0)

>>> 1e-325

0.0
3. Complex Number

Python is a very versatile language for dealing with numerical data. It also supports working
on both real and imaginary numbers.

Most scientists and engineers, as well as every mathematician, should have an


understanding of complex numbers. Physicists and electrical engineers may routinely work
with complex numbers. Complex numbers, are used in real-life applications, such as
electricity, as well as quadratic equations. We can use Python for creating scientific
applications, mathematical applications and engineering applications, and in developing
those kind of applications the complex number data type can be used if required

But normally we don't use complex numbers in our python programs

A complex number is a number with real and imaginary components. For example, 5 + 6j is a
complex number where 5 is the real component and 6 multiplied by j is an imaginary
component.

In mathematics, Complex numbers are the numbers that are expressed in the form of a+ib

where, a and b are real numbers and ‘i’ is an imaginary number called “iota”.

The value of i = (√-1).

Complex numbers have a real part and an imaginary part


We can define complex numbers in python by simply declaring a variable and assigning an expression
of the form (a+bj) .Here “a” and “b” should be a numeric and “j” is a small 'j' or capital alphabet 'J'

>>> cn = 4+2j

>>> cn

(4+2j)

>>> print(cn)

(4+2j)

>>> type(cn)

<class 'complex'>

myNum= 3+2j

print("The Number is:")


print(myNum)

print("Data type of Number is:")

print(type(myNum))

>>> 2 + 3j

(2+3j)
>>> 4j

4j
>>> 0 + 4j

4j
>>> 2 + 0j

(2+0j)

>>> 8 - 2j

(8-2j)

>>> -2 + 3j
(-2+3j)

>>> 1j * 1j

(-1+0j)

>>> 2j * 2j

(-4+0j)
>>> c = 3 +6j

>>> print(type(c))

<class 'complex'>

>>> print(c)
(3+6j)

>>> c1 = complex(3,6)

>>> print(type(c1))

<class 'complex'>

>>> print(c1)
(3+6j)

You must use j or J as imaginary component. Using other character will throw syntax error.

>>> a=5+2k

SyntaxError: invalid syntax

>>> a=5+j

SyntaxError: invalid syntax


>>> a=5i+2j
SyntaxError: invalid syntax
complex()

The complex() method returns a complex number when real and imaginary parts are
provided, or it converts a string to a complex number.

The syntax of complex() is:

complex([real[, imag]])

It takes two numeric parameters, the first one is a real number which is mandatory and the
second one is an imaginary number which is an optional paramter

Return Value from complex()

As suggested by the name, complex() method returns a complex number.

If the string passed to this method is not a valid complex number, ValueError exception is
raised.

Example:

>>> complex(4)
(4+0j)

>>> complex(5,3)

(5+3j)

>>> r=8

>>> i=2
>>> c=complex(r,i)

>>> print(c)

(8+2j)
Extracting real and imaginary part of a complex number

In a complex number (a+bj), “a” is called the real part and “b” is called the imaginary part.

We can extract real part of the complex number using an attribute named “real” which
contains value “a” and imaginary part using the attribute “imag” which contains the value
“b” as follows.

To access the real part of a complex number, we can use the built-in real attribue function
and similarly use the imag attribute to access the imaginary part

>>> #Complex Number:

>>> c = (3 + 6j)
>>> #Real Part of complex number

>>> print('Complex Number: Real Part is = ', c. real)


Complex Number: Real Part is = 3.0

>>> #Imaginary Part of complex number

>>> print('Complex Number: Imaginary Part is = ', c. imag)


Complex Number: Imaginary Part is = 6.0

myNum= complex(3,2)

print("The Complex Number is:")


print(myNum)
print("Real part of the complex Number is:")

print(myNum.real)
print("Imaginary part of the complex Number is:")

print(myNum.imag)
Output

The Complex Number is:

(3+2j)
Real part of the complex Number is:

3.0

Imaginary part of the complex Number is:

2.0
Boolean Data Type:

In programming, you often want to check if a condition is true or not and perform some
actions based on the result.
To represent true and false, Python provides you with the boolean data type. The boolean
value has a technical name as bool.

The boolean data type has two values: True and False.

Note that the boolean values True and False start with the capital letters (T) and (F).

is_active = True

is_admin = False

The bool() function

To find out if a value is True or False, you use the bool() function. For example:

>>> bool('Hi')

True
>>> bool('')

False
>>> bool(100)
True

>>> bool(0)

False

As you can see clearly from the output, some values evaluate to True and the others
evaluate to False.
Falsy and Truthy values

When a value evaluates to True, it’s truthy. And if a value evaluates to False, it’s falsy.

The following are falsy values in Python:

The number zero (0)


An empty string ''

False
None

An empty list []

An empty tuple ()
An empty dictionary {}

The truthy values are the other values that aren’t falsy.
String Data Type:

In Python, a string is a sequence of Unicode characters. Unicode was introduced to include


every character in all languages and bring uniformity in encoding
Strings can be created by enclosing characters inside a single quote or double-quotes. Even
triple quotes can be used in Python but generally used to represent multiline strings and
docstrings.

A triple quoted string can be enclosed in three single quotes ‘’’ or three double quotes “””

my_string = 'Hello'
print(my_string)

my_string = "Hello"

print(my_string)

my_string = '''Hello'''

print(my_string)

# triple quotes string can extend multiple lines


my_string = """Hello, welcome to
the world of Python"""

print(my_string)

>>> uname="Issac Newton"

>>> type(uname)
<class 'str'>
>>> type('Hello World')

<class 'str'>

>>> type('''Welcome to Python Triple Quoted Strings''')

<class 'str'>
>>> msg="Jun 29th is India's National Statistics Day"

>>> print(msg)

Jun 29th is India's National Statistics Day

>>> quote='The famous quote "Time is money" is from Benjamin Franklin'

>>> print(quote)
The famous quote "Time is money" is from Benjamin Franklin

>>> message='''Our chef Manohar's special dish is "Paneer Afgani" is available today'''
>>> print(message)

Our chef Manohar's special dish is "Paneer Afgani" is available today

>>> mesg="""Our chef Manohar's special dish is "Paneer Afgani" is available today"""
>>> print(mesg)

Our chef Manohar's special dish is "Paneer Afgani" is available today

You might also like