School of Computer Engineering
Course Name : Data Visualization
Credits :2
Semester : II
Academic Year : 2025-2026
Course Co-ordinator: Dr. S. Priya
INTRODUCTION
• Why data is important?
• Why data visualization is important?
Course Co-ordinator: Dr. S. Priya
SYLLABUS
SYLLABUS
• Introduction, Data Visualization basics: importance of context, effective
visuals and storytelling. Python Language Basics: Python Interpreter,
Input-Output, Identifiers and keywords, Conditional Statements and
Looping, Strings. Built-in Data Structures, Functions and Files: Tuple, List,
Dictionary, Sets, Functions, Modules and packages. NumPy basics: Arrays
and vectorised computation. Pandas basics: series, data frame, indexing.
Data Loading, storage and file formats: read and write files. Data
cleaning: missing values, data transforms, discretization and binning,
outliers, permutation and random sampling. String manipulation, regular
expressions. Data Wrangling: Join, combine, reshaping and pivoting.
Plotting and Visualization: Matplotlib basics, figures and subplots, basic
plots-line, bar, histogram, density plots, scatter, facet grids and categorical
data, Data Aggregation and Group operations: group summary statistics,
linear regression, rank, or subset selection, pivot tables and cross-
tabulations. Case study.
Course Co-ordinator: Dr. S. Priya
Course Outcomes
CO Level of learning
Course Outcomes
Nos. domain
Demonstrate ability to program in Python using built-
CO1 in data structures K3
Perform vectorized computation with Pandas and
CO2 NumPy K3
Implement wrangling, aggregation and summarisation
CO3 of data K3
Develop insightful visualizations using Matplotlib and
CO4 Seaborn K3
Apply data summarization and visualization techniques
CO5 to write reports K3
Course Co-ordinator: Dr. S. Priya
Textbooks:
• Wes McKinney , Python for Data Analysis: Data Wrangling
with pandas, NumPy & Jupyter. 3rd edition. O’Reilly Media,
2022.
• Cole Nussbaumer Knaflic, Storytelling With Data: A Data
Visualization Guide for Business Professionals, John Wiley and
Sons, 2015.
• Jake VanderPlas, Python Data Science Handbook. O'Reilly
Media, 2016.
• Alberto Boschetti and Luca Massaron, Python Data Science
Essentials, 3rd edition, Packt Publishing Ltd. 2018.
• Manaranjan Pradhan, U Dinesh Kumar, “Machine Learning
using Python”, Wiley India, 2019.
Course Co-ordinator: Dr. S. Priya
Introduction to Python Programming
What is Python?
• Python is a general purpose, high level,
interpreted language with easy syntax and
dynamic semantics.
• Created by Guido Van Rossum in 1989
Course Co-ordinator: Dr. S. Priya
Introduction to Python Programming
• Free and open-source
• Easy to learn
• Portable
Why Python?
• Different platforms
• Simple syntax
• Interpreter system
• Treated in a procedural or object-oriented or functional way.
Course Co-ordinator: Dr. S. Priya
Python Syntax compared to other programming
languages
• New lines to complete a command
• indentation
Python is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.
Course Co-ordinator: Dr. S. Priya
How to Install Python IDE
• Integrated Development Environment:
• Thonny
• Pycharm
• Netbeans or Eclipse
• Web Application
• Jupyter
• Google Colab
Course Co-ordinator: Dr. S. Priya
[Link] Syntax in Python
Syntax:
✓ The set of rules / structure which defines how a Python program will
be written.
✓ Designed to be a highly readable language.
Basic Syntax:
✓ Python statement ends with the token NEWLINE character.
✓ Backslash character \ to join a statement span over multiple lines.
✓Expressions in parentheses (), square brackets [ ], or curly braces {
} can be spread over multiple lines without using backslashes.
Course Co-ordinator: Dr. S. Priya
Indentation in Python
Indentation
✓ Indentation refers to the spaces at the beginning of a code line.
✓ Python uses indentation to indicate a block of code.
Indentation Rules
✓ Use the colon : to start a block and press Enter.
✓ All the lines in a block must use the same indentation, either space
or a tab.
✓ A block can have inner blocks with next level indentation.
Course Co-ordinator: Dr. S. Priya
Comments in Python
COMMNETS IN PYTHON
✓ Used to explain python code.
✓ Used to make the code more readable.
✓ Used to prevent execution when testing code.
✓ Any line starting with a # symbol, the Python interpreter will ignore them.
✓ Does not really have a syntax for multi line comments.
✓ To add a multiline comment you could insert a # for each line.
✓ Since Python will ignore string literals that are not assigned to a variable,
you can add a multiline string (triple quotes) in your code, and place your
comment inside it.
Course Co-ordinator: Dr. S. Priya
Python Naming Conventions
• Identifiers in Python are case sensitive
• Class names should use the TitleCase convention
• Function names should be in lowercase.
• Variable names in the function should be in lowercase
• Module and package names should be in lowercase
• Constant variable names should be in uppercase
• Two leading and trailing underscores are used in Python itself for a
special purpose
Course Co-ordinator: Dr. S. Priya
Display Output
The print() serves as an output statement in Python.
Multiple values can be displayed by the single print() function
separated by comma.
Course Co-ordinator: Dr. S. Priya
Getting User's Input
GETTING USER INPUT
• The input() function is a part of the core library of standard Python
distribution.
The type() function used earlier confirms this behavior.
Course Co-ordinator: Dr. S. Priya
Keywords in Python
KEYWORDS IN PYTHON
✓ Keywords are the reserved words in Python.
✓ Keywords are case sensitive.
Course Co-ordinator: Dr. S. Priya
[Link]
✓ Variables are containers for storing data values.
✓ Unlike other programming languages, Python has no command for
declaring a variable.
✓ A variable is created the moment you first assign a value to it.
✓ Variables created inside a function is normally local, and can only be
used inside that function.
✓ To create a global variable inside a function, you can use
the global keyword.
Course Co-ordinator: Dr. S. Priya
Assigning multiple values to multiple variables
Assigning multiple values to multiple variables
Constants
• A constant is a type of variable whose value cannot be changed.
Unpack a Collection
• If you have a collection of values in a list, tuple etc. Python allows
you extract the values into variables. This is called unpacking.
Course Co-ordinator: Dr. S. Priya
Rules for naming Variables
Rules for naming Variables
✓ A variable name must start with a letter or the underscore character
✓ A variable name cannot start with a number
✓ A variable name can only contain alpha-numeric characters and
underscores (A-z, 0-9, and _ )
✓ Variable names are case-sensitive (age, Age and AGE are three
different variables)
Course Co-ordinator: Dr. S. Priya
Literals
LITERALS
✓ Literal is a raw data given in a variable or constant.
Numeric Literals
✓ Numeric Literals are immutable
✓ Integer, Float, and Complex
String literals
✓ Single Line String Literal
✓ Character Literal
✓ Multi-Line String Literal
Boolean literals
✓ True, False
Special literals None Course Co-ordinator: Dr. S. Priya
Immutable Vs Mutable Variables
Immutable Vs Mutable Variables
✓ Immutable Variables - An immutable object can't be changed after it
is created. In-built types like int, float, bool, string, unicode, tuple.
✓ Mutable Variables - An mutable object can be changed after it is
created. These are of type list, dict, set.
Course Co-ordinator: Dr. S. Priya
Course Co-ordinator: Dr. S. Priya
Aliasing Vs Cloning
✓ Aliasing - Variables refer to objects and if we assign one variable to
another, both variables refer to the same object.
✓ Cloning - If we want to modify a list and also keep a copy of the
original, we need to make a copy of the list.
Course Co-ordinator: Dr. S. Priya
type() ?
✓ All data is stored in the form of an object. An object has three
things: id, type, and value.
✓ The type function will provide the type of the object that’s provided
as its argument.
Course Co-ordinator: Dr. S. Priya
Data types in Python
• The data stored in memory can be of many types.
• Python has various standard data types that are used to
define the operations possible on them and the storage
method for each of them.
• Python has five standard data types −
• Numbers
• String
• List
• Tuple
• Dictionary
Course Co-ordinator: Dr. S. Priya
Python Numbers
• Number data types store numeric values. Number objects are
created when you assign a value to them. For example −
var1 = 1
var2 = 10
• You can also delete the reference to a number object by using
the del statement.
del var
del var_a, var_b
• Python supports three different numerical types −
– int (signed integers)
– float (floating point real values)
– complex (complex numbers)
Course Co-ordinator: Dr. S. Priya
Python Strings
• Strings in Python are identified as a contiguous set of
characters represented in the quotation marks.
• Python allows either pair 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 to the end.
Course Co-ordinator: Dr. S. Priya
Python Strings
str = 'Hello World!'
print (str) # Prints complete string
print (str[0]) # Prints first character of the string
print (str[2:5]) # Prints characters starting from 3rd to 5th
print (str[2:]) # Prints string starting from 3rd character
print (str * 2) # Prints string two times
print (str + "TEST") # Prints concatenated string
[Link]
Course Co-ordinator: Dr. S. Priya
Python Lists
• A list contains items separated by commas and enclosed
within square brackets ([]).
• To some extent, lists are similar to arrays in C.
• One of the differences between them is that all the items
belonging to a list can be of different data type.
• The values stored in a list can be accessed using the slice
operator ([ ] and [:])
Course Co-ordinator: Dr. S. Priya
Python Lists
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print (list) # Prints complete list
print (list[0]) # Prints first element of the list
print (list[1:3]) # Prints elements starting from 2nd till 3rd
print (list[2:]) # Prints elements starting from 3rd element
print (tinylist * 2) # Prints list two times
print (list + tinylist) # Prints concatenated lists
[Link]
Course Co-ordinator: Dr. S. Priya
Python Tuples
• A tuple is another sequence data type that is similar to the
list. A tuple consists of a number of values separated by
commas. Unlike lists, however, tuples are enclosed within
parenthesis.
• The main difference 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.
Course Co-ordinator: Dr. S. Priya
Python Tuples
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
tinytuple = (123, 'john')
print (tuple) # Prints complete tuple
print (tuple[0]) # Prints first element of the tuple
print (tuple[1:3]) # Prints elements starting from 2nd till 3rd
print (tuple[2:]) # Prints elements starting from 3rd element
print (tinytuple * 2) # Prints tuple two times
print (tuple + tinytuple) # Prints concatenated tuple
Course Co-ordinator: Dr. S. Priya
Python Tuples
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
list1 = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tuple[2] = 1000 # Invalid syntax with tuple
list1[2] = 1000 # Valid syntax with list
print(list1)
output:
['abcd', 786, 1000, 'john', 70.2]
Course Co-ordinator: Dr. S. Priya
Python Dictionary
• Python's dictionaries are kind of hash-table type.
• It consist of key-value pairs.
• A dictionary key can be almost any Python type, but are
usually numbers or strings. Values, on the other hand, can be
any arbitrary Python object.
• Dictionaries are enclosed by curly braces ({ }) and values can
be assigned and accessed using square braces ([]).
Course Co-ordinator: Dr. S. Priya
Python Dictionary
dict = {}
dict['one'] = "This is one"
dict[2] = "This is two"
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
print (dict['one']) # Prints value for 'one' key
print (dict[2]) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print ([Link]()) # Prints all the keys
print ([Link]()) # Prints all the values
Course Co-ordinator: Dr. S. Priya
Python Dictionary
This produces the following result −
This is one
This is two
{'name': 'john', 'dept': 'sales', 'code': 6734}
dict_keys(['name', 'dept', 'code'])
dict_values(['john', 'sales', 6734])
[Link]
Course Co-ordinator: Dr. S. Priya
Data types in Python
• Every value in Python has a datatype.
• Data types are actually classes and variables are instance (object) of
these classes.
Text Type : str
Numeric Types : int, float, complex
Sequence Types : list, tuple, range
Mapping Type : dict
Set Types : set, frozenset
Boolean Type : bool
Binary Types : bytes, bytearray, memoryview
Course Co-ordinator: Dr. S. Priya
Data types in Python
• Python Numbers
• Integers, floating point numbers and complex numbers fall
under Python numbers category
✓ a=5 #Integer
✓ a = 2.0 # Float
✓ a = 1+2j #Complex
• type() function to know which class a variable or a value belongs to.
isinstance() function is used to check if an object belongs to a
particular class.
Course Co-ordinator: Dr. S. Priya
Data types in Python
• Python List
• Lists are used to store multiple items in a single variable.
a = [1, 2.2, ‘mahe']
• List items are ordered, changeable, and allow duplicate values.
• List items are indexed, the first item has index [0], the second item
has index [1] etc.
a = [1, 2.2, ‘mahe‘, 1, 2.2, ‘mahe']
• To determine how many items a list has, use the len() function
print(len(a))
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python List
Access Items
• List items are indexed and you can access them by referring to the
index number
a = [1, 2.2, ‘mahe‘, 1, 2.2, ‘mahe']
print(a[1])
• Negative indexing means start from the end. -1 refers to the last
item, -2 refers to the second last item etc.
print(a[-1])
• Range of Indexes Specifies where to start and where to end the
range.
print(a[2:5])
print(a[:4])
print(a[2:])
print(a[-4:-1])
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python List
• To determine if a specified item is present in a list use
the in keyword
a = [1, 2.2, ‘mahe‘, 1, 2.2, ‘mahe']
for “mahe” in a:
print(“yes”)
• To change the value of a specific item, refer to the index number
a = [1, 2.2, ‘mahe‘, 1, 2.2, ‘mahe']
a[5]=“university”
print(a)
• To change the value of items within a specific range
a = [1, 2.2, ‘mahe‘, 1, 2.2, ‘mahe']
a[1:3]=[3.8,“university”]
print(a)
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python List
• To insert a new list item, without replacing any of the existing
values, we can use the insert() method
a = [1, 2.2, ‘mahe‘, 1, 2.2, ‘mahe']
[Link](5.”CSE”)
• To add an item to the end of the list, use the append() method
a = [1, 2.2, ‘mahe‘, 1, 2.2, ‘mahe']
[Link](”University”)
• To append elements from another list to the current list, use
the extend() method
a = [1, 2.2, ‘mahe‘]
b = [2, 3.4, ‘IIT‘]
[Link](b)
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python List
• The remove() method removes the specified item
a = [1, 2.2, ‘mahe‘]
[Link](”mahe”)
• The pop() method removes the specified index.
a = [1, 2.2, ‘mahe‘, 1, 2.2, ‘mahe']
[Link](2)
[Link]()
• The del keyword also removes the specified index
a = [1, 2.2, ‘mahe‘, 1, 2.2, ‘mahe']
del a[2]
• The clear() method empties the list
[Link]()
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python List
• Loop through the list items by using a for loop
for i in a:
print(i)
• Loop through the list items by using a while loop.
i=0
while(i < len(a)):
print(a[i])
i=i+1
• List comprehension offers a shorter syntax when you want to create
a new list based on the values of an existing list.
newlist = [expression for item in iterable if condition == True]
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python List
• List objects have a sort() method that will sort the list
alphanumerically, ascending, by default
[Link]()
• To sort descending, use the keyword argument reverse = True
[Link](reverse=True)
• The reverse() method reverses the current sorting order of the
elements.
[Link]()
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python Tuple
• Tuple is an ordered sequence of items same as a list. The only
difference is that tuples are immutable. Tuples once created cannot
be modified.
• Tuples are used to write-protect data and are usually faster than lists
as they cannot change dynamically.
• It is defined within parentheses () where items are separated by
commas.
t = (5,'program', 1+3j)
Access Tuple Items
• You can access tuple items by referring to the index number, inside
square brackets
print(t[1])
print(t[-1])
print(t[1:2])
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python Tuple
Change Tuple Values
• Once a tuple is created, you cannot change its values. Tuples
are unchangeable, or immutable as it also is called.
x = (5,'program', 1+3j)
y = list(x)
y[1] = “CSE"
x = tuple(y)
print(x)
Unpacking a Tuple
• To extract the values back into variables from tuple is called
"unpacking“
x = (5,'program', 1+3j)
(a, b, c)=x
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python Set
• A set is a collection which is both unordered and unindexed.
• Set items are unordered, unchangeable, and do not allow duplicate
values
• Sets are written with curly brackets.
• To determine how many items a set has, use the len() method.
s = {“mahe", “cse", 1,3.5,2+3j}
Access Items
• You cannot access items in a set by referring to an index or a key.
• But you can loop through the set items using a for loop, or ask if a
specified value is present in a set, by using the in keyword.
for x in s:
print(x)
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python Set
Add Items
• Once a set is created, you cannot change its items, but you can add
new items.
• To add one item to a set use the add() method.
s = {“mahe", “cse", 1,3.5,2+3j}
[Link](“university")
print(s)
Add Sets
• To add items from another set into the current set, use
the update() method.
[Link](s1)
Remove Item
• To remove an item in a set, use the remove(), or the discard() method.
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python Set
Join Two Sets
• There are several ways to join two or more sets in Python.
• You can use the union() method that returns a new set containing all
items from both sets, or the update() method that inserts all the items
from one set into another:
set3 = [Link](set2)
[Link](set2)
• The intersection_update() method will keep only the items that are
present in both sets.
x.intersection_update(y)
• The symmetric_difference_update() method will keep only the
elements that are NOT present in both sets.
x.symmetric_difference_update(y)
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python Dictionary
• Dictionaries are used to store data values in key:value pairs.
• A dictionary is a collection which is ordered*, changeable and does
not allow duplicates.
d={
“name": “mahe",
“dept": “cse",
"year": 1990
}
print(d)
Accessing Items
• You can access the items of a dictionary by referring to its key name,
inside square brackets
x = d[“name"]
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python Dictionary
Get Keys
• The keys() method will return a list of all the keys in the dictionary.
x = [Link]()
Get Values
• The values() method will return a list of all the values in the
dictionary.
x = [Link]()
Get Items
• The items() method will return each item in a dictionary, as tuples in a
list.
x = [Link]()
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python Dictionary
Change Values
• You can change the value of a specific item by referring to its key
name:
d["year"] = 2018
• The update() method will update the dictionary with the items from
the given argument.
[Link]({"year": 2020})
Adding Items
• Adding an item to the dictionary is done by using a new index key and
assigning a value to it:
d["color"] = "red"
Course Co-ordinator: Dr. S. Priya
Data types in Python
Python Dictionary
Removing Items
• The pop() method removes the item with the specified key name
[Link](“name")
• The popitem() method removes the last inserted item
[Link]()
• The del keyword removes the item with the specified key name
del d[“name"]
• The clear() method empties the dictionary
[Link]()
Course Co-ordinator: Dr. S. Priya
Conversion between data types
Type Conversion
The process of converting the value of one data type (integer, string,
float, etc.) to another data type is called type conversion
• Implicit Type Conversion
• Explicit Type Conversion
Implicit Type Conversion
• In Implicit type conversion, Python automatically converts one data
type to another data type. This process doesn't need any user
involvement.
num_int = 123
num_flo = 1.23
num_new = num_int + num_flo
print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))
Course Co-ordinator: Dr. S. Priya
Conversion between data types
Type Conversion
• Explicit Type Conversion
• In Explicit Type Conversion, users convert the data type of an object
to required data type. We use the predefined functions
like int(), float(), str(), etc to perform explicit type conversion.
• This type of conversion is also called typecasting because the user
casts (changes) the data type of the objects.
Syntax
<required_datatype>(expression)
num_int = 123
num_str = "456“
num_str = int(num_str)
num_sum = num_int + num_str
Course Co-ordinator: Dr. S. Priya
List of Type Casting functions
Course Co-ordinator: Dr. S. Priya
Python Operators
• Operators are used to perform operations on variables and values.
• Operators are special symbols in Python that carry out arithmetic or
logical computation. The value that the operator operates on is
called the operand.
>>> 2+3
5
• Python divides the operators in the following groups:
✓ Arithmetic operators
✓ Assignment operators
✓ Comparison operators
✓ Logical operators
✓ Identity operators
✓ Membership operators
✓ Bitwise operators
Course Co-ordinator: Dr. S. Priya
Python Operators
Python Arithmetic Operators
• Arithmetic operators are used with numeric values to perform
common mathematical operations
Operator Meaning Example
+ Add two operands or unary plus x + y+ 2
- Subtract right operand from the left or unary minus x - y- 2
* Multiply two operands x*y
Divide left operand by the right one (always results into
/ x/y
float)
x%y
Modulus - remainder of the division of left operand by the
% (remainder of
right
x/y)
Floor division - division that results into whole number
// x // y
adjusted to the left in the number line
x**y (x to the
** Exponent - left operand raised to the power of right
power y)
Course Co-ordinator: Dr. S. Priya
Python Operators
Code:
a = 10
b=3
print(a + b) # 13
print(a // b) # 3
print(a ** b) # 1000
Course Co-ordinator: Dr. S. Priya
Python Operators
Comparison operators
• Comparison operators are used to compare values. It returns
either True or False according to the condition.
Operator Meaning Example
> Greater than - True if left operand is greater than the right x>y
< Less than - True if left operand is less than the right x<y
== Equal to - True if both operands are equal x == y
!= Not equal to - True if operands are not equal x != y
Greater than or equal to - True if left operand is greater
>= x >= y
than or equal to the right
Less than or equal to - True if left operand is less than or
<= x <= y
equal to the right
Course Co-ordinator: Dr. S. Priya
Python Operators
Code:
print(10 > 5) # True
print(3 != 3) # False
Course Co-ordinator: Dr. S. Priya
Python Operators
Logical operators
• Logical operators are the and, or, not operators.
Operator Meaning Example
and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements the operand) not x
Course Co-ordinator: Dr. S. Priya
Python Operators
Code:
a = True
b = False
print(a and b) # False
print(a or b) # True
print(not a) # False
Course Co-ordinator: Dr. S. Priya
Python Operators
Bitwise operators
• Bitwise operators act on operands as if they were strings of binary
digits. They operate bit by bit, hence the name.
• For example, 2 is 10 in binary and 7 is 111.
• In the table below: Let x = 10 (0000 1010 in binary) and y = 4
(0000 0100 in binary)
Operator Meaning Example
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)
Course Co-ordinator: Dr. S. Priya
Python Operators
Code:
a = 5 # 0101
b = 3 # 0011
print(a & b) # 1
print(a | b) # 7
print(~a) # -6
print(5 << 1) # 10
print(5 >> 1) # 2
Course Co-ordinator: Dr. S. Priya
Python Operators
Assignment operators
• Assignment operators are used in Python to assign values to
variables.
Course Co-ordinator: Dr. S. Priya
Python Operators
Code:
x = 10
x += 5
print(x) # 15
UNARY OPERATORS
a = -10
print(-a) # 10
print(not False) # True
Course Co-ordinator: Dr. S. Priya
Python Operators
Special operators
• Python language offers some special types of operators like the
identity operator or the membership operator.
Identity operators
• is and is not are the identity operators in Python. They are used to
check if two values (or variables) are located on the same part of the
memory.
Operator Meaning Example
True if the operands are identical (refer to
is x is True
the same object)
True if the operands are not identical (do
is not x is not True
not refer to the same object)
Course Co-ordinator: Dr. S. Priya
Python Operators
Code:
x = [1, 2]
y=x
z = [1, 2]
print(x is y) # True
print(x is z) # False
print(x == z) # True (values
are same)
Course Co-ordinator: Dr. S. Priya
Python Operators
Special operators
• Membership operators
• in and not in are the membership operators in Python. They are used
to test whether a value or variable is found in a sequence
(string, list, tuple, set and dictionary)
Operator Meaning Example
True if value/variable is found in the
in 5 in x
sequence
True if value/variable is not found in the
not in 5 not in x
sequence
Course Co-ordinator: Dr. S. Priya
Python Operators
Code:
print('p' in 'apple') # True
print(3 not in [1, 2, 4]) # True
Course Co-ordinator: Dr. S. Priya
[Link] & its precedence
Course Co-ordinator: Dr. S. Priya
Python Operators
Code:
Associativity
Expression
2+5*2
Expression
2+5*2*2/5
print(2**3**2)
a= eval(input(“enter your expression”)
print(a)
Course Co-ordinator: Dr. S. Priya
[Link] Error Messages
✓ In Python 3.x, print is a built-in function and requires parentheses.
✓ IndexError is thrown when trying to access an item at an invalid
index.
✓ ModuleNotFoundError is thrown when a module could not be
found.
Course Co-ordinator: Dr. S. Priya
Understanding Error Messages
✓ KeyError is thrown when a key is not found.
✓ ImportError is thrown when a specified function can not be found.
Course Co-ordinator: Dr. S. Priya
Understanding Error Messages
✓ StopIteration is thrown when the next() function goes beyond the
iterator items.
✓ TypeError is thrown when an operation or function is applied to an
object of an inappropriate type.
Course Co-ordinator: Dr. S. Priya
Understanding Error Messages
✓ ValueError is thrown when a function's argument is of an
inappropriate type.
✓ NameError is thrown when an object could not be found.
Course Co-ordinator: Dr. S. Priya
Understanding Error Messages
✓ ZeroDivisionError is thrown when the second operator in the
division is zero.
✓ KeyboardInterrupt is thrown when the user hits the interrupt key
(normally Control-C) during the execution of the program.
Course Co-ordinator: Dr. S. Priya
Understanding Error Messages
Course Co-ordinator: Dr. S. Priya
Understanding Error Messages
Course Co-ordinator: Dr. S. Priya
Basic Python Programs
1. Sum of two numbers.
2. Finding square root of a number.
3. Swap two variables.
4. Generate a random number.
5. Temperature conversion from celcius to fahrenheit.
6. ASCII value of a character.
7. Display calendar.
8. Vowel count in a sentence.
Course Co-ordinator: Dr. S. Priya
Sum of two numbers
Program
a = int(input('Enter value of a:'))
b = int(input('Enter value of b:'))
c=a+b
print('The sum of ',a,' and ',b,' is = ',c)
Output
Enter value of a:5
Enter value of b:3
The sum of 5 and 3 is = 8
Course Co-ordinator: Dr. S. Priya
Finding square root of a number
Program
num = float(input('Enter a number: '))
num_sqrt = num ** 0.5
print('The square root of %0.3f is %0.3f' %(num, num_sqrt))
Output
Enter a number: 3
The square root of 3.000 is 1.732
Course Co-ordinator: Dr. S. Priya
Swap two variables
Program
a = int(input('Enter value of a:'))
b = int(input('Enter value of b:'))
(a,b) = (b,a)
print('The value of a = ', a)
print('The value of b = ', b)
Output
Enter value of a:3
Enter value of b:2
The value of a = 2
The value of b = 3
Course Co-ordinator: Dr. S. Priya
Generate a random number
Program
import random
print([Link](0,6))
Output
5
Course Co-ordinator: Dr. S. Priya
Temperature conversion from celcius to fahrenheit.
Program
celsius = float(input('Enter temperature in celcius : '))
fahrenheit = (celsius * 1.8) + 32
print('%0.2f degree Celsius is equal to %0.2f degree Fahrenheit'
%(celsius,fahrenheit))
Output
Enter temperature in celcius : 37.5
37.50 degree Celsius is equal to 99.50 degree Fahrenheit
Course Co-ordinator: Dr. S. Priya
ASCII value of a character
Program
c = input('Enter any character : ')
print("The ASCII value of '" + c + "' is", ord(c))
Output
Enter any character : A
The ASCII value of 'A' is 65
Course Co-ordinator: Dr. S. Priya
Display Calendar
Program
import calendar
yy = int(input("Enter year: "))
mm = int(input("Enter month: "))
print([Link](yy, mm))
Output
Course Co-ordinator: Dr. S. Priya
Vowel count in a sentence
Program
vowels = 'aeiou'
ip_str = 'Hello, Welcome you all for python programming'
ip_str = ip_str.casefold()
count = {}.fromkeys(vowels,0)
for char in ip_str:
if char in count:
count[char] += 1
print(count)
Output
{'a': 2, 'e': 3, 'i': 1, 'o': 6, 'u': 1}
Course Co-ordinator: Dr. S. Priya
Python list Methods
Method Description
append() Adds an element at the end of the list, [Link](elmnt)
clear() Removes all the elements from the list, [Link]()
copy() Returns a copy of the list, x = [Link]()
count() Returns the number of elements with the specified value,
[Link](value)
extend() Add the elements of a list (or any iterable), to the end of the current
list, [Link](collections)
index() Returns the index of the first element with the specified value.
[Link](elmnt)
insert() Adds an element at the specified position, [Link](pos, elmnt)
pop() Removes the element at the specified position, [Link](pos)
remove() Removes the first item with the specified value, [Link](elmnt)
reverse() Reverses the order of the list, [Link]()
sort() Sorts the list, [Link](reverse=True|False)
Course Co-ordinator: Dr. S. Priya
Python Set Methods
Method Description
add() Adds an element to the set
clear() Removes all the elements from the set
copy() Returns a copy of the set
difference() Returns a set containing the difference
between two or more sets
difference_update() Removes the items in this set that are also
included in another, specified set
discard() Remove the specified item
Course Co-ordinator: Dr. S. Priya
Python Set Methods
Method Description
intersection() Returns a set, that is the intersection
of two other sets
intersection_update() Removes the items in this set that are
not present in other, specified set(s)
isdisjoint() Returns whether two sets have a
intersection or not
issubset() Returns whether another set contains
this set or not
issuperset() Returns whether this set contains
another set or not
Course Co-ordinator: Dr. S. Priya
Python Set Methods
Method Description
pop() Removes an random element from
the set
remove() Removes the specified element
symmetric_difference() Returns a set with the symmetric
differences of two sets
symmetric_difference_updat inserts the symmetric differences
e() from this set and another
union() Return a set containing the union
of sets
update() Update the set with the union of
this set and others
Course Co-ordinator: Dr. S. Priya
Python Dictionary Methods
Method Description
clear() Removes all the elements from the
dictionary
copy() Returns a copy of the dictionary
fromkeys() Returns a dictionary with the specified
keys and value
get() Returns the value of the specified key
items() Returns a list containing a tuple for each
key value pair
Course Co-ordinator: Dr. S. Priya
Python Dictionary Methods
Method Description
keys() Returns a list containing the dictionary's keys
pop() Removes the element with the specified key
popitem() Removes the last inserted key-value pair
setdefault() Returns the value of the specified key. If the
key does not exist: insert the key, with the
specified value
update() Updates the dictionary with the specified key-
value pairs
values() Returns a list of all the values in the dictionary
Course Co-ordinator: Dr. S. Priya
range()
✓ Returns an immutable sequence of numbers between the given start
integer to the stop integer.
✓ Takes mainly three arguments having the same use in both
definitions:
✓ start - integer starting from which the sequence of integers is to be
returned. Default is 0.
✓ stop - integer before which the sequence of integers is to be
returned. The range of integers ends at stop -1.
✓ step (Optional) - integer value which determines the increment
between each integer in the sequence. Default is 1.
Course Co-ordinator: Dr. S. Priya
Execution with range()
Course Co-ordinator: Dr. S. Priya
[Link] Statements
✓ A control structure (or flow of control) is a block of programming
that analyses variables and chooses a direction in which to go based
on given parameters.
✓ Three basic types of control structures: Sequential, Selection and
Repetition.
✓ In addition to this there is break, continue and pass which changes
the usual order of execution.
Course Co-ordinator: Dr. S. Priya
Control Statements
I. Sequential – Occurs when statements are executed one after another
in order. You don't need to do anything more for this to happen.
II. Selection - used for decisions, branching that is choosing between 2
or more alternative paths.
1. If 2. if…else 3. Nested if
4. if…Elif else Ladder 5. Switch
III. Iterative / Repetition - used for looping, i.e. repeating a piece of
code multiple times in a row.
1. while 2. do…while 3. for
IV. Loop control statements: break - breaks out of the innermost loop
and terminates the loop.
continue - continues with the next iteration of the loop by skipping
the current iteration.
pass - used when a statement is required syntactically but the
program requires no [Link] Co-ordinator: Dr. S. Priya
[Link] Statements
✓ Set of statements where the execution process will happen in
sequence manner.
✓ If the logic gets broken in any one of the line, then complete source
code execution will get broken.
Course Co-ordinator: Dr. S. Priya
[Link] / Conditional / Decision Making
Statements
✓ Decides the direction of flow of program execution.
✓ Evaluate multiple expressions which produce True or False as
outcome.
✓ You need to determine which action to take and which statements to
execute if outcome is True or False.
✓ Following are different types and constraints for building a good
decision making statements.
Course Co-ordinator: Dr. S. Priya
if, if…else Statements
✓ If statement evaluates the test expression inside parenthesis. If test
expression is evaluated to True, statements inside the body of if is
executed.
✓ If the test expression is evaluated to False, statements inside the body
of else is executed.
✓ The else statement is an optional statement and there could be at most
only one else statement following if.
Syntax for if: Syntax for if…else:
Another Way - result = 'pass' if number >= 50 else 'fail'
Course Co-ordinator: Dr. S. Priya
if, if…else Statements
✓ Executes if block only when it satisfies the condition and
terminates otherwise.
✓ Executes if block when it satisfies the condition and else block
when it fails the condition.
Course Co-ordinator: Dr. S. Priya
Nested if Statements
✓ When an if statement is presented inside another if statement or
if/else statement.
✓ Tests for true/false conditions and then take an appropriate action.
Syntax
Course Co-ordinator: Dr. S. Priya
if elif else ladder
✓ Checks for the condition and executes if block when it is True.
When it is False it checks next condition in the elif block and this
goes on until every conditions are checked.
✓ If all the conditions are False, the body of else is executed.
✓ Only one block among the several if...elif...else blocks is executed
according to the condition.
✓ The if block can have only one else block. But it can have multiple
elif blocks.
Syntax
Course Co-ordinator: Dr. S. Priya
Nested if & if elif ladder Statements
Nested if
if elif ladder
Course Co-ordinator: Dr. S. Priya
Switch Statements
✓ Python does not have a switch or case statement.
✓ In order to achieve switch statement, we can use a dictionary to map
cases to their functionality.
✓ We define a function week() to tell us which day a certain day of
the week is.
✓ A switcher is a dictionary that performs this mapping.
Course Co-ordinator: Dr. S. Priya
[Link] / Repetition / Looping Statements
[Link] loop
✓ A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string).
✓ Iterating over a sequence is called traversal.
✓ We can also use range function to traverse through the sequence.
Syntax
Course Co-ordinator: Dr. S. Priya
[Link] loop
✓ Used to iterate over a block of code as long as the test expression
(condition) is true.
✓ We generally use this loop when we don't know the number of
times to iterate beforehand.
✓ test expression is checked first. The body of the loop is entered only
if the test_expression evaluates to True.
✓ After one iteration, the test expression is checked again. This
process continues until the test_expression evaluates to False.
Syntax
Course Co-ordinator: Dr. S. Priya
for & while loop
for loop
while loop
Course Co-ordinator: Dr. S. Priya
[Link]…while
✓ Python doesn't have do-while loop. But we can create a program like
this.
✓ The do while loop is used to check condition after executing the
statement. It is like while loop but it is executed at least once.
Example
Course Co-ordinator: Dr. S. Priya
[Link] Control Statements
[Link]
✓ The break statement terminates the loop containing it.
✓ Control of the program flows to the statement immediately after the
body of the loop.
✓ If the break statement is inside a nested loop (loop inside another
loop), the break statement will terminate the innermost loop.
Example Code
Course Co-ordinator: Dr. S. Priya
[Link]
✓ The continue statement is used to skip the rest of the code inside a
loop for the current iteration only.
✓ Loop does not terminate but continues on with the next iteration.
Example Code
Course Co-ordinator: Dr. S. Priya
[Link]
✓ The pass statement is a null statement.
✓ The difference between a comment and a pass statement in Python is
that while the interpreter ignores a comment entirely, pass is not
ignored.
✓ Nothing happens when the pass is executed. It results in no
operation (NOP).
Example Code
def function(args):
pass
class Example:
pass Course Co-ordinator: Dr. S. Priya
Example
for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print(n, 'equals', x, '*', n//x)
break
else:
# loop fell through without finding a factor
print(n, 'is a prime number')
Course Co-ordinator: Dr. S. Priya
Example
x=5
y = 10
match operator:
case '+':
result = x + y
case '-':
result = x - y
case '*':
result = x * y
case '/':
result = x / y
case _:
result = "Unsupported operator"
Course Co-ordinator: Dr. S. Priya
Example
subject = input("Enter a subject: ")
score = int(input("Enter a score: "))
match subject:
# if score is 80 or higher in Physics or Chemistry
case 'Physics' | 'Chemistry' if score >= 80:
print("Excellent in Science!")
# if score is 80 or higher in English or Grammar
case 'English' | 'Grammar' if score >= 80:
print("Excellent in English!")
# if score is 80 or higher in Maths
case 'Maths' if score >= 80:
print("Excellent in Maths!")
case _:
print(f"Needs improvement in {subject}!")
Course Co-ordinator: Dr. S. Priya
Collections
List, tuple, Set, Dictionary
sort()
reverse()
clear()
in
notin
len(l)
min(l)
max(l)
+
*
index(ele, beg, end)
count(x)
Course Co-ordinator: Dr. S. Priya
Collections
•ChainMap – Groups multiple dictionaries into one view.
•Counter – Counts hashable objects.
•OrderedDict – Dictionary that remembers insertion order.
•UserDict – Wrapper to create custom dictionary-like classes.
•UserList – Wrapper to create custom list-like classes.
•UserString – Wrapper to create custom string-like classes.
•abc – Abstract base classes for container types.
•defaultdict – Dictionary with default values for missing keys.
•deque – Double-ended queue.
•namedtuple() – Factory function for tuple subclasses with named
fields.
Course Co-ordinator: Dr. S. Priya
Python Import Statement
➢ When our program grows bigger, it is a good idea to break it into different
modules.
➢ A module is a file containing Python definitions and statements. Python
modules have a filename and end with the extension .py.
➢ Definitions inside a module can be imported to another module or the
interactive interpreter in Python. We use the import keyword to do this.
For example, we can import the math module by typing the following line:
import math
We can use the module in the following ways: import math
print([Link])
Output
3.141592653589793
Course Co-ordinator: Dr. S. Priya
Python Import Statement
Now all the definitions inside math module are available in our scope.
We can also import some specific attributes and functions only, using
the from keyword.
For example:
>>> from math import pi
>>> pi3.141592653589793
While importing a module, Python looks at several places defined in [Link].
It is a list of directory locations.
>>> import sys
>>> [Link]
['', 'C:\\Python33\\Lib\\idlelib', 'C:\\Windows\\system32\\[Link]',
'C:\\Python33\\DLLs', 'C:\\Python33\\lib', 'C:\\Python33',
'C:\\Python33\\lib\\site-packages']
Course Co-ordinator: Dr. S. Priya
Python Namespace
➢ A Namespace containing all the built-in names is created when we start the
Python interpreter and exists as long as the interpreter runs.
➢ This is the reason that built-in functions like id(), print() etc. are always
available to us from any part of the program. Each module creates its own global
namespace.
➢These different namespaces are isolated. Hence, the same name that may exist
in different modules do not collide.
L → Local → E → Enclosing → G → Global → B → Built-in
A diagram of different namespaces in Python
Course Co-ordinator: Dr. S. Priya
Python Variable Scope
➢ A scope is the portion of a program from where a namespace can be
accessed directly without any prefix.
➢ At any given moment, there are at least three nested scopes.
▪ Scope of the current function which has local names
▪ Scope of the module which has global names
▪ Outermost scope which has built-in names
➢ When a reference is made inside a function, the name is
searched in the local namespace, then in the global namespace and
finally in the built-in namespace.
Example of Scope and Namespace in Python
def outer_function():
b = 20
def inner_func():
c = 30
a = 10
Course Co-ordinator: Dr. S. Priya
Python Namespace and scope
The following example will further clarify the namespace and scope.
def outer_function():
a = 20
def inner_function():
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
outer_function()
print('a =', a)
As you can see, the output of this program is
a = 30
a = 20
a = 10
Course Co-ordinator: Dr. S. Priya
Python Namespace and scope
In this program, three different variables a are defined in separate namespaces and
accessed accordingly. While in the following program,
def outer_function():
global a
a = 20
def inner_function():
global a
a = 30
print('a =', a)
inner_function()
print('a =', a)
a = 10
outer_function()
print('a =', a)
The output of the program is.
a = 30
a = 30
a = 30
Here, all references and assignments are to the global a due to the use of keyword global.
Course Co-ordinator: Dr. S. Priya
Functions
What is a function in Python?
✓A function is a group of related statements that performs a specific task.
✓Helps to break our program into smaller and modular chunks.
✓When program grows larger and larger, functions make it more organized
and manageable.
✓It avoids repetition and makes the code reusable.
Syntax of Function
def function_name(parameters):
"""docstring"""
statement(s)
Course Co-ordinator: Dr. S. Priya
Program structure and design
Python Program Consists of
➢ Modules Program
➢ Statements
➢ Expressions
➢ Objects Modules
Statements
Expressions Objects
Course Co-ordinator: Dr. S. Priya
Types of Functions
Functions divided into the following two types:
[Link]-in Functions – functionality defined by default.
[Link]-defined Functions – functionality defined by the user.
Functions vs Methods
✓ A method refers to a function which is part of a class.
✓ You access it with an instance or object of the class.
✓ A function doesn’t have this restriction: it just refers to a standalone
function.
✓ All methods are functions, but not all functions are methods.
Course Co-ordinator: Dr. S. Priya
Functions vs Methods
✓ A function plus() and then a Summation class with a sum() method.
✓ A method refers to a function which is part of a class.
✓ You access it with an instance or object of the class.
✓ A function doesn’t have this restriction: it just refers to a standalone
function.
✓ All methods are functions, but not all functions are methods.
✓ A function plus() and then a Summation class with a sum() method.
Method Call
Course Co-ordinator: Dr. S. Priya
Rules for Defining a User-defined Function
✓ Keyword def that marks the start of the function header.
✓ A function name to uniquely identify the function. Function naming
follows the same rules of writing identifiers in Python.
✓ Parameters (arguments) are the variables/constants through which
we pass values to a function (optional).
✓ A colon (:) to mark the end of the function header.
✓ One or more valid python statements that make up the function
body.
✓ Statements must have the same indentation level (usually 4 spaces).
✓ An optional return statement to return a value from the function.
Course Co-ordinator: Dr. S. Priya
Function Call
✓ We can call a defined function from another function, program or
even the Python shell.
✓ Function Call - type the function name with appropriate parameters.
✓ The return statement is used to exit a function and go back to the
place from where it was called.
✓ Can contain an expression that gets evaluated and the value is
returned.
✓ If there is no expression in the statement or the return statement
itself is not present inside a function, then the function will return
the None object.
Course Co-ordinator: Dr. S. Priya
The return Statements
The return statement is used at the end of the function and returns the
result of the function.
Syntax:
return [expression_list]
Example:
# Defining function
def sum():
a = 10
b = 20
c = a+b
return c
# calling sum() function in print
statement
print("The sum is:",sum())
Course Co-ordinator: Dr. S. Priya
Arguments and return values
Creating function without arguments Creating function without arguments
and without return statement and with return statement
# Defining function # Defining function
def sum(): def sum():
a = 10 a = 10
b = 20 b = 20
c = a+b c = a+b
print(c) return c
# calling sum() function # calling sum() function
sum() print(sum())
Course Co-ordinator: Dr. S. Priya
Arguments and return values
Creating function with arguments Creating function with arguments and
and without return statement return statements
# Defining function # Defining function
def sum(a,b): def sum(a,b):
c = a+b c = a+b
print(c) return c
# calling sum() function # calling sum() function
a = 10 a = 10
b = 20 b = 20
sum(a,b) print(sum(a,b))
Course Co-ordinator: Dr. S. Priya
Formal vs actual arguments
Course Co-ordinator: Dr. S. Priya
Passing Arguments to a Function
Course Co-ordinator: Dr. S. Priya
Pass by Value & Pass by Reference
✓ In Python, we don't have to think about pass by value and pass by
reference as it does that automatically for you.
✓ To emulate this using Python, we use the concept of mutability.
✓ All parameters (arguments) in the Python language are passed by
reference.
✓ It means if you change what a parameter refers to within a function,
the change also reflects back in the calling function.
✓ If you pass immutable arguments like integers, strings or tuples to a
function, the passing acts like Call-by-value.
✓ It's different, if we pass mutable arguments.
Course Co-ordinator: Dr. S. Priya
Pass by Value & Pass by Reference
Course Co-ordinator: Dr. S. Priya
Variations of Function Arguments
Course Co-ordinator: Dr. S. Priya
Variations of Function Arguments
Course Co-ordinator: Dr. S. Priya
Positional / Keyword Arguments
✓ When we call a function with some values, these values get assigned
to the arguments according to their position.
✓ In keyword arguments we can call functions in different ways i.e.,
the order (position) of the arguments can be changed.
✓ Can mix positional arguments with keyword arguments during a
function call.
✓ But keyword arguments must follow positional arguments.
Course Co-ordinator: Dr. S. Priya
Arbitrary Arguments
✓ We do not know in advance the number of arguments that will be
passed into a function.
✓ Python allows us to handle this kind of situation through function
calls with an arbitrary number of arguments.
✓ We use an asterisk (*) before the parameter name to denote this kind
of argument in function definition.
Course Co-ordinator: Dr. S. Priya
Different ways of using return Statement in a
Function
Course Co-ordinator: Dr. S. Priya
Use of values returned from a Function
Course Co-ordinator: Dr. S. Priya
Recursive Function
What is recursion?
A recursive function is a special function, which calls itself again
and again until some condition satisfied.
Factorial of a number is the product of all the integers from 1 to that
number. For example, the factorial of 6 (denoted as 6!) is 1*2*3*4*5*6 =
720
Course Co-ordinator: Dr. S. Priya
Recursive Function
Example of a recursive function
def factorial(x):
"""This is a recursive function
to find the factorial of an integer"""
if x == 1:
return 1
else:
return (x * factorial(x-1))
num = 3
print("The factorial of", num, "is", factorial(num))
Output
The factorial of 3 is 6
Course Co-ordinator: Dr. S. Priya
Recursive Function
factorial(3) # 1st call with 3 #
3 * factorial(2) 2nd call with 2
3 * 2 * factorial(1) # 3rd call with 1
3*2*1 # return from 3rd call as number=1
3*2 # return from 2nd call # return
6 from 1st call
Maximum depth of recursion is
1000
Course Co-ordinator: Dr. S. Priya
Recursive Function
Advantages of Recursion
Recursive functions make the code look clean and elegant.
A complex task can be broken down into simpler sub-problems using
recursion.
Sequence generation is easier with recursion than using some nested
iteration.
Disadvantages of Recursion
Sometimes the logic behind recursion is hard to follow through.
Expensive since tasks lot of memory and time
Recursive functions are hard to debug.
Course Co-ordinator: Dr. S. Priya
Built-in Functions in Python
✓ Built-in functions are the ones whose functionality is predefined.
✓ These get stored in the interpreter and come into action when they
are called. These can be accessed from any part of the program. The
Python 3.6 version has 69 built-in functions and these are:
Course Co-ordinator: Dr. S. Priya
Some of popular Built-in Functions in Python
Course Co-ordinator: Dr. S. Priya
Built-in Functions in Python
abs()
✓ Return the absolute value of a number( An absolute numbers is the
magnitude of real number without regard to its sign).
Syntax:
>>>abs(X)
Course Co-ordinator: Dr. S. Priya
Built-in Functions in Python
range()
✓ returns an iterator from a starting point to a end point with a specific
step. It is most commonly used in looping with a FOR LOOP.
Syntax:
range(start,stop[, step])
✓ Note: Stop is a mandatory argument.
✓ Start and Step are optional (Default value of start is 0 and step is 1).
Course Co-ordinator: Dr. S. Priya
Built-in Functions in Python
bin()
✓ Converts an integer number to a binary string counterpart prefixed
with “0b “.
Syntax:
✓ >>> bin(x)
Course Co-ordinator: Dr. S. Priya
Built-in Functions in Python
min()
✓ Return the smallest item in an iterable or the smallest of two or more
arguments.
✓ If one positional argument is provided, it should be an iterable. The
smallest item in the iterable is returned. If two or more positional
arguments are provided, the smallest of the positional arguments is
returned.
Syntax:
✓ >>>min(iterable)
✓ >>>min(arg1, arg2 ,…..)
Course Co-ordinator: Dr. S. Priya
Built-in Functions in Python
max()
✓ Return the largest item in an iterable or the largest of two or more
arguments.
✓ If one positional argument is provided, it should be an iterable. The
largest item in the iterable is returned. If two or more positional
arguments are provided, the largest of the positional arguments is
returned.
Syntax:
>>>max(iterable)
>>>max(arg1, arg2 ,…..)
Course Co-ordinator: Dr. S. Priya
Python Built-in Function
Python Built-in Functions
The built-in Python functions are pre-defined by the python interpreter.
There are many built-in python functions. These functions perform a specific
task and can be used in any program, depending on the requirement of the
user.
Course Co-ordinator: Dr. S. Priya
Python Modules
✓ A module is a file with the [Link] that contains Python or C
executable code.
✓ A module is made up of a number of Python statements and
expressions.
✓ Modules allow us to use pre-defined variables, functions, and
classes.
✓ This cuts down on development time and allows code to be reused.
Course Co-ordinator: Dr. S. Priya
Python Modules
Creating a Module in Python
• We can create a module by writing some code in a file and saving
that file in a [Link] extension.
def display(): Output
print(“MAHE")
MAHE
Importing a Module in Python
We can import a module by using the import keyword
import mahe
[Link]()
Course Co-ordinator: Dr. S. Priya
Python Modules
• We can import every object in a module by using the asterisk *
operator.
from mahe import *
display()
• Likewise, we can import a specific function from a module.
from pythongeeks import display
display()
• We can also alias a module while importing
import pythongeeks as pg
[Link]()
Course Co-ordinator: Dr. S. Priya
Packages in Python
• To provide an application development environment, a python
package establishes a hierarchical directory structure with several
modules and sub-packages. They are nothing more than a bundle of
modules and sub-packages.
Creating and Importing a Package
• To create a Python package, we need to create a directory with a
__init__.py file and a module. Suppose we have created a package
named website with the previously created module [Link] in it.
We can import the website package by using the import keyword
and a dot operator.
import [Link]
[Link]()
Course Co-ordinator: Dr. S. Priya
Python Modules vs Packages
The following are some of the distinctions between Modules and
Packages:
• A Package is a directory containing numerous modules and sub-
packages, whereas a Module is [Link] file containing Python code.
• An __init__ .py file is required to create a package. There is no
such necessity when it comes to creating modules.
• We can import all objects in a module at once by using the asterisk
(*) operator but we can’t import all modules in a package at once.
Course Co-ordinator: Dr. S. Priya
Understanding error msgs in python
➢ A python program terminates as soon as it encounters an unhandled error.
These errors can be broadly classified into two classes:
➢ Syntax errors
➢ Logical errors (Exceptions)
Python Syntax Errors
Error caused by not following the proper structure (syntax) of the language is
called syntax error or parsing error.
Let's look at one example:
>>> if a < 3
File "<interactive input>", line 1
if a < 3
^SyntaxError: invalid syntax
As shown in the example, an arrow indicates where the parser ran into the
syntax error.
We can notice here that a colon Course
: is missing
Co-ordinator:in
Dr. the if statement.
S. Priya
Python Syntax error
Common Syntax Problems
• Misusing the Assignment Operator (=)
• Misspelling, Missing, or Misusing Python Keywords
• Missing Parentheses, Brackets, and Quotes
• Mistaking Dictionary Syntax
• Using the Wrong Indentation
• Defining and Calling Functions
• Changing Python Versions
There are a few elements of a SyntaxError traceback that can help you determine
where the invalid syntax is in your code:
• The file name where the invalid syntax was encountered
• The line number and reproduced line of code where the issue was encountered
• A caret (^) on the line below the reproduced code, which shows you the point in the
code that has a problem
• The error message that comes after the exception type SyntaxError, which can
Course Co-ordinator: Dr. S. Priya
provide information to help you determine the problem
Misusing the assignment operator
Misusing the Assignment Operator (=)
➢There are several cases in Python where you’re not able to make assignments to
objects.
➢Some examples are assigning to literals and function calls.
➢In the code block below, you can see a few examples that attempt to do this and the
resulting SyntaxError tracebacks:
>>> ('hello') = 5
File "<stdin>", line 1
SyntaxError: can't assign to function call
>>> 'foo' = 1
File "<stdin>", line 1
SyntaxError: can't assign to literal
>>> 1 = 'foo'
File "<stdin>", line 1
SyntaxError: can't assign to literal
Course Co-ordinator: Dr. S. Priya
Misspelling, Missing, or Misusing keyword
There are three common ways that you can mistakenly use keywords:
➢Misspelling a keyword
>>> fro i in range(10):
File "<stdin>", line 1
fro i in range(10):
^
SyntaxError: invalid syntax
➢Missing a keyword
>>> for i range(10):
File "<stdin>", line 1
for i range(10):
^
SyntaxError: invalid syntax
➢Misusing a keyword
>>> names = ['pam', 'jim', 'michael']
>>> if 'jim' in names:
print('jim found') break
File "<stdin>", line 3
SyntaxError: 'break' outside loop
Course Co-ordinator: Dr. S. Priya
Missing Parentheses, Brackets and Quotes
Missing Quotes:
>>> message = 'don't' File "<stdin>", line 1 message = 'don't'
SyntaxError: invalid syntax
➢Escape the single quote with a backslash ('don\'t')
➢Surround the entire string in double-quotes instead ("don't")
Missing Brackets
def foo():
return [1, 2, 3
print(foo())
When you run this code, you’ll be told that there’s a problem with the call to print():
SyntaxError: invalid syntax
Course Co-ordinator: Dr. S. Priya
Mistaking Dictionary Syntax
>>> ages = {'pam'=24}
File"<stdin>“ , line 1
ages = {'pam'=24}
^
SyntaxError: invalid syntax
To fix this, you could replace the equals sign with a colon.
>>> ages = {'pam‘:24}
>>> print(ages)
{'sam': 4}
>>> print(ages['sam']) 4
Course Co-ordinator: Dr. S. Priya
Using Wrong Indentation
There are two sub-classes of SyntaxError that deal with indentation issues
specifically:
1. IndentationError
2. TabError
While other programming languages use curly braces to denote blocks of code,
Python uses whitespace for Indentation.
1 # [Link]
2 def foo():
3 for i in range(10):
4 print(i)
5 print('done')
6
7 foo()
IndentationError: unindent does not match any outer indentation level
Course Co-ordinator: Dr. S. Priya
Changing Python versions
>>> # Valid Python 2 syntax that fails in Python 3
>>> print 'hello'
File "<stdin>" , line 1
print 'hello'
^
SyntaxError: Missing parentheses in call to 'print'. Did
you mean print('hello')?
>>> # Any version of python before 3.6 including 2.7
>>> w ='world'
>>> print(f'hello, {w}')
File "<stdin>", line 1
print(f'hello, {w}')
^
SyntaxError: invalid syntax
Course Co-ordinator: Dr. S. Priya
Python Logical Errors (Exception)
➢ Errors that occur at runtime (after passing the syntax test) are
called exceptions or logical errors. For instance
➢ FileNotFoundError : try to open a file(for reading) that does not exist.
➢ ZeroDivisionError : try to divide a number by zero.
➢ ImportError: try to import a module that does not exist.
➢ Whenever these types of runtime errors occur, Python creates an exception object.
➢ If not handled properly, it prints a traceback to that error along with some
details about why that error occurred.
➢ Let's look at how Python treats these errors:
>>> open("[Link]")
Traceback (most recent call last):
File "<string>", line 301, in runcode
File "<interactive input>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '[Link]’
Course Co-ordinator: Dr. S. Priya
Python Sample Programs
1) Python program to do arithmetical operations
2) Python program to find the area of a triangle
3) Python program to solve quadratic equation
4) Python program to swap two variables
5) Python program to generate a random number
6) Python program to convert kilometers to miles
7) Python program to convert Celsius to Fahrenheit
8) Python program to display calendar
9) Python Program to Check if a Number is Odd or Even
10) Python Program to Check Leap Year
11) Python Program to Check Prime Number
12) Python Program to Add Two Matrices
13) Python Program to Multiply Two Matrices
14) Python Program to Transpose a Matrix
Course Co-ordinator: Dr. S. Priya
Online Resources
REFERENCES
➢ [Link]
➢ [Link]
➢ [Link]
➢ [Link]
➢ [Link]
Course Co-ordinator: Dr. S. Priya