Data Type

Download as pdf or txt
Download as pdf or txt
You are on page 1of 26

DATA TYPES IN PYTHON

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'>
>>>

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 1


SEQUENCE DATA TYPES IN PYTHON
The sequence Data Type in Python is the ordered collection of similar or different Python data types.
Sequences allow storing of multiple values in an organized and efficient fashion. There are several
sequence data types of Python:
 Python String
 Python List
 Python Tuple

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 = 'Welcome to the Python World'


print("String with the use of Single Quotes: ")
print(String1)
String1 = "I'm a Python"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
String1 = '''I'm a Python and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))

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

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 2


tuple1 >>> print(tuple1) (15, 25, "Orange", 2.4, 'o')

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

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 3


Mutable and Immutable Data Types

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.

Differences between Mutable and Immutable data types

Examples Required Here

Deciding Usage of Python Data Types

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.

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 4


If our data is constantly being modified, requires fast lookup based on custom keys, or involves a logical
association between key-value pairs, dictionaries are advised. A mobile phone book is a good example of
a dictionary in use.

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.

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 ARITHMETIC 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).

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 5


DIFFERENT ARITHMETIC OPERATORS IN PYTHON

Following is the table which lists down all the arithmetic operators available in Python:

Addition Operator (+)

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.

Example: Addition of Two Integers

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)

It will produce the following output −

Addition of two integers


a = 10 b = 20 addition = 30
Example: Addition of Integer and Float Numbers
Addition of integer and float results in a float.

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 −

Addition of integer and float


a = 10 b = 20.5 addition = 30.5

Example: Addition of Two Complex Numbers

The result of adding float to complex is a complex number.

a=10+5j
b=20.5
print ("Addition of complex and float")

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 6


print ("a=",a,"b=",b,"addition=",a+b)
It will produce the following output −

Addition of complex and float


a= (10+5j) b= 20.5 addition= (30.5+5j)

Subtraction Operator (-)

This operator, known as minus, subtracts the second operand from the first. The resultant number is
negative if the second operand is larger.

Example: Subtraction of Two Integers

First example shows subtraction of two integers.

 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 −

Subtraction of two integers


a = 10 b = 20 a-b = -10
a = 10 b = 20 b-a = 10
Example: Subtraction of Integer and Float Numbers
Subtraction of an integer and a float follows the same principle.

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 −

subtraction of integer and float


a= 10 b= 20.5 a-b= -10.5
a= 10 b= 20.5 b-a= 10.5

Example: Subtraction of Two Complex Numbers

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)

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 7


print ("a=",a,"b=",b,"b-a=",b-a)
It will produce the following output −

subtraction of complex and float


a= (10+5j) b= 20.5 a-b= (-10.5+5j)
a= (10+5j) b= 20.5 b-a= (10.5-5j)

Multiplication Operator (*)

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

Example: Multiplication of Two Integers

a=10
b=20
print ("Multiplication of two integers")
print ("a =",a,"b =",b,"a*b =",a*b)

It will produce the following output :

Multiplication of two integers

a = 10 b = 20 a*b = 200

Example: Multiplication of Integer and Float Numbers

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)

It will produce the following output :

Multiplication of integer and float

a = 10 b = 20.5 a-b = -10.5

Multiplication of float and float

a = -5.55 b = 0.00675 a*b = -0.037462499999999996

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 8


Division Operator (/)

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.

Example: Division of Two 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)

It will produce the following output −

Division of two integers

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 −

Division of integer and float


a= 10 b= -20.5 a/b= -0.4878048780487805
Division of float and float
a= -2.5 b= 125.0 a/b= -0.02
a=0
b=2.5
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= 0 b= 2.5 a/b= 0.0


Traceback (most recent call last):
File "C:\Users\mlath\examples\example.py", line 20, in <module>
print ("a=",a,"b=",b,"b/a=",b/a)

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 9


~^~
ZeroDivisionError: float division by zero

Modulus Operator (%)

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.

Example: Modulus Operation With Integer Values

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

ZeroDivisionError: integer modulo by zero

Example: Modulus Operation With Float Values

If any of the operands is a float, the mod value is always float.

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)

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 10


a=12.4
b=3
print ("a=",a, "b=",b, "a%b=", a%b)
It will produce the following output −

a= 10 b= 2.5 a%b= 0.0


a= 10 b= 1.5 a%b= 1.0
a= 7.7 b= 2.5 a%b= 0.20000000000000018
a= 12.4 b= 3 a%b= 0.40000000000000036
Python doesn't accept complex numbers to be used as operand in modulus operation. It throws TypeError:
unsupported operand type(s) for %.

Exponent Operator (**)

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.

Example of Exponent Operator

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)

It will produce the following output −

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

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 11


Floor Division Operator (//)

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).

Example of Floor Division Operator

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)

It will produce the following output −

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 RELATIONAL OPERATORS


Comparison operators in Python are very important in Python's conditional statements (if, else and elif)
and looping statements (while and for loops). The comparison operators also called relational operators.
Some of the well-known operators are "<" stands for less than, and ">" stands for greater than operator.

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.

DIFFERENT COMPARISON OPERATORS IN PYTHON


Python has two more comparison operators in the form of "==" and "!=". They are for is equal to and is
not equal to operators. Hence, there are six comparison operators in Python and they are listed below in
this table:

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 12


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

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 −

print ("Both operands are integer")

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 −

Both operands are integer

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

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 13


Comparison of Float Number

In the following example, an integer and a float operand are compared.

Example

print ("comparison of int and float")

a=10

b=10.0

print ("a=",a, "b=",b, "a>b is", a>b)

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 −

print ("Both operands are integer")

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 −

Both operands are integer

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

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 14


In the following example, an integer and a float operand are compared.

Example

print ("comparison of int and float")

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 −

comparison of int and float


a= 10 b= 10.0 a>b is False
a= 10 b= 10.0 a<b is False
a= 10 b= 10.0 a==b is True
a= 10 b= 10.0 a!=b is False
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 −

comparison of int and float

a= 10 b= 10.0 a>b is False


a= 10 b= 10.0 a<b is False
a= 10 b= 10.0 a==b is True
a= 10 b= 10.0 a!=b is False
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 −

print ("Both operands are integer")

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 −

Both operands are integer

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 15


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
In the following example, an integer and a float operand are compared.
Example

print ("comparison of int and float")


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 −

comparison of int and float

a= 10 b= 10.0 a>b is False


a= 10 b= 10.0 a<b is False
a= 10 b= 10.0 a==b is True
a= 10 b= 10.0 a!=b is False

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.

EXAMPLE OF ASSIGNMENT OPERATOR IN PYTHON


Consider following Python statements −

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.

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 17


IDENTITY OPERATORS
The Python Identity Operators are used to compare the objects if both the objects are actually of the same
data type and share the same memory location. There are different identity operators such as:

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.

Example based on integers

>>>number =100
>>>type(number1) is int
True
>>>number2=number1
>>>id(number1)
1433920576 [memory Address]
>>>id(number2)
1433920576
>>>number1 is number2
True

Example based on Strings

>>> str1=”Good”
>>>str2=”Good”
>>str1 is str2
True

PYTHON IS NOT OPERATOR


The is not operator evaluates True if both variables on the either side of the operator are not the same
object in the memory location otherwise it evaluates False.

Example: In this code we take two integers, lists and strings. Then used the ‘is not’ operator to check each
data type’s identity.

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 18


Example

>>> 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.

TYPES OF PYTHON MEMBERSHIP OPERATORS

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

PYTHON NOT IN OPERATOR


The ‘not in’ Python operator evaluates to true if it does not find the variable in the specified sequence and
false otherwise.
>>> n=[10,20,30]
>>> 40 not in n
True
>>> 10 not 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:

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 19


100 20.0+23.5
number 23/3 -5 * 7(14 -2)
Number + 20 "Good" + "Citizen"

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.

Bitwise Operators: Bitwise AND &, OR |, and XOR ^.

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.

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 20


PYTHON OPERATORS PRECEDENCE RULE – PEMDAS
PEMDAS stands for Parentheses, Exponents, Multiplication and Division, and Addition and Subtraction.
This acronym serves as a useful mnemonic to remember the order of operations in Python. Understanding
PEMDAS is a must for any Python programmer who wants to write error-free code. Let's look at each
component:

Parentheses (): Anything in parentheses is evaluated first, offering you a way to override other
precedence rules.

Exponents **: Exponential calculations are performed next.

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:

>>> x = 400 #assignment statement


>>> cube = x ** 3 #assignment statement
>>> print (x, cube) #print statement
4 64

INPUT AND OUTPUT

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.

INPUT FUNCTION IN PYTHON

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.

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 21


SYNTAX OF INPUT FUNCTION IN PYTHON

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])

PARAMETERS OF INPUT FUNCTION IN PYTHON

It will take only a single argument which is optional.


*prompt: it is a string that is written with respect to standard output without going into a new line.

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.

name = input("Please Enter Your Name: ")


stno= input("Please Enter Student Number ")

#function int() to convert string to integer

>>> age = int( input("Enter your age:"))


Enter your age:20
>>> type(age)
<class 'int'>

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

Print(“Iam”, 17, ”years old” Iam 17 years old

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 22


TYPE CONVERSION

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.

Python has two types of data type conversions: [Type Casting]

1. Implicit Type Conversion


2. Explicit Type Conversion

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.

The general form of an explicit data type conversion is:

(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

Program: Program of explicit type conversion from


Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 23
int to float.
#Program 5-5
#Explicit type conversion from int to float
num1 = 40
num2 = 30
num3 = num1 + num2
print(num3)
print(type(num3))
num4 = float(num1 + num2)
print(num4)
print(type(num4))
Output:
70
<class 'int'>
70.0
<class 'float'>

Program explicit type conversion from


float to int.
#Explicit type conversion from float to int
num1 = 10.2
num2 = 30.6
num3 = (num1 + num2)
print(num3)
print(type(num3))
num4 = int(num1 + num2)
print(num4)
print(type(num4))
Output:
40.8
<class 'float'>
40
<class 'int' >

Program Program to show explicit type casting.


#Explicit type casting
priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total in Rs." + str(totalPrice))
Output:
The total in Rs.70
Similarly, type casting is needed to convert float to string. In Python, one can convert string to integer or
float values whenever required.
Program 5-9 Program to show explicit type conversion.
#Program 5-9
#Explicit type conversion
icecream = '25'
chacholate = '45'
#String concatenation
price = icecream + chacholate

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 24


print("Total Price Rs." + price)
#Explicit type conversion - string to integer

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."

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 25


Let's examine a program that demonstrates two types of runtime errors: one when the user enters a non-
integer value, and another when the value entered is '0'. The program generates the correct output when
the user inputs an integer value for num2.

Program Example of a program which generates runtime error.

#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

Data types in PYTHON – Mohan C HOD, Dept. Of Computer Sci. Page 26

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy