Data Type
Data Type
Data Type
Python Data Types are used to define the type of a variable. It defines what type of data we are going to
store in a variable. The data stored in memory can be of many types. For example, a person's age is stored
as a numeric value and his or her address is stored as alphanumeric characters.
Python has the following built-in data types are listed below:
Number: Number data type stores numerical values only. It is further classified into three different types:
int, float and complex.
Numeric data Types
1. 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.
2. 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.
3. Complex Numbers – A complex number is represented by a complex class. It is specified as (real
part) + (imaginary part) j. For example – 2+3j
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two constants,
True and False. Boolean True value is non-zero, non-null and non-empty. Boolean False is the value zero.
Executing few statements in interactive mode to determine the data type of the variable using built-in
function type().
>>> number1=30
>>> type(number1)
<class 'int'>
>>> number2=-100
>>> type(number2)
<class 'int'>
>>> number3=100.50
>>> type(number3)
<class 'float'>
>>> number4=-1000.50
>>> type(number4)
<class 'float'>
>>>
String: A string is a collection of one or more characters put in a single quote, double-quote, or triple-
quote. In Python, there is no character data type Python, a character is a string of length one. It is
represented by str class.
Example: This Python code showcases various string creation methods. It uses single quotes, double
quotes, and triple quotes to create strings with different content and includes a multiline string. The code
also demonstrates printing the strings and checking their data types.
String1 = '''Good
Morning
Boys & Girls'''
print("\nCreating a multiline String: ")
print(String1)
List: List is a sequence of items separated by commas and the items are enclosed in square brackets [ ].
Example
#To create a list
>>> list1 = [10, 25.4, "Bengaluru", "30C", 45]
#print the elements of the list list1
>>> print(list1)
[5, 3.4, 'New Delhi', '20C', 45]
Tuple: Tuple is a sequence of items separated by commas and items are enclosed in parenthesis ( ). This
is unlike list, where values are enclosed in brackets [ ]. Once created, we cannot change the tuple.
Example #create a tuple tuple1
>>> tuple1 = (15, 25, "Orange", 2.4, 'o')
#print the elements of the tuple
Set: Set is an unordered collection of items separated by commas and the items are enclosed in curly
brackets { }.
A set is similar to list, except that it cannot have duplicate entries. Once created, elements of a set cannot
be changed.
Example:
#create a set
>>> set1 = {10,20,3.14,"New Delhi"}
>>> print(type(set1))
<class ‘set’>
>>> print(set1)
{10, 20, 3.14, "New Delhi"}
#duplicate elements are not included in set
>>> set2 = {1,2,1,3}
>>> print(set2) {1, 2, 3}
None
None is a special data type with a single value. It is used to signify the absence of value in a situation.
None supports no special operations, and it is neither same as False nor 0 (zero).
Example 5.7
>>> myVar = None
>>> print(type(myVar))
<class 'NoneType'>
>>> print(myVar)
None
Mapping:
Mapping is an unordered data type in Python. Currently, the only standard mapping data type available in
Python is the dictionary.
In Python, a dictionary stores data in key-value pairs, enclosed within curly brackets {}. This structure
allows for quick data access. Each key is separated from its corresponding value by a colon (:). You can
access the values in a dictionary using their keys. Typically, keys are strings, while values can be any data
type. To retrieve a value, you specify its key within square brackets [].
Example 5.8
#create a dictionary
>>> dict1 = {'Fruit':'Orange',
'Climate':'hot', 'Price(kg)':140}
>>> print(dict1)
{'Fruit': 'Apple', 'Climate': 'Cold',
'Price(kg)': 140}
>>> print(dict1['Price(kg)'])
140
Sometimes, we may need to change or update the values of certain variables in a program. However, for
some data types, Python does not permit value changes once a variable of that type has been created and
assigned values.
Variables whose values can be changed after creation and assignment are called mutable. Variables
whose values cannot be changed after creation and assignment are called immutable. When an attempt is
made to update the value of an immutable variable, the old variable is discarded, and a new variable
with the same name is created in memory.
It is preferable to use lists when we need a simple iterable collection of data that may undergo frequent
modifications. For example, if we store the names of students in a class in a list, it is easy to update the
list when new students join or some leave the course.
Tuples are used when no changes to the data are needed, such as for the names of the months in a year.
When we need to ensure the uniqueness of elements and avoid duplicates, it is better to use sets, like a list
of artefacts in a museum.
OPERATORS
Operators perform specific mathematical or logical operations on values, known as operands. For
instance, in the expression 20 + number value, the value 10 and the variable number are operands,
while the + (plus) sign is an operator. Python supports various types of operators, which are briefly
categorized and explained in this section.
Arithmetic Operators
Comparison (Relational) Operators
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
The Python operators are fundamental for performing mathematical calculations in programming
languages like Python, Java, C++, and many others. Arithmetic operators are symbols used to perform
mathematical operations on numerical values. In most programming languages, arithmetic operators
include addition (+), subtraction (-), multiplication (*), division (/), and modulus (%).
In addition, Python defines few more arithmetic operators. They are "%" (Modulus), "**" (Exponent) and
"//" (Floor division).
Following is the table which lists down all the arithmetic operators available in Python:
This operator pronounced as plus, is a basic arithmetic operator. It adds the two numeric operands on the
either side and returns the addition result.
In the following example, the two integer variables are the operands for the "+" operator.
a=10
b=20
print ("Addition of two integers")
print ("a =",a,"b =",b,"addition =",a+b)
a=10
b=20.5
print ("Addition of integer and float")
print ("a =",a,"b =",b,"addition =",a+b)
It will produce the following output −
a=10+5j
b=20.5
print ("Addition of complex and float")
This operator, known as minus, subtracts the second operand from the first. The resultant number is
negative if the second operand is larger.
a=10
b=20
print ("Subtraction of two integers:")
print ("a =",a,"b =",b,"a-b =",a-b)
print ("a =",a,"b =",b,"b-a =",b-a)
Result −
a=10
b=20.5
print ("subtraction of integer and float")
print ("a=",a,"b=",b,"a-b=",a-b)
print ("a=",a,"b=",b,"b-a=",b-a)
It will produce the following output −
In the subtraction involving a complex and a float, real component is involved in the operation.
a=10+5j
b=20.5
print ("subtraction of complex and float")
print ("a=",a,"b=",b,"a-b=",a-b)
The * (asterisk) symbol is defined as a multiplication operator in Python (as in many languages). It
returns the product of the two operands on its either side. If any of the operands negative, the result is also
negative. If both are negative, the result is positive. Changing the order of operands doesn't change the
result
a=10
b=20
print ("Multiplication of two integers")
print ("a =",a,"b =",b,"a*b =",a*b)
a = 10 b = 20 a*b = 200
In multiplication, a float operand may have a standard decimal point notation, or a scientific notation.
a=10
b=20.5
print ("Multiplication of integer and float")
print ("a=",a,"b=",b,"a*b=",a*b)
a=-5.55
b=6.75E-3
print ("Multiplication of float and float")
print ("a =",a,"b =",b,"a*b =",a*b)
The "/" symbol is usually called as forward slash. The result of division operator is numerator (left
operand) divided by denominator (right operand). The resultant number is negative if any of the operands
is negative. Since infinity cannot be stored in the memory, Python raises ZeroDivisionError if the
denominator is 0.
The result of division operator in Python is always a float, even if both operands are integers.
a=10
b=20
print ("Division of two integers")
print ("a=",a,"b=",b,"a/b=",a/b)
print ("a=",a,"b=",b,"b/a=",b/a)
a= 10 b= 20 a/b= 0.5
a= 10 b= 20 b/a= 2.0
Example: Division With Float Numbers
In Division, a float operand may have a standard decimal point notation, or a scientific notation.
a=10
b=-20.5
print ("Division of integer and float")
print ("a=",a,"b=",b,"a/b=",a/b)
a=-2.50
b=1.25E2
print ("Division of float and float")
print ("a=",a,"b=",b,"a/b=",a/b)
It will produce the following output −
Python defines the "%" symbol, which is known aa Percent symbol, as Modulus (or modulo) operator. It
returns the remainder after the denominator divides the numerator. It can also be called Remainder
operator. The result of the modulus operator is the number that remains after the integer quotient. To give
an example, when 10 is divided by 3, the quotient is 3 and remainder is 1. Hence, 10%3 (normally
pronounced as 10 mod 3) results in 1.
If both the operands are integer, the modulus value is an integer. If numerator is completely divisible,
remainder is 0. If numerator is smaller than denominator, modulus is equal to the numerator. If
denominator is 0, Python raises ZeroDivisionError.
a=10
b=2
print ("a=",a, "b=",b, "a%b=", a%b)
a=10
b=4
print ("a=",a, "b=",b, "a%b=", a%b)
print ("a=",a, "b=",b, "b%a=", b%a)
a=0
b=10
print ("a=",a, "b=",b, "a%b=", a%b)
print ("a=", a, "b=", b, "b%a=",b%a)
It will produce the following output −
a= 10 b= 2 a%b= 0
a= 10 b= 4 a%b= 2
a= 10 b= 4 b%a= 4
a= 0 b= 10 a%b= 0
a=10
b=2.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=10
b=1.5
print ("a=",a, "b=",b, "a%b=", a%b)
a=7.7
b=2.5
print ("a=",a, "b=",b, "a%b=", a%b)
Python uses ** (double asterisk) as the exponent operator (sometimes called raised to operator). So, for
a**b, you say a raised to b, or even bth power of a.
If in the exponentiation expression, both operands are integer, result is also an integer. In case either one
is a float, the result is float. Similarly, if either one operand is complex number, exponent operator returns
a complex number.
If the base is 0, the result is 0, and if the index is 0 then the result is always 1.
a=10
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=10
b=1.5
print ("a=",a, "b=",b, "a**b=", a**b)
a=7.7
b=2
print ("a=",a, "b=",b, "a**b=", a**b)
a=1+2j
b=4
print ("a=",a, "b=",b, "a**b=", a**b)
a=12.4
b=0
print ("a=",a, "b=",b, "a**b=", a**b)
print ("a=",a, "b=",b, "b**a=", b**a)
a= 10 b= 2 a**b= 100
a= 10 b= 1.5 a**b= 31.622776601683793
a= 7.7 b= 2 a**b= 59.290000000000006
a= (1+2j) b= 4 a**b= (-7-24j)
a= 12.4 b= 0 a**b= 1.0
a= 12.4 b= 0 b**a= 0.0
Floor division is also called as integer division. Python uses // (double forward slash) symbol for the
purpose. Unlike the modulus or modulo which returns the remainder, the floor division gives the quotient
of the division of operands involved.
If both operands are positive, floor operator returns a number with fractional part removed from it. For
example, the floor division of 9.8 by 2 returns 4 (pure division is 4.9, strip the fractional part, result is 4).
But if one of the operands is negative, the result is rounded away from zero (towards negative infinity).
Floor division of -9.8 by 2 returns 5 (pure division is -4.9, rounded away from 0).
a=9
b=2
print ("a=",a, "b=",b, "a//b=", a//b)
a=9
b=-2
print ("a=",a, "b=",b, "a//b=", a//b)
a=10
b=1.5
print ("a=",a, "b=",b, "a//b=", a//b)
a=-10
b=1.5
print ("a=",a, "b=",b, "a//b=", a//b)
a= 9 b= 2 a//b= 4
a= 9 b= -2 a//b= -5
a= 10 b= 1.5 a//b= 6.0
a= -10 b= 1.5 a//b= -7.0
Python uses two more operators, combining "=" symbol with these two. The "<=" symbol is for less than
or equal to operator and the ">=" symbol is for greater than or equal to operator.
Example
Comparison operators are binary in nature, requiring two operands. An expression involving a
comparison operator is called a Boolean expression, and always returns either True or False.
Example
a=5
b=7
print (a>b)
print (a<b)
It will produce the following output −
False
True
Both the operands may be Python literals, variables or expressions. Since Python supports mixed
arithmetic, you can have any number type operands.
Example
The following code demonstrates the use of Python's comparison operators with integer numbers −
a=5
b=7
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)
It will produce the following output −
a= 5 b= 7 a>b is False
a= 5 b= 7 a<b is True
a= 5 b= 7 a==b is False
a= 5 b= 7 a!=b is True
Example
a=10
b=10.0
print ("a=",a, "b=",b," Comparison operators are binary in nature, requiring two operands. An expression
involving a comparison operator is called a Boolean expression, and always returns either True or False.
Example
a=5
b=7
print (a>b)
print (a<b)
It will produce the following output −
False
True
Both the operands may be Python literals, variables or expressions. Since Python supports mixed
arithmetic, you can have any number type operands.
Example
The following code demonstrates the use of Python's comparison operators with integer numbers −
a=5
b=7
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)
It will produce the following output −
a= 5 b= 7 a>b is False
a= 5 b= 7 a<b is True
a= 5 b= 7 a==b is False
a= 5 b= 7 a!=b is True
Comparison of Float Number
Example
a=10
b=10.0
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)
It will produce the following output −
False
True
Both the operands may be Python literals, variables or expressions. Since Python supports mixed
arithmetic, you can have any number type operands.
Example
The following code demonstrates the use of Python's comparison operators with integer numbers −
a=5
b=7
print ("a=",a, "b=",b, "a>b is", a>b)
print ("a=",a, "b=",b,"a<b is",a<b)
print ("a=",a, "b=",b,"a==b is",a==b)
print ("a=",a, "b=",b,"a!=b is",a!=b)
It will produce the following output −
ASSIGNMENT OPERATORS
The Python Operators are used to perform operations on values and variables. These are the special
symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is
known as the Operand. Here, we will cover Different Assignment operators in Python.
a = 10
b=5
a=a+b
print (a)
At the first instance, at least for somebody new to programming but who knows maths, the statement
"a=a+b" looks strange. How could a be equal to "a+b"? However, it needs to be reemphasized that the =
symbol is an assignment operator here and not used to show the equality of LHS and RHS.
Because it is an assignment, the expression on right evaluates to 15, the value is assigned to a.
In the statement "a+=b", the two operators "+" and "=" can be combined in a "+=" operator. It is called as
add and assign operator. In a single statement, it performs addition of two operands "a" and "b", and
result is assigned to operand on left, i.e., "a".
= Assigns value from the right side operand to left side operand.
>>>num1=100
>>>num2=num1
>>>num2
Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 16
>>>city=’Bengaluru’
>>>city
LOGICAL OPERATORS
Python logical operators are used to form compound Boolean expressions. Each operand for these logical
operators is itself a Boolean expression. For example,
Along with the keyword False, Python interprets None, numeric zero of all types, and empty sequences
(strings, tuples, lists), empty dictionaries, and empty sets as False. All other values are treated as True.
There are three logical operators in Python. They are "and", "or" and "not". They must be in
lowercase.
PYTHON IS OPERATOR
The is operator evaluates to True if the variables on either side of the operator point to the same object in
the memory and false otherwise.
Example: In this code we take two integers, strings. Then used the ‘is’ operator to check each data type’s
identity.
>>>number =100
>>>type(number1) is int
True
>>>number2=number1
>>>id(number1)
1433920576 [memory Address]
>>>id(number2)
1433920576
>>>number1 is number2
True
>>> str1=”Good”
>>>str2=”Good”
>>str1 is str2
True
Example: In this code we take two integers, lists and strings. Then used the ‘is not’ operator to check each
data type’s identity.
>>> number1=200
>>> number2=200
>>> number1 is not number2
False
MEMBERSHIP OPERATORS
Membership operators are operators used to validate the membership of a value. It test for membership in
a sequence, such as strings, lists, or tuples.
Python has two membership operators: in and not in. Both return a Boolean result. The result
of in operator is opposite to that of not in operator
PYTHON IN OPERATOR
The in operator is used to check if a character/substring/element exists in a sequence or not. Evaluate to
True if it finds the specified element in a sequence otherwise False .
Example:
>>> n=[10,20,30]
>>> 30 in n
True
>>> n=[10,20,30]
>>> ‘30’ in n
False
EXPRESSIONS
An expression is a combination of constants, variables, and operators that always evaluates to a value.
Both a value and a standalone variable qualify as expressions, while a standalone operator does not. Here
are some examples of valid expressions:
Precedence of Operators
The evaluation of an expression depends on the precedence of its operators. When an expression includes
different types of operators, precedence dictates the order in which the operators are applied, with higher
precedence operators being evaluated before those with lower precedence.
Most of the operators discussed so far are binary operators, which operate on two operands.
Unary operators, which require only one operand, have higher precedence than binary operators.
The minus (-) and plus (+) operators can function as both unary and binary operators. Additionally, the
"not" operator is a unary logical operator.
Arithmetic Operators: From highest to lowest precedence, these are ** (exponential), * (multiplication),
/ (division), + (addition), - (subtraction).
Comparison Operators: These include == (equal), != (not equal), <= (less than or equal to), >= (greater
than or equal to), < (less than), > (greater than).
Logical Operators: not has the highest precedence, followed by and, and then or.
Assignment Operators: The assignment operator = is used to set values, while += and -= are compound
assignment operators that perform an operation and an assignment in a single step.
The order of precedence in Python is not just arbitrary; it's designed to minimize ambiguity in
expressions, offering a clear path for execution, which becomes crucial in complex programming
scenarios.
Parentheses (): Anything in parentheses is evaluated first, offering you a way to override other
precedence rules.
Multiplication and Division *, /: These are processed from left to right. They have the same level of
precedence, which is where the left-to-right rule comes in.
Addition and Subtraction +, -: These are the last to be performed, also from left to right .
STATEMENT
In Python, a statement is a unit of code that the Python interpreter can execute.
Example:
The input function in Python is a powerful tool for interacting with users and collecting data from the
keyboard during program execution. Whether you’re creating a simple command-line application or
building a complex software system, the input() function allows you to gather user input and make your
programs more interactive and dynamic.
The input function is a built-in function in Python that allows developers to read data from the user. The
input function in python reads the input as a string, which can then be converted into other data types,
such as integers, floating-point numbers, or booleans.
The syntax of the input function in python is straightforward. It takes a single argument, which is the
message to be displayed to the user.
input([prompt])
The input() takes exactly what is typed from the keyboard, converts it into a string and assigns it to the
variable on left-hand side of the assignment operator (=). Entering data for the input function is
terminated by pressing the enter key.
Python uses the print() function to output data to the standard output device—the screen. We will learn
about functions in Chapter 7. The print() function evaluates the expression before displaying it on the
screen. It outputs a complete line and then moves to the next line for subsequent output. The syntax for
print() is:
python
Copy code
print(value [, ..., sep=' ', end='\n'])
sep: The optional parameter sep acts as a separator between the output values. You can use a character,
integer, or string as a separator. The default separator is a space.
end: This optional parameter allows you to specify a string to be appended after the last value. The default
is a new line.
Example:
Print(“Good morning”) Good morning
Print(10*2.5) 25.0
Print(“Good”+”morning”+”Friends” GoodmorningFriends
Type conversion in Python refers to the direct conversion of object of one data type to another data type.
In this conversion, Python interpreter automatically performs conversion.
In Python, we have the flexibility to convert one data type to another using a specific function. On top of
that, we do not need to explicitly define the data type while declaring variables unlike other programming
languages like C++ and Java.
IMPLICIT TYPE CONVERSION: Implicit conversion, also known as coercion, happens when data type
conversion is done automatically by Python. Users don’t have to involve in this process.
#Program 5-10
#Implicit type conversion from int to float
num1 = 20 #num1 is an integer
num2 = 30.0 #num2 is a float
sum1 = num1 + num2 #sum1 is sum of a float
and an integer
print(sum1)
print(type(sum1))
Output: 50.0
In the example above, an integer value stored in the variable num1 is added to a float value stored in the
variable num2. The result is automatically converted to a float and stored in the variable sum1, without
any explicit instruction to the interpreter.
This process is known as implicit data conversion. You might wonder why the float value wasn't
converted to an integer instead. This is due to type promotion, which allows operations to be performed
by converting data to a wider data type when possible, ensuring no loss of information.
EXPLICIT TYPE CONVERSION: In Explicit type conversion, we manually alter the datatype of a Python
object to suit our purpose. For this, we make use of various in-built functions. It is also important to note
that, since we forcefully change the data type of the object, there is some risk of data loss.
(new_data_type) (expression)
Function Description
int(x) Converts x to an integer
float(x) Converts x to a floating-point number
str(x) Converts x to a string representation
chr(x) Converts ASCII value of x to character
Ord(x) Returns the character associated with the ASCII code x
price = int(icecream)+int(chacholate)
print("Total Price Rs." + str(price))
Output:
Total Price Rs.2545
Total Price Rs.70
DEBUGGING
Programmers often make mistakes while writing a program, which can prevent the program from
executing correctly or cause it to generate incorrect output. The process of identifying and removing these
mistakes, also known as bugs or errors, is called debugging. Errors that occur in programs can be
following types.
i) Syntax errors
ii) Logical errors
iii) Runtime errors
Syntax Errors
Like other programming languages, Python has specific rules that determine its syntax. The interpreter
can only interpret statements that are syntactically correct according to these rules. If there is a syntax
error, the interpreter displays an error message and stops execution. For example, parentheses must be in
pairs; the expression (11 + 14) is syntactically correct, whereas (17 + 12 is not due to the missing right
parenthesis. These errors must be corrected before the program can be executed.
Logical Errors
A logical error is a bug in the program that causes it to behave incorrectly. Unlike syntax errors, logical
errors do not cause the program to abruptly terminate; instead, they produce undesired output. Since the
program executes successfully even with logical errors, identifying these errors can be challenging. The
only clue to their presence is the incorrect output. By working backwards from the output, one can
determine what went wrong.
For example, if we want to find the average of two numbers, 10 and 12, and write the code as 10 + 12 /
2, the program will run successfully and produce the result 16. However, 16 is not the average of 10 and
12. The correct code to find the average should be (10 + 12) / 2, which yields the correct output of 11.
Logical errors are also called semantic errors because they occur when the meaning of the program (its
semantics) is incorrect.
Runtime Error
A runtime error causes the program to terminate abnormally while it is executing. These errors occur
when a statement is syntactically correct, but the interpreter cannot execute it. Runtime errors do not
become apparent until the program starts running.
For example, consider a statement involving a division operation. If the denominator is mistakenly
entered as zero, the program will produce a runtime error, such as "division by zero."
#Program 5-11
#Runtime Errors Example
num1 = 10.0
num2 = int(input("num2 = "))
#if user inputs a string or a zero, it leads
to runtime error
print(num1/num2