Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 42

Data types in Python

Data types are the classification or categorization of data items. It represents


the kind of value that tells what operations can be performed on a particular
data. Since everything is an object in Python programming, data types are
classes and variables are instances (objects) of these classes.

Standard data types


The storage method for each of the standard data types that Python provides
is specified by Python. The following is a list of the Python-defined data types.

 Numbers
 Sequence Type
 Boolean
 Set
 Dictionary
Data types in Python
Data types in Python

Type() function:
To define the values ​of various data types and check their data types
we use the type() function. Which returns the type of the passed
variable.

Numeric Data Types in Python


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

Integers – This value is represented by int class. It contains positive or


negative whole numbers (without fractions or decimals). In Python, there is
no limit to how long an integer value can be.

Float – This value is represented by the float class. It is a real number with
a floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer
may be appended to specify scientific notation.

Complex Numbers – A complex number is represented by a complex class.


It is specified as (real part) + (imaginary part)j.
For example – 4+5j

Note – type() function is used to determine the type of data type.


Data types in Python

Example:
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))

Output:
Type of a: <class 'int’>

Type of b: <class 'float’>

Type of c: <class 'complex'>


Data types in Python

String:
Python Strings are identified as a contiguous set of characters represented
in the quotation marks. Python allows for either pairs of single or double
quotes. Subsets of strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and working their
way from -1 at the end.
The plus (+) sign is the string concatenation operator and the asterisk (*) is
the repetition operator in Python.
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string Output:
Hello World!
print (str[2:5]) # Prints characters starting from 3rd to 4th H
print (str[2:]) # Prints string starting from 3rd character llo
print (str * 2) # Prints string two times llo World!
Hello World!Hello
print (str + "TEST") # Prints concatenated string
World!
Hello World!TEST
Data types in Python

Python List Data Type


Python Lists are the most versatile compound data types. A Python
list contains items separated by commas and enclosed within
square brackets ([]). To some extent, Python lists are similar to
arrays in C. One difference between them is that all the items
belonging to a Python list can be of different data type where as C
array can store elements related to a particular data type.
The values stored in a Python list can be accessed using the slice
operator ([ ] and [:]) with indexes starting at 0 in the beginning of
the list and working their way to end -1.
The plus (+) sign is the list concatenation operator, and the asterisk
(*) is the repetition operator.
Data types in Python

List Example:
list = [ 'abcd', 786 , 2.23, ‘RKS', 70.2 ]
tinylist = [123, ' RKS ']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 1st till 2nd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2)
print (list + tinylist) Output:
['abcd', 786, 2.23, ‘RKS', 70.2]
abcd
[786, 2.23]
[2.23, ‘RKS', 70.2]
[123, ' RKS ', 123, ' RKS ']
['abcd', 786, 2.23, ' RKS ', 70.2, 123, 'RKS ']
Data types in Python

Python Tuple Data Type


Python tuple is another sequence data type that is similar to a list. A
Python tuple consists of a number of values separated by commas. Unlike
lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are enclosed in
brackets ( [ ] ) and their elements and size can be changed, while tuples
are enclosed in parentheses ( ( ) ) and cannot be updated. Tuples can be
thought of as read-only lists.
tuple = ( 'abcd', 786 , 2.23, 'RKS', 70.2 )
tinytuple = (123, 'RKS')
print (tuple)
Output −
('abcd', 786, 2.23, 'RKS', 70.2)
print (tuple[0])
abcd
print (tuple[1:3])
(786, 2.23)
print (tuple[2:])
(2.23, 'RKS', 70.2)
print (tinytuple * 2) (123, 'RKS', 123, 'RKS')
print (tuple + tinytuple) ('abcd', 786, 2.23, 'RKS', 70.2, 123, 'RKS')
Data types in Python

The following code is invalid with tuple, because we attempted to


update a tuple, which is not allowed. Similar case is possible with
lists −
tuple = ( 'abcd', 786 , 2.23, 'RKS', 70.2 )
list = [ 'abcd', 786 , 2.23, 'RKS', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list[2] = 1000 # Valid syntax with list

Difference b/w List and tuple


List and Tuple in Python are the classes of Python Data Structures.
The list is dynamic, whereas the tuple has static characteristics. This
means that lists can be modified whereas tuples cannot be
modified, the tuple is faster than the list because of static in
nature. Lists are denoted by the square brackets but tuples are
denoted as parenthesis.
Data types in Python
Data types in Python

Example:
List = [1, 2, 4, 4, 3, 3, 3, 6, 5]
print("Original list ", List) Output:

Original list [1, 2, 4, 4, 3, 3, 3, 6, 5]


List[3] = 77 Example to show mutability [1, 2, 4, 77, 3, 3, 3, 6, 5]
print("Example to show mutability ", List)
Data types in Python

Python Dictionary
Python dictionaries are kind of hash table type. They work like associative arrays or
hashes found in Perl and consist of key-value pairs. A dictionary key can be almost
any Python type, but are usually numbers or strings. Values can be any arbitrary
Python object. Dictionaries are enclosed by curly braces ({ }) and values can be
assigned and accessed using square braces ([]).
Output:
This is one
Example: This is two
dict = {} {'dept': 'CSA', 'code': 9020, 'name': 'RKS'}
dict['one'] = "This is one" ['dept', 'code', 'name']
dict[2] = "This is two" ['CSA', 9020, 'RKS']
tinydict = {'name': 'RKS','code':9020, 'dept': 'CSA'}
print (dict['one'])
print (dict[2])
print (tinydict)
print (tinydict.keys())
print (tinydict.values())
Note: Python dictionaries have no concept of order among elements. Simply, they are
unordered.
Data types in Python

Python Boolean Data Types


Python boolean type is one of built-in data types which represents
one of the two values either True or False. Python bool() function
allows you to evaluate the value of any expression and returns either
True or False based on the expression.

Examples
a = True
# display the value of a Output:
print(a) true
# display the data type of a <class 'bool'>
print(type(a))
Data types in Python

Example:
a=2
b=4
print(bool(a==b))
print(a==b)
Output:
a = None
False
print(bool(a)) False
a = () False
print(bool(a)) False
False
a = 0.0 True
print(bool(a))
a = 10
print(bool(a))
Data types in Python

Sets are used to store multiple items in a single variable.


A set is a collection which is unordered, unchangeable*, and unindexed.
Sets are written with curly brackets.
Note:
1. Set items are unchangeable, Once a set is created, you cannot change
its items, but you can remove items and add new items.
2. Sets are unordered, so you cannot be sure in which order the items
will appear.
3. Sets cannot have two items with the same value.
4. A set can contain different data types

Example:
set = {"apple", "banana", "cherry"}
print(set)
Data types in Python

Set items can be of any data type:


Example
String, int and boolean data types:
set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}
set3 = {True, False, False}

A set with strings, integers and boolean values:


set1 = {"abc", 34, True, 40, "male"}

Get the Length of a Set


To determine how many items a set has, use the len() function.
set = {"apple", "banana", "cherry"}
print(len(set))
Data types in Python

Duplicates Not Allowed


Sets cannot have two items with the same value.

Example
Duplicate values will be ignored:

set = {"apple", "banana", "cherry", "apple"}


print(set)
Data types in Python
Data types in Python

There are four collection data types in the Python


programming language:

 List is a collection which is ordered and changeable.


Allows duplicate members.
 Tuple is a collection which is ordered and unchangeable.
Allows duplicate members.
 Set is a collection which is unordered, unchangeable*,
and unindexed. No duplicate members.
 Dictionary is a collection which is ordered** and
changeable. No duplicate members.
Data types in Python
Data types in Python
Type Conversion in Python

Data Type Conversion:


Sometimes, you may need to perform conversions between the
built-in data types. To convert data between different Python data
types, you simply use the type name as a function.
Example1:
Conversion to int
a = int(1) # a will be 1 a = float(1) # a will be 1.0
b = int(2.2) # b will be 2 b = float(2.2) # b will be 2.2
c = int("3") # c will be 3 c = float("3.3") # c will be 3.3
print (a) print (a)
print (b)
print (b)
print (c)
print (c)
Type Conversion in Python

Data Type Conversion:


Type conversion is the process of converting data of one type to
another.
For example: converting int data to str.
There are two types of type conversion in Python.
 Implicit Conversion - automatic type conversion
 Explicit Conversion - manual type conversion

Implicit Type Conversion


In certain situations, Python automatically converts one data type to
another. This is known as implicit type conversion.

Converting integer to float


An example where Python promotes the conversion of the lower data
type (integer) to the higher data type (float) to avoid data loss .
Type Conversion in Python

Example:
int_num = 123 Output:
float_num = 1.23 Value: 124.23
new_num = int_num + float_num Data Type: <class 'float'>
# display new value and resulting data type
print("Value:",new_num)
print("Data Type:", type(new_num))

It is because Python always converts smaller data types to larger data


types to avoid the loss of data.
Note: We get TypeError, if we try to add str and int.
For example, '12' + 23. Python is not able to use Implicit Conversion in
such conditions.
Python has a solution for these types of situations which is known as
Explicit Conversion.
Type Conversion in Python

Explicit Type Conversion


In Explicit Type Conversion, users convert the data type of an object
to required data type.
Mainly type casting can be done with built-in functions like int(),
float(), str(), etc to perform explicit type conversion.

 Int(): Python Int() function take float or string as an argument and


returns int type object.
 float(): Python float() function take int or string as an argument
and return float type object.
 str(): Python str() function takes float or int as an argument and
returns string type object.
We use the This type of conversion is also called typecasting because
the user casts (changes) the data type of the objects.
Type Conversion in Python

Example:
num_string = '12'
num_integer = 23
print("Data type of num_string before Type Casting:",type(num_string))

# explicit type conversion


num_string = int(num_string)

print("Data type of num_string after Type Casting:",type(num_string))

num_sum = num_integer + num_string

print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Type Conversion in Python

Output:
Data type of num_string before Type Casting:
<class 'str'>
Data type of num_string after Type Casting:
<class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>

Key Points:
 Type Conversion is the conversion of an object from one data type to
another data type.
 Implicit Type Conversion is automatically performed by the Python
interpreter.
 Python avoids the loss of data in Implicit Type Conversion.
 Explicit Type Conversion is also called Type Casting, the data types of
objects are converted using predefined functions by the user.
 In Type Casting, loss of data may occur as we enforce the object to a
Python Operators
Operators in Python
In Python, operators are special symbols or keywords that carry out
operations on values and python variables. They serve as a basis for
expressions, which are used to modify data and execute computations.
Python contains several operators, each with its unique purpose.

Types of Python Operators


 Python language supports various types of operators, which are:
 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Python Operators
Arithmetic Operators
Python Arithmetic Operators
• Mathematical operations including addition, subtraction, multiplication,
and division are commonly carried out using Python arithmetic
operators.
• They are compatible with integers, variables, and expressions.
• In addition to the standard arithmetic operators, there are operators for
modulus, exponentiation, and floor division.
Arithmetic Operators
Example:
a = 21
b = 10
# Addition
print ("a + b : ", a + b) Output:
# Subtraction a + b : 31
print ("a - b : ", a - b) a - b : 11
# Multiplication a * b : 210
print ("a * b : ", a * b) a / b : 2.1
# Division a%b:1
print ("a / b : ", a / b)
a ** b : 16679880978201
# Modulus
a // b : 2
print ("a % b : ", a % b)
# Exponent
print ("a ** b : ", a ** b)
# Floor Division
print ("a // b : ", a // b)
Operators in Python

• Python Comparison Operators


• To compare two values, Python comparison operators are needed.
• Based on the comparison, they produce a Boolean value (True or
False).
Operators in Python

Example:
a=4
b=5
# Equal
print ("a == b : ", a == b) Output
a == b : False
# Not Equal a != b : True
print ("a != b : ", a != b) a > b : False
# Greater Than a < b : True
a >= b : False
print ("a > b : ", a > b)
a <= b : True
# Less Than
print ("a < b : ", a < b)
# Greater Than or Equal to
print ("a >= b : ", a >= b)
# Less Than or Equal to
print ("a <= b : ", a <= b)
Operators in Python

Python Assignment Operators


• Python assignment operators are used to assign values to variables in Python.
• The single equal symbol (=) is the most fundamental assignment operator.
• It assigns the value on the operator's right side to the variable on the operator's
left side.
Operators in Python

# Assignment Operator
a = 10
# Addition Assignment
a += 5
print ("a += 5 : ", a)
# Subtraction Assignment
a -= 5
print ("a -= 5 : ", a)
# Multiplication Assignment
a *= 5
print ("a *= 5 : ", a)
# Division Assignment
a /= 5
Output
print ("a /= 5 : ",a)
a += 5 : 15
# Remainder Assignment
a %= 3
a -= 5 : 10
print ("a %= 3 : ", a) a *= 5 : 50
# Exponent Assignment a /= 5 : 10.0
a **= 2 a %= 3 : 1.0
print ("a **= 2 : ", a) a **= 2 : 1.0
# Floor Division Assignment a //= 3 : 0.0
a //= 3
Operators in Python

4. Python Bitwise Operators


• Python bitwise operators execute operations on individual bits of binary integers.
• They work with integer binary representations, performing logical operations on
each bit location.
• Python includes various bitwise operators, such as AND (&), OR (|), NOT (),
XOR (), left shift (), and right shift (>>).
Operators in Python

a = 60 # 60 = 0011 1100
b = 13 # 13 = 0000 1101
# Binary AND
c = a & b # 12 = 0000 1100
print ("a & b : ", c)
# Binary OR
c = a | b # 61 = 0011 1101
print ("a | b : ", c)
# Binary XOR
c = a ^ b # 49 = 0011 0001
print ("a ^ b : ", c)
Output
# Binary Ones Complement
a & b : 12
c = ~a; # -61 = 1100 0011
a | b : 61
a ^ b : 49
print ("~a : ", c)
~a : -61
# Binary Left Shift
a >> 2 : 240
c = a << 2; # 240 = 1111 0000
a >> 2 : 15
print ("a << 2 : ", c)
# Binary Right Shift
c = a >> 2; # 15 = 0000 1111
print ("a >> 2 : ", c)
Operators in Python

5. Python Logical Operators


• Python logical operators are used to compose Boolean expressions and evaluate
their truth values.
• They are required for the creation of conditional statements as well as for
managing the flow of execution in programs.
• Python has three basic logical operators: AND, OR, and NOT.

Example:
x=5 Output
y = 10 Both x and y are within the specified range
if x > 3 and y < 15:
print("Both x and y are within the specified range")
Operators in Python

6. Python Membership Operators


• Python membership operators are used to determine whether or not a certain
value occurs within a sequence.
• They make it simple to determine the membership of elements in various data
structures such as lists, tuples, sets, and strings.
• Python has two primary membership operators: the in and not in operators.

Example:
fruits = ["apple", "banana", "cherry"]
if "banana" in fruits:
print("Yes, banana is a fruit!") Output
else: Yes, banana is a fruit!
print("No, banana is not a fruit!")
Operators in Python

7. Python Identity Operators


• Python identity operators are used to compare two objects' memory addresses
rather than their values.
• If the two objects refer to the same memory address, they evaluate to True;
otherwise, they evaluate to False.
• Python includes two identity operators: the is and is not operators.

Example:
x = 10
y=5
if x is y:
print("x and y are the same object")
Output
else:
x and y are not the same object
print("x and y are not the same object")
Operators in Python

You might also like