Python Basics
Panchatcharam M
Panchatcharam M December 2025 1
Python Environments and IDE
Panchatcharam M
Panchatcharam M December 2025 2
Text Book and References
1. Martin C B, Python: The Complete Reference, 2nd Edition, McGraw Hill
Education (2018).
2. Mark S, Programming in Python 3: A Complete Introduction to the Python
Language, 2nd Edition, Pearson Education (2018).
3. Robert J, Numerical Python, 2nd Edition, Apress (2018).
Panchatcharam M December 2025 3
Other References
1. H. Bhasin, Python for Beginners, 2018
2. M. Lutz and D. Ascher, Learning Python, 2016
3. H. P. Langtangen, A Primer on Scientific Programming with Python, 2016
4. E. Matthes, Python Crash Course, 2015
5. A. B. Downey, Think Python: How to think like a computer scientist, 2016
6. D. Beazley and B. K. Jones, Python cookbook, 2013
Panchatcharam M December 2025 4
Compiler vs Interpreter
Panchatcharam M December 2025 5
PYTHON: What, Why, How
6
Python
◼ Famous programming language
◼ 1989, Guido van Rossum, a Dutch computer
programmer
Over six years ago, in December 1989, I was looking for a
◼ A back end programming language "hobby" programming project that would keep me
occupied during the week around Christmas. My office (a
◼ High level programming language government-run research lab in Amsterdam) would be
closed, but I had a home computer, and not much else
on my hands. I decided to write an interpreter for the
◼ Reliability, simplicity new scripting language I had been thinking about lately:
a descendant of ABC that would appeal to Unix/C
hackers. I chose Python as a working title for the project,
◼ Supports polymorphism, operator overloading, being in a slightly irreverent mood (and a big fan of
Monty Python's Flying Circus).
inheritance --Guido van Rossum
Reston, VA, May 1996
◼ Call components written in C or C++ or vice versa
Panchatcharam M December 2025 7
Python
>>> import this Special cases aren't special enough to break the rules.
Although practicality beats purity.
The Zen of Python, by Tim Peters Errors should never pass silently.
Unless explicitly silenced.
Beautiful is better than ugly. In the face of ambiguity, refuse the temptation to guess.
Explicit is better than implicit. There should be one-- and preferably only one --obvious way to do it.
Simple is better than complex. Although that way may not be obvious at first unless you're Dutch.
Complex is better than complicated. Now is better than never.
Flat is better than nested. Although never is often better than *right* now.
Sparse is better than dense. If the implementation is hard to explain, it's a bad idea.
Readability counts. If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Panchatcharam M December 2025 8
Characteristics of Python
◼ Richer data type than any other programming language
◼ Simpler to peruse linguistic structures than any other
programming language
◼ Autonomous scripted language
◼ Full access to working framework API’s
◼ More run-time adaptability
◼ Libraries are cross-platform (works with Linux, Mac,
Windows)
Panchatcharam M December 2025 9
Characteristics of Python
◼ Can build extensive applications
Easily compiled to byte-code
◼
◼ Easy to use OOP
Easy
◼ Easier to troubleshoot Popular Powerful
◼ Easier to test
◼ Clean, clear syntax
Rich Libraries
◼ Very few keyword General Purpose
Panchatcharam M December 2025 10
Why Python
◼ Clean Syntax
◼ No variable declaration required
◼ Although not a type-less language
◼ Less development time
◼ Require less training
Python is a programming language that lets you work
quickly and integrate systems more effectively
Panchatcharam M December 2025 11
Python Libraries
◼ Numpy: Multi-dimensional array
◼ 130K+ packages operations
◼ Scipy: scientific computing
◼ 2K packages per month
◼ Matplotlib: plotting library
◼ 181657 projects
◼ SageMath: System of Algebra and
Geometry Experimentation
◼ Symby: symbolic computation
◼ Pandas: data manipulation and
analysis
Panchatcharam M December 2025 12
Python Libraries
◼ PiCloud: Supercomputing processing
◼ Many aspects Mathematics capacity on the cloud
◼ Algebra ◼ Scikit-learn: Machine Learning toolkit
◼ Combinatorics ◼ Pygame: For game development
◼ Numerical Mathematics ◼ pyQT/pyGtk: To develop GUI
◼ Calculus ◼ Nltk: natural language kit
◼ Number theory ◼ TensorFlow: machine learning library
◼ Keras: machine learning library
Panchatcharam M December 2025 13
Applications for Python
Web and Internet Development
Ed
Scientific and Numeric u c at
io
n
GUIs p m e n t Gaming
e D e v e l o
Soft w a r
b a s e Business applications
D a t a
Panchatcharam M December 2025 14
Applications for Python
Panchatcharam M December 2025 15
Python Programs
Modules are written as text files
.py extension
Every module has its own discrete namespace
Modules and programs are differentiated only by
the way they are called
Panchatcharam M December 2025 16
Python Programs
.py file executed directly are called programs
.py files reference by import statement are
called modules
.py file can be script also
Panchatcharam M December 2025 17
PYTHON installation
18
Requirements
Download python from [Link]
Any version:
Recommended version > 3.12
Download numpy 2.3.5
Download scipy 1.16.3
Download matplotlib 3.10.7
Panchatcharam M December 2025 19
Install
Download python from [Link]
In Windows Store
In Ubuntu 16.04 or later, it is part of OS
For Mac OSX, download and install
Panchatcharam M December 2025 20
Install
After installation open python shell
Panchatcharam M December 2025 21
Vagitus
Panchatcharam M December 2025 22
PYTHON IDEs
23
Pycharm
[Link]
Panchatcharam M December 2025 24
Pycharm
File Explorer Editor
Output
Terminal
Panchatcharam M December 2025 25
Pycharm
Panchatcharam M December 2025 26
Jupyter
[Link]
Panchatcharam M December 2025 27
Jupyter
[Link]
Panchatcharam M December 2025 28
Anaconda
[Link]
Panchatcharam M December 2025 29
Anaconda
Panchatcharam M December 2025 30
Anaconda
Panchatcharam M December 2025 31
Anaconda
Panchatcharam M December 2025 32
Colaboratory
[Link]
Panchatcharam M December 2025 33
Colaboratory
[Link]
Panchatcharam M December 2025 34
Kaggle
[Link]
Panchatcharam M December 2025 35
PYTHON: Simple files
36
Python Programs
Modules are written as text files
.py extension
Every module has its own discrete namespace
Modules and programs are differentiated only by
the way they are called
Panchatcharam M December 2025 37
Python Programs
.py file executed directly are called programs
.py files reference by import statement are
called modules
.py file can be script also
Panchatcharam M December 2025 38
PYTHON: frequently used
DATA Types
39
Variables
◼ variable: A named piece of memory that
can store a value.
◼ Usage:
◼Compute an expression's result,
◼store that result into a variable,
◼and use that variable later in the
program
Panchatcharam M December 2025 40
Variables
No variable declaration required
>>> a = 5
>>>
Variable assignment is a statement, no printing
>>> a
5
a itself is an expression, so printing the result
Warning: Variables must be created before usage
Exception error
Panchatcharam M December 2025 41
Types of variable
>>> a = 5 >>> a = “ATSNPDE”
>>> type(a) >>> type (a)
<class ‘int’> <class ‘str’>
>>> a = 8.0
>>> type (a)
<class ‘float’>
Panchatcharam M December 2025 42
Data Types
Strings
Can use “” or ‘’ to specify.
“abc” ‘abc’ (Same thing.)
Unmatched can occur within the string
“matt’s”
Use triple double-quotes for multi-line
strings or strings that contain both ‘and “
inside of them:
“““a‘b“c”””
Panchatcharam M December 2025 43
PYTHON: white space and
comments
44
White Space
Whitespace is meaningful in Python: especially
indentation and placement of newlines.
Use a newline to end a line of code.
Use \ when must go to next line prematurely
Panchatcharam M December 2025 45
White Space
No braces { } to mark blocks of code in Python…
Use consistent indentation instead.
The first line with less indentation is outside of the block.
The first line with more indentation starts a nested block
Often a colon appears at the start of a new block.
(E.g. for function and class definitions.)
Panchatcharam M December 2025 46
Comments
Start comments with # – the rest of line is ignored.
Can include a “documentation string” as the first line of
any new function or class that you define.
The development environment, debugger, and other tools
use
it: it’s good style to include one.
def my_function(x, y):
“““This is the docstring. This
function does blah blah blah.”””
# The code would go here...
Panchatcharam M December 2025 47
Data Types
48
Numeric Types
>>> a = 5 >>> a = 8.0
>>> type(a) >>> type (a)
<class ‘int’> <class ‘float’>
>>> a = 5+4j
>>> type(a)
<class ‘complex’>
Panchatcharam M December 2025 49
String Data Types
>>> a = “ATSNPDE”
Strings >>> type (a)
<class ‘str’>
Can use “” or ‘’ to specify.
“abc” ‘abc’ (Same thing.)
Unmatched can occur within the string
“matt’s”
Use triple double-quotes for multi-line
strings or strings that contain both ‘and “
inside of them:
“““a‘b“c”””
Panchatcharam M December 2025 50
Boolean Datatypes
>>> is_pass = True >>> is_pass = False
>>> type (is_pass) >>> type (is_pass)
<class ‘bool’> <class ‘bool’>
Panchatcharam M December 2025 51
List and Tuple Datatypes
>>> company= [“Google”,”Facebook”,”Apple”]
>>> type (company)
<class ‘list’>
company=list(("Google","Facebook","Apple"))
>>> animals= (“Lion”,”Tiger”,”Cat”)
>>> type (animals)
<class ‘tuple’>
animals= tuple((“Lion”,”Tiger”,”Cat”))
Panchatcharam M December 2025 52
Set Datatypes
>>> company= {“Google”,”Facebook”,”Apple”}
>>> type (company)
<class ‘set’>
company=set(("Google","Facebook","Apple"))
>>> animals= frozenset({“Lion”,”Tiger”,”Cat”})
>>> type (animals)
<class ‘frozenset’>
animals= frozenset((“Lion”,”Tiger”,”Cat”))
Panchatcharam M December 2025 53
Range and dict Datatypes
>>> x=range(10)
>>> type (x)
<class ‘range’>
>>> s= {“name”:”Raj”,”age”:20,”Marks”:94.5,”Pass”:True}
>>> type (s)
<class ‘dict’>
Panchatcharam M December 2025 54
Byte Datatypes
>>> x=b”Placement”
>>> type(x) >>> x=bytearray(5)
<class ‘bytes’> >>> type(x)
<class ‘bytearray’>
>>> x=memoryview(x)
>>> type(x)
<class ‘memoryview’>
Panchatcharam M December 2025 55
Operators and precedence
56
Arithmetic Operators
expression: A data value or set of operations to compute a value.
Examples: 1 + 4 * 3
Arithmetic operators we will use:
+ addition
- subtraction/negation
* multiplication
/ division
% modulus, a.k.a. remainder
** exponentiation
// floor division
Panchatcharam M December 2025 57
Precedence
Order in which operations are computed.
** has higher precedence than * / // %
* / // % have a higher precedence than + -
1 + 3 * 4 is 13
Parentheses can be used to force a certain order of evaluation.
(1 + 3) * 4 is 16
Multiple operators of same precedence
** right to left associativity
* / // % + -left to right associativity
Advice: Better use parentheses if you have more than one
operators of multiple precedence
Panchatcharam M December 2025 58
Expressions
Python can also manipulate real numbers.
Examples: 6.022 -15.9997 42.0 2.143e17
The operators + - * / // % ** ( ) all work for real numbers.
Example for / 15.0 / 2.0 is 7.5
Example for // : 15.0 / 2.0 is 7
The % produces an exact answer: 7.5 / 2.0 is 1.5
The same rules of precedence also apply to real numbers:
Evaluate ( ) before * / % before + -
When integers and reals are mixed, the result is a real number.
Example: 1 / 2.0 is 0.5
Panchatcharam M December 2025 59
Math Methods
Method Description
Constant Description
abs(value) absolute value
e 2.7182818...
ceil(value) rounds up
pi 3.1415926...
cos(value) cosine, in radians
tau (2*pi) 6.2831853...
floor(value) rounds down
log(value) logarithm, base e
log10(value) logarithm, base 10
max(value1, value2) larger of two values
min(value1, value2) smaller of two values
round(value) nearest whole number
sin(value) sine, in radians
sqrt(value) square root
◼ To use many of these Methods, you must write the following
at the top of your Python program:
◼ import math
Panchatcharam M December 2025 60
Reserved Words
Names are case sensitive and cannot start with a number.
They can contain letters, numbers, and underscores.
bob Bob _bob _2_bob_ bob_2 BoB
and, assert, break, class, continue,
def, del, elif, else, except, exec,
finally, for, from, global, if, import,
in, is, lambda, not, or, pass, print,
raise, return, try, while
Panchatcharam M December 2025 61
Assignment: What goes on
behind the scene
62
Assignment statement
◼ Assignment Statement: Stores a value into a variable.
◼ Syntax:
name = value
◼ Examples: x = 5
gpa = 3.14
x, y = 2,3
◼ A variable that has been given a value can be used in
expressions.
x + 4 is 9
◼ Exercise: Evaluate the quadratic equation for a given a, b, and c.
2
◼ 𝑎𝑥 + 𝑏𝑥 + 𝑐
Panchatcharam M December 2025 63
Assignment statement
◼ Assignment manipulates references.
◼ x = y does not make a copy of the object y references
◼ x = y makes x reference the object y references
name = value
◼ Examples: a = [1,2,3] # a now references the list [1,2,3]
b = a # b now references what a references
[Link](4) # this changes the list a references
print(b) # if we print b
[1,2,3,4] # SURPRISED!?
Panchatcharam M December 2025 64
Assignment statement
◼ There is a lot going on when we type a = 3
◼ First, an integer 3 is created and stored in memory
◼ A name a is created
◼ A reference to the memory location storing the 3 is the assigned
to the name a
◼ So: When we say that the value of a is 3
◼ we mean that a now refers to the integer 3
Name: a Type: Integer
Ref: <address1> Data: 3
name list memory
Panchatcharam M December 2025 65
Assignment statement
❖ The data 3 we created is of type integer. In Python, the datatypes integer, float,
and string (and tuple) are “immutable.”
❖ This doesn’t mean we can’t change the value of x, i.e. Change what x refers to …
❖ For example, we could increment x
>>> x = 5
>>> x = x + 1
>>> print(x)
6
Panchatcharam M December 2025 66
Assignment statement
➢ If we increment x, then what’s really happening is:
➢ The reference of name x is looked up. >>> x = x + 1
➢ The value at that reference is retrieved
➢ The 3+1 calculation occurs, producing a new data element 4 which is
assigned to a fresh memory location with a new reference.
➢ The name x is changed to point to this new reference.
➢ The old data 3 is garbage collected if no name still refers to it
Type: Integer
Name: x Data: 3
Ref: <address1>
Type: Integer
Data: 4
Panchatcharam M December 2025 67
Assignment statement
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print(x) # No effect on x, still ref 3.
3
Name: x
Ref: <address1> Type: Integer
Data: 3
Panchatcharam M December 2025 68
Assignment statement
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print(x) # No effect on x, still ref 3.
3
Name: x
Ref: <address1> Type: Integer
Data: 3
Name: y
Ref: <address1>
Panchatcharam M December 2025 69
Assignment statement
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print(x) # No effect on x, still ref 3.
3
Name: x
Ref: <address1> Type: Integer
Data: 3
Name: y
Ref: <address1> Type: Integer
Data: 4
Panchatcharam M December 2025 70
Assignment statement
>>> x = 3 # Creates 3, name x refers to 3
>>> y = x # Creates name y, refers to 3.
>>> y = 4 # Creates ref for 4. Changes y.
>>> print(x) # No effect on x, still ref 3.
3
Name: x Type: Integer
Ref: <address1> Data: 3
Name: y Type: Integer
Ref: <address1> Data: 4
Panchatcharam M December 2025 71
Assignment statement
❑ For other data types (lists, dictionaries, user-defined types),
assignment works differently.
❑ These datatypes are “mutable.”
❑ When we change these data, we do it in place.
❑ We don’t copy them into a new memory address each time.
❑ If we type y=x and then modify y, both x and y are changed
immutable mutable
>>> x = 3
x = some mutable object
>>> y = x
y = x
>>> y = 4 make a change to y
>>> print(x) look at x
3
x will be changed as well
Panchatcharam M December 2025 72
Sharing List
a = [1, 2, 3] a 1 2 3
a
b = a 1 2 3
b
a
[Link](4) 1 2 3 4
b
Panchatcharam M December 2025 73
Print and input
74
print
◼ print : Produces text output on the console.
◼ Syntax:
print("Message“)
print(Expression)
◼ Prints the given text message or expression value on the
console, and moves the cursor down to the next line.
print(Item1, Item2, ..., ItemN)
◼ Prints several messages and/or expressions on the same line.
Panchatcharam M December 2025 75
print
◼ Examples:
print("Hello, world!")
age = 45
print("You have", 65 - age, "years until
retirement")
Output:
Hello, world!
You have 20 years until retirement
Panchatcharam M December 2025 76
input
◼ input : Reads a number from user input.
◼ You can assign (store) the result of input into a variable.
◼ Example:
age = input("How old are you? ")
print("Your age is", age)
print("You have", 65 – int(age), "years
until retirement")
Output:
How old are you? 53
Your age is 53
You have 12 years until retirement
Panchatcharam M December 2025 77
More on print
Fancy output
78
print
◼ print : Produces text output on the console.
◼ Full Syntax:
print(*objects, sep=' ', end='\n',
file=[Link], flush=False)
❑ objects: objects to be printed
❑ sep: object separated by sep
❑ file: with write string method
❑ flush: stream is forcibly flushed
Panchatcharam M December 2025 79
print
◼ Examples:
a,b = 10,5
print("a = ", a, sep='00000', end='\n\n\n')
print(“b = ", a, sep='0', end='')
Output:
a = 0000010
a = 05
Panchatcharam M December 2025 80
print
◼ Examples:
fp=open('[Link]','w')
print(“ATSNPDE Laboratory",file=fp)
[Link]()
Panchatcharam M December 2025 81
Formatted string in print
◼ Examples:
import math
print(f'The value of pi is approx {[Link]:.3f}.')
print('There are {}, {}, {}, {} in chess'.format('knights',
'king','queen','horses'))
FirstName='Raja'
LastName='Kumar'
Marks=43.5
print('Student Name {1} {2}. His Mark is {0}'.format(Marks,FirstName, LastName))
print('Student Name {0} {1}. His Mark is {2}'.format(FirstName, LastName,Marks))
print('Student Name {first} {last}. His Mark is
{mark}'.format(mark=Marks,first=FirstName, last=LastName))
print('Student Name {first} {last}. His Mark is {mark}'.format(first=FirstName,
mark=Marks,last=LastName))
Panchatcharam M December 2025 82
Formatted string in print
◼ Examples:
x=2
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
x=3
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
x=8
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
x=10
print('{0:2d} {1:3d} {2:4d}'.format(x, x*x, x*x*x))
Panchatcharam M December 2025 83
More on lists
84
List: Key Functions
x=[1,2,3,4,5]
print('First Element: ',x[0]) #indexing
print(‘Second Element: ',x[1])
print('Last Element: ',x[-1]) #indexing from last
print('Slicing: ',x[2:]) #slicing
print('Slicing 2: ',x[-2:]) #slicing
x=x+[2,3,4,5,6] #concatenation
print('Concatenation:',x)
[Link](7) #appending
print('Appended 7: ',x)
[Link](2) #removing
print('Removed 2: ',x)
x[2]=7 #replacing
print('Replacment: ',x)
Panchatcharam M December 2025 85
List: Key Functions
y=[0,0,0] #nested list
y[0]=[1,2,3] #replacing
y[1]=[3,4,5]
y[2]=[5,6,7]
print('Nested List :',y)
#can be mixture of all data types
A=['a','b','c','d','e','f',0,0.1,"Ram",True,3+4j,[1,2,3,4]]
print('Mixtures: ',A)
print('Slicing Again: ',A[2:7]) #slicing
#Remove item
A[2:6]=[]
print('Removing again: ',A)
del A[2]
print('Deleting: ',A)
#Remove all
A[:]=[]
print('Removed Everything: ',A)
Panchatcharam M December 2025 86
List: Key Functions
#Length
A=['a','b','c','d','e','f’]
print(‘A*2:’,A*2)
print('New List:',A)
print('Length of List: ',len(A))
[Link]()
x=x+[2,3,4,5,6]
print('Cleared Again: ',A)
print(x)
A=['a','b','c','d','e','f']
print('Number of occurences of 3: ',[Link](3))
[Link]('g')
#number of occurences
print('Extended',A)
print('Index of 5 in the list: ',[Link](5))
print('Maximum and Minimum: ',max(x),min(x))
#minimum and maximum
[Link]()
print('Reversed: ',x)
[Link]()
print('Sorted: ',x)
reversed(x)
print(x)
Panchatcharam M December 2025 87
More on Tuples
88
Tuples: Key Functions
heros=('Arthos','Porthos','Aramis','Romeo','Juliet')
print(heros)
print(len(heros))
print(heros[1],heros[2],heros[-1],heros[-
2],heros[2:],heros[-2:],sep=' & ')
print([Link]('Porthos'))
Panchatcharam M December 2025 89
More on SETS
90
Sets: Key Functions
emptyset=set()
print(emptyset)
print(x)
numbers=set(x)
print(numbers)
y=list(numbers)
print(y) programming=set(['C','C++','Python','Ruby','Java','S
cala','Swift','Perl'])
print(programming)
[Link]('Python')
print(programming)
[Link]('SQL')
print(programming)
compilers=set(['C','C++','Scala'])
interpreters=set(['Python','Java'])
[Link](compilers)
Panchatcharam M December 2025 91
Sets: Key Functions
intersect=[Link](interpreters)
print(intersect)
union=[Link](interpreters)
print(union)
union=[Link](programming)
print(union)
diff=[Link](compilers)
print(diff)
print([Link](interpreters))
print([Link](programming))
print([Link](compilers))
print(programming^compilers)#symmetric difference
print(programming.symmetric_difference(compilers))
Panchatcharam M December 2025 92
More on Dictionaries
93
dict: Key Functions
course={'MA6024':'PDE','MA5191':'Programming','MA5023':'DE',
'MA6204':'Numerical'}
print(course)
print(course['MA6204'])
print([Link]('MA5191'))
print([Link]())
print([Link]())
print([Link]())
course['MA1101']='Calculus'
print(course)
print(len(course))
[Link]()
print('cleared: ',course)
Panchatcharam M December 2025 94
dict: Key Functions
btechcourse={'MA2021':'Linear Algebra','MA2022':'Complex
Methods','MA2023':'Probability'}
print(btechcourse)
[Link](btechcourse)
print(course)
herodictionary=[Link](heros)
print(herodictionary)
herodictionary=[Link](heros,[1,2,3,4,5])
print(herodictionary)
Panchatcharam M December 2025 95
branching
96
Branching
◼ if statement: Executes a group of statements only if a certain condition is true.
Otherwise, the statements are skipped.
◼ Syntax:
if condition:
statements
◼ Example:
gpa = 3.4
if gpa > 2.0:
print("Your application is accepted.")
Panchatcharam M December 2025 97
Branching
◼ if/else statement: Executes one block of statements if a certain condition is True, and
a second block of statements if it is False.
◼ Syntax:
if condition:
statements
else:
statements
◼ Example:
gpa = 8.4
if gpa > 7.0:
print("Welcome to ATSNPDE")
else:
print("Your application is denied.")
Panchatcharam M December 2025 98
Branching
◼ Multiple conditions can be chained with elif ("else if"):
if condition:
statements
elif condition:
statements
else:
statements
Panchatcharam M December 2025 99
Relational Operators
Operator Meaning Example Result
== equals 1 + 1 == 2 True
!= does not equal 3.2 != 2.5 True
< less than 10 < 5 False
> greater than 10 > 5 True
<= less than or equal to 126 <= 100 False
>= greater than or equal to 5.0 >= 5.0 True
Panchatcharam M December 2025 100
Logical Operators
Operator Example Result
and 9 != 6 and 2 < 3 True
or 2 == 3 or -1 < 5 True
not not 7 > 0 False
Panchatcharam M December 2025 101
LOOPS
102
Loops
◼ for loop: Repeats a set of statements over a group of values.
◼ Syntax:
for variableName in groupOfValues:
statements
◼ We indent the statements to be repeated with tabs or spaces.
◼ variableName gives a name to each value, so you can refer to
it in the statements.
◼ groupOfValues can be a range of integers, specified with the
range function.
Panchatcharam M December 2025 103
Loops
◼ Example:
for x in range(1, 6):
print(x, "squared is", x * x)
Output:
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
Panchatcharam M December 2025 104
range
◼ The range function specifies a range of integers:
◼ range(start, stop) - the integers between start
(inclusive)
and stop (exclusive)
◼ It can also accept a third value specifying the change between
values.
◼ range(start, stop, step) - the integers between start
(inclusive)
and stop (exclusive) by step
Panchatcharam M December 2025 105
range
◼ Example:
for x in range(5, 0, -1): sum = 0
print(x) for i in range(1, 11):
print("Blastoff!“) sum = sum + (i * i)
Output: print("sum of first 10 squares is", sum)
5
Output:
4
sum of first 10 squares is 385
3
2
1
Blastoff!
Panchatcharam M December 2025 106
while
◼ while loop: Executes a group of statements as long as a condition is True.
◼ good for indefinite loops (repeat an unknown number of times)
◼ Syntax:
while condition:
statements
Panchatcharam M December 2025 107
while
◼ Example:
number = 1
while number < 200:
print(number)
number = number * 2
◼ Output:
1 2 4 8 16 32 64 128
Panchatcharam M December 2025 108
Examples
◼ Check whether given number is prime or composite
Panchatcharam M December 2025 109
So Far
✓ How to write Simple Python Code
✓ Python Language Mechanism
✓ Each code is sequence of instructions
Not easy for larger problems
Difficult to keep track of details
How do check whether you have given correct input to
section of the code
Panchatcharam M December 2025 110
summary
111
Good Programmer
✓ Introduce Functions
✓ Decompose the problem into smaller portions
✓ Introduce abstraction
More code is not necessarily a good thing
Keeping everything in a single file
Writing 1000 lines of code
Panchatcharam M December 2025 112
functions
113
Tirutsava at IIT Tirupati
❖ Will you ask a single person to organize everything?
1. Food Committee
2. Cultural Committee
3. Finance Committee
4. Technical Committee
5. Website Development Committee
6. …
7. ….
Panchatcharam M December 2025 114
Multi TV –Single Picture
❖ Different devices work together
for a single job
Panchatcharam M December 2025 115
Decomposition
❖ Divide the program or code into modules
✓ It should be self-contained
✓ Break up the codes into pieces
✓ It should be reusable
✓ Helps you to organize the code
✓ Coherence
❖ Functions/Modules/Procedures/Methods
❖ Classes
Panchatcharam M December 2025 116
Abstraction
❖ Take a Bank Details or Your Mobile Phone or PC
✓ It is not necessary that everyone should know
everything about your account
✓ Manager/Administrator has a role
✓ Cashier/User has a role
✓ Think: A piece of code as black box
✓ Cannot See
✓ Do not need to see
✓ Do not want to see
✓ Hide Coding details
Panchatcharam M December 2025 117
Functions
✓ Functions: Write reusable pieces of code
✓ Should not run until they are called or invoked
✓ Characteristics:
✓ Name
✓ Parameters (≥ 𝟎)
✓ Docstring (Optional)
✓ Body
✓ Return (None or something)
Panchatcharam M December 2025 118
functions
119
Functions
➢def creates a function and assigns it a name
➢return sends a result back to the caller
➢Arguments are passed by assignment
➢Arguments and return types are not declared
def name(arg1, arg2, ...):
"""documentation""" # optional doc string
statements or Body
return expression # from function
def product(x,y): product(2,3)
return x*y 6
Panchatcharam M December 2025 120
Functions
def gcd(a, b):
"greatest common divisor"
while a != 0:
a, b = b%a, a # parallel assignment
return b 𝑎 = 𝑞0 𝑏 + 𝑟0
𝑏 = 𝑞1 𝑟0 + 𝑟1
>>> gcd.__doc__
'greatest common divisor' 𝑏 = 𝑞0 𝑎 + 𝑟0
𝑎 = 𝑞1 𝑟0 + 𝑟1
>>> gcd(12, 20)
𝑟0 = 𝑞2 𝑟1 + 𝑟2
4
Panchatcharam M December 2025 121
Variable Scope
✓ Formal Parameter gets bound the value of actual
parameter when function is called
✓ New Scope/Frame/Environment created when enter a
function
✓ Scope: Mapping of names to objects
def func(a):
a = a + 1 a = 10
print(‘Value of a’,a) b = func(a)
return a
Panchatcharam M December 2025 122
Variable Scope
def func(a):
a = a + 1
print(‘Value of a’,a)
return a Global Scope Func Scope
Func Some a 10
a = 10 Code
b = func(a) a 10
b 11
Panchatcharam M December 2025 123
No Return or None Return
def func(a):
a = a + 1
print(‘Value of a’,a)
a = 10
b=func(a)
print(b)
Panchatcharam M December 2025 124
Function as Arguments
def func_a(): def func_b(x):
print(‘Inside func_a’) print(‘Inside func_b’)
return x
def func_c(y):
Global Scope Func_a Scope
print(‘Inside func_c’) Func_a
return func_a() Func_b
print(func_a()) Func_c
print(7+fun_c(3))
print(func_c(func_a)
Panchatcharam M December 2025 125
Functions Arguments
✓ Positional Arguments
✓ Keyword Arguments
def functionpositional(x,y,z): #Positional Arguments
print("I am inside the Positional")
print("My Name is ",x)
print("My Age is ",y)
print("My Marks is ",z)
def functionkeyword(Name=None,Age=None,Marks=None): #Keyword
Arguments
print("Another Definition")
print("My Name is ",Name) x,y,z="IITTP",6,4.8
print("My Age is ",Age) functionpositional(x,y,z)
print("My Marks is ",Marks) functionkeyword(Age=y,Name=y,Marks=z)
Panchatcharam M December 2025 126
Default Arguments
def func(a, b,c=10,d=100):
print(a,b,c,d)
>>> func(1,2)
1 2 10 100
>>> func(1,2,3,4)
1 2 3 4
Panchatcharam M December 2025 127
*args and **kwargs
✓ Non-keyword Arguments with variable length
✓ Keyword Arguments with variable length
def studentdetails(name,*data):
print(name)
print(data)
print(type(data))
studentdetails("placement",28,'A',True)
def studentdetailskey(**kwargs):
print(kwargs["name"])
print(type(kwargs))
for keys,vals in [Link]():
print(keys,vals)
studentdetailskey(name=x,Age=y,Grade=z)
studentdetailskey(sno="firstcolumn",name="secondcolumn",quiz="third
column")
studentdetailskey(sno="firstcolumn",quiz="thirdcolumn")
Panchatcharam M December 2025 128
Lambda Function/Expression
✓ Lambda operator or lambda function or lambda
expression is a way to create small anonymous function
✓ Function without name
✓ Throw away function
✓ Major uses Filter, Map, Reduce
Lambda argument list: lambda expression
double = lambda x: x*x
double(4) def secretkey(n):
16 return lambda a: a*n
mykey=secretkey(4)
print(mykey(11))
Panchatcharam M December 2025 129
Filter Function
✓ Filter out all elements of a list or dictionary
✓ Example find all even numbers from a list
Syntax: filter(function, list)
numbers=[0,1,3,4,6,10,39,30,28,5,7]
even=list(filter(lambda x: x%2==0, numbers))
print(even)
phoneos=[‘Android’,’iOS’,’Ubuntu’,’Windows’,’Android’,’Android’,’Ubuntu’]
even=list(filter(lambda x: x==‘Android’, phoneos))
print(even)
Panchatcharam M December 2025 130
Map Function
✓ It maps to a new list
✓ Applies the function to all the elements of the sequence
Syntax: map(function, seq)
numbers=[0,1,3,4,6,10,39,30,28,5,7]
even=list(map(lambda x: x*2, numbers))
print(even) def fahrenheit(T):
return ((float(9)/5)*T + 32)
def celsius(T):
temperature=[0,1,3,4,6,10,39,30,28,5,7] return (float(5)/9)*(T-32)
F=list(map(fahrenheit,temperature))
C=list(map(celsius,temperature))
temperature=[0,1,3,4,6,10,39,30,28,5,7]
F=list(map(lambda x:((float(9)/5)*x + 32), temperature))
C=list(map(lambda x: (float(5)/9)*(T-32),temperature))
Panchatcharam M December 2025 131
Reduce Function
✓ sum(): This function computes the sum of an array
✓ Instead of if you want to operate on two different parameters, then func can be
used
✓ First define two elements of the list: func(s1,s2)
✓ reduce on a list = [s1,s1,…,sn] will work as follows
✓ [func(s1,s2),s3,…,sn)] Syntax: reduce(function, seq)
✓ [func(func(s1,s2),s3),s4,…,sn)]
✓ [func(func(func(s1,s2),s3),s4),s5,…,sn)]
✓ …..
numbers=[0,1,3,4,6,10,39,30,28,5,7]
mysum= reduce(lambda x,y: x+y, numbers)
print(mysum)
numbers=[0,1,3,4,6,10,39,30,28,5,7]
mysub=reduce(lambda x,y: x*y, numbers)
print(mysub)
Panchatcharam M December 2025 132
Python : Import
Panchatcharam M
12/4/2025
Panchatcharam M December 2025 133
Import Modules
◼ Modules: File containing Python definitions and Statements
◼ We can import module definition from one file to another
import <module_name>
Example:
import math
import numpy
import random
Panchatcharam M December 2025 134
Access Module Function
❑ A module can contain variables
❑ A module can contain function
❑ To access the variables and functions use dot operator
[Link]
[Link]
Example:
[Link](30)
[Link]
[Link](100)
Panchatcharam M December 2025 135
More on Modules
❑ Further module can contain
❑ Executable statements with Function definitions
❑ Its own private symbol table : Global symbol for all
functions of the module
❑ Module Search Path
1. Current directory
2. List of directories specified in PYTHONPATH
Panchatcharam M December 2025 136
Reload Modules
❑ When we specify import <module_name>
❑ You can access each of its function as
❑ [Link]()
❑ When you have modified a few functions in module
❑ You should restart your interpreter
❑ Alternatively, you can reload the module
❑ E.g.: import importlib
❑ [Link](module_name)
Panchatcharam M December 2025 137
Python Packages
❑ When a very large application is developed with multiple
submodules, you can’t import all submodules at one go.
❑ from <module_name> import *
❑ It does not import all submodules from a package
❑ E.g: from scipy import * does not import
[Link]
❑ Make sure, you have imported required packages properly
❑ E.g: from [Link] import *
❑ import [Link]
Panchatcharam M December 2025 138
Import Part of Modules
❑ from <module_name> import <name(s)>
❑ You can also integrate a few specific module
❑ E.g: from [Link] import
quadrature,trapz
Panchatcharam M December 2025 139
Import Module as
❑ from <module_name> import <name(s)> as <alt_name>
❑ You can import a module and given alternative name
❑ E.g: import numpy as np
❑ import matplotlib as mpl
❑ import [Link] as plt
[Link]
Panchatcharam M December 2025 140
Python Numpy
Panchatcharam M
Panchatcharam M December 2025 141
Numpy
◼ Numpy is the core library for scientific computing in python
◼ High-performance multi-dimensional array object and tools for working
with these arrays
◼ Familiar with MATLAB??
Panchatcharam M December 2025 142
Arrays
◼ A numpy array is a grid of values, all of the same type
◼ indexed by a tuple of nonnegative integers
◼ number of dimensions is the rank of the array
◼ the shape of an array is a tuple of integers giving the
size of the array along each dimension.
Panchatcharam M December 2025 143
Arrays
import numpy as np
a = [Link]([1, 2, 3]) # Create a rank 1 array
print(type(a)) # Prints "<class '[Link]'>"
print([Link]) # Prints "(3,)"
print(a[0], a[1], a[2]) # Prints "1 2 3"
a[0] = 5 # Change an element of the array
print(a) # Prints "[5, 2, 3]"
b = [Link]([[1,2,3],[4,5,6]]) # Create a rank 2 array
print([Link]) # Prints "(2, 3)"
print(b[0, 0], b[0, 1], b[1, 0]) # Prints "1 2 4
Panchatcharam M December 2025 144
Arrays
import numpy as np
a = [Link]((2,2)) # Create an array of all zeros
print(a) # Prints "[[ 0. 0.]
# [ 0. 0.]]"
b = [Link]((1,2)) # Create an array of all ones
print(b) # Prints "[[ 1. 1.]]"
c = [Link]((2,2), 7) # Create a constant array
print(c) # Prints "[[ 7. 7.]
# [ 7. 7.]]"
d = [Link](2) # Create a 2x2 identity matrix
print(d) # Prints "[[ 1. 0.]
# [ 0. 1.]]"
e = [Link]((2,2)) # Create an array filled with random values
print(e) # Might print "[[ 0.91940167 0.08143941]
# [ 0.68744134 0.87236687]]"
Panchatcharam M December 2025 145
Slicing
import numpy as np
# Create the following rank 2 array with shape (3, 4)
# [[ 1 2 3 4]
# [ 5 6 7 8]
# [ 9 10 11 12]]
a = [Link]([[1,2,3,4], [5,6,7,8], [9,10,11,12]])
# Use slicing to pull out the subarray consisting of the first 2 rows
# and columns 1 and 2; b is the following array of shape (2, 2):
# [[2 3]
# [6 7]]
b = a[:2, 1:3]
# A slice of an array is a view into the same data, so modifying it
# will modify the original array.
print(a[0, 1]) # Prints "2"
b[0, 0] = 77 # b[0, 0] is the same piece of data as a[0, 1]
print(a[0, 1]) # Prints "77
Panchatcharam M December 2025 146
Slicing
# Two ways of accessing the data in the middle row of the array.
# Mixing integer indexing with slices yields an array of lower rank,
# while using only slices yields an array of the same rank as the
# original array:
row_r1 = a[1, :] # Rank 1 view of the second row of a
row_r2 = a[1:2, :] # Rank 2 view of the second row of a
print(row_r1, row_r1.shape) # Prints "[5 6 7 8] (4,)"
print(row_r2, row_r2.shape) # Prints "[[5 6 7 8]] (1, 4)"
# We can make the same distinction when accessing columns of an array:
col_r1 = a[:, 1]
col_r2 = a[:, 1:2]
print(col_r1, col_r1.shape) # Prints "[ 2 6 10] (3,)"
print(col_r2, col_r2.shape) # Prints "[[ 2]
# [ 6]
# [10]] (3, 1)"
Panchatcharam M December 2025 147
Indexing
import numpy as np
a = [Link]([[1,2], [3, 4], [5, 6]])
# An example of integer array indexing.
# The returned array will have shape (3,) and
print(a[[0, 1, 2], [0, 1, 0]]) # Prints "[1 4 5]"
# The above example of integer array indexing is equivalent to this:
print([Link]([a[0, 0], a[1, 1], a[2, 0]])) # Prints "[1 4 5]"
# When using integer array indexing, you can reuse the same
# element from the source array:
print(a[[0, 0], [1, 1]]) # Prints "[2 2]"
# Equivalent to the previous integer array indexing example
print([Link]([a[0, 1], a[0, 1]])) # Prints "[2 2]"
Panchatcharam M December 2025 148
Indexing
import numpy as np
# Create a new array from which we will select elements
a = [Link]([[1,2,3], [4,5,6], [7,8,9], [10, 11, 12]])
print(a) # prints "array([[ 1, 2, 3],
# [ 4, 5, 6],
# [ 7, 8, 9],
# [10, 11, 12]])"
# Create an array of indices
b = [Link]([0, 2, 0, 1])
# Select one element from each row of a using the indices in b
print(a[[Link](4), b]) # Prints "[ 1 6 7 11]"
# Mutate one element from each row of a using the indices in b
a[[Link](4), b] += 10
print(a) # prints "array([[11, 2, 3],
# [ 4, 5, 16],
# [17, 8, 9],
# [10, 21, 12]])
Panchatcharam M December 2025 149
Indexing
import numpy as np
a = [Link]([[1,2], [3, 4], [5, 6]])
bool_idx = (a > 2) # Find the elements of a that are bigger than 2;
# this returns a numpy array of Booleans of the same
# shape as a, where each slot of bool_idx tells
# whether that element of a is > 2.
print(bool_idx) # Prints "[[False False]
# [ True True]
# [ True True]]"
# We use boolean array indexing to construct a rank 1 array
# consisting of the elements of a corresponding to the True values
# of bool_idx
print(a[bool_idx]) # Prints "[3 4 5 6]"
# We can do all of the above in a single concise statement:
print(a[a > 2]) # Prints "[3 4 5 6]"
Panchatcharam M December 2025 150
Datatypes
import numpy as np
x = [Link]([1, 2]) # Let numpy choose the datatype
print([Link]) # Prints "int64"
x = [Link]([1.0, 2.0]) # Let numpy choose the datatype
print([Link]) # Prints "float64"
x = [Link]([1, 2], dtype=np.int64) # Force a particular datatype
print([Link])
Panchatcharam M December 2025 151
Array Operations
import numpy as np
x = [Link]([[1,2],[3,4]], dtype=np.float64)
y = [Link]([[5,6],[7,8]], dtype=np.float64)
# Elementwise sum; both produce the array
# [[ 6.0 8.0]
# [10.0 12.0]]
print(x + y)
print([Link](x, y))
# Elementwise difference; both produce the array
# [[-4.0 -4.0]
# [-4.0 -4.0]]
print(x - y)
print([Link](x, y))
Panchatcharam M December 2025 152
Array Operations
# Elementwise product; both produce the array
# [[ 5.0 12.0]
# [21.0 32.0]]
print(x * y)
print([Link](x, y))
# Elementwise division; both produce the array
# [[ 0.2 0.33333333]
# [ 0.42857143 0.5 ]]
print(x / y)
print([Link](x, y))
# Elementwise square root; produces the array
# [[ 1. 1.41421356]
# [ 1.73205081 2. ]]
print([Link](x))
Panchatcharam M December 2025 153
Array Operations
import numpy as np
x = [Link]([[1,2],[3,4]])
y = [Link]([[5,6],[7,8]])
v = [Link]([9,10])
w = [Link]([11, 12])
# Inner product of vectors; both produce 219
print([Link](w))
print([Link](v, w))
# Matrix / vector product; both produce the rank 1 array [29 67]
print([Link](v))
print([Link](x, v))
# Matrix / matrix product; both produce the rank 2 array
# [[19 22]
# [43 50]]
print([Link](y))
print([Link](x, y))
Panchatcharam M December 2025 154
Array Operations
import numpy as np
x = [Link]([[1,2],[3,4]])
print([Link](x)) # Compute sum of all elements; prints "10"
print([Link](x, axis=0)) # Compute sum of each column; prints "[4 6]"
print([Link](x, axis=1)) # Compute sum of each row; prints "[3 7]"
Panchatcharam M December 2025 155
Array Operations
import numpy as np
x = [Link]([[1,2], [3,4]])
print(x) # Prints "[[1 2]
# [3 4]]"
print(x.T) # Prints "[[1 3]
# [2 4]]"
# Note that taking the transpose of a rank 1 array does nothing:
v = [Link]([1,2,3])
print(v) # Prints "[1 2 3]"
print(v.T) # Prints "[1 2 3]"
Panchatcharam M December 2025 156
Python Scipy
Panchatcharam M
12/4/2025
Panchatcharam M December 2025 157
SciPy
◼ NumPy/SciPy – numerical and scientific
function libraries.
◼ Collection of mathematical algorithms
◼ NumPy extension
◼ Interactive python session by providing
the user with high-level commands
◼ Manipulating and visualizing data
◼ Data processing
◼ System prototyping like MATLAB, SciLab
Panchatcharam M December 2025 158
[Link]
Methods for Integrating Functions given a function object:
Method Explanation
quad General purpose integration
dblquad General purpose double integration
tplquad General purpose triple integration
fixed_quad Integrate function f(x) using Gaussian quadrature of order n
quadrature Integrate with given tolerance using Gaussian quadrature
romberg Integrate function using Romberg integration
Panchatcharam M December 2025 159
[Link]
Methods for Integrating Functions given a fixed samples:
Method Explanation
trapz Use trapezoidal rule to compute integral from samples
cumtrapz Use trapezoidal rule to cumulatively compute integral
simps Use Simpson's rule to compute integral from samples
romb Use Romberg Integration to compute integral from (2**k + 1)
evenly-spaced samples
Panchatcharam M December 2025 160
[Link]
Simple Integral example
𝑏
න sin 𝑥 𝑑𝑥
𝑎
[Link]!
Panchatcharam M December 2025 161
[Link]
Methods for Integrating Functions given a fixed samples:
#Integration
import numpy as np
import [Link]
print([Link]([Link],0,[Link]))
print([Link]([Link],-[Link],[Link]))
#Integration Sampling
x=[Link](0,[Link],10000000)
y=[Link](x)
print([Link](x,y))
[Link]
Panchatcharam M December 2025 162
Scipy contsants
from scipy import constants
print([Link])
for i,j in constants.physical_constants.items():
print(i,j)
Panchatcharam M December 2025 163
Scipy linalg
Linear Algebra
import numpy as np
from scipy import linalg
A = [Link]([[1, 2], [3, 4]])
b = [Link]([[5], [6]])
print("A: ",A)
print("b: ",b)
print("Inverse: of ",[Link](A))
print("Solution Ax=b",[Link](A,b))
print("Determinant of A: ", [Link](A))
print("Column Sum norm: ",[Link](A,1))
print("Row sum norm: ",[Link](A,[Link]))
Panchatcharam M December 2025 164
[Link]
Linear Algebra
#1D Interpolation
from [Link] import interp1d
import numpy as np
x = [Link](0, 10, num=21, endpoint=True)
y = [Link](-x**2/9.0)
f = interp1d(x, y)
f2 = interp1d(x, y, kind='cubic')
xnew = [Link](0, 10, num=51, endpoint=True)
import [Link] as plt
[Link](x, y, 'o', xnew, f(xnew), '-', xnew, f2(xnew), '--')
[Link](['data', 'linear', 'cubic'], loc='best')
[Link]()
Panchatcharam M December 2025 165
Other Scipy Submodules
Submodules Description
[Link] Special Functions
[Link] Fast Fourier Transforms
[Link] Signal Processing
[Link] Compressed Sparse Graph
[Link] Spatial Data structures, Delaunay, Simplices
[Link] Statistics
[Link] Multidimensional Image Processing
[Link] Input Output
[Link] Eigenvalues for large sparse matrices
Panchatcharam M December 2025 166
Python Matplotlib
Panchatcharam M
Associate Professor
Department of Mathematics and Statistics,
IIT Tirupati
Panchatcharam M December 2025 167
Matplotlib
◼ Plotting library
◼ Huge number of examples for tacking unique problems
Panchatcharam M December 2025 168
Matplotlib-plot function
◼ import matplotlib as mpl
◼ import [Link] as plt
◼ [Link](x_values, y_values, format_string [, x, y,
format, ])
Panchatcharam M December 2025 169
Matplotlib-plot function
◼ import matplotlib as mpl
◼ import [Link] as plt
◼ [Link](x_values, y_values, format_string [, x, y,
format, ])
◼ x_values and y_values: numpy arrays, if not, internal conversion to
numpy array
◼ format_string: the color and line type of the plot
◼ ‘bs’ blue squares
◼ ‘ro’: red circles
◼ Line properties: Set them via keyword arguments to the plot function.
◼ label, linewidth, animated, color, etc…
Panchatcharam M December 2025 170
Matplotlib-plot function
◼ import numpy as np
import [Link] as plt
# evenly sampled time at .2 intervals
t = [Link](0., 5., 0.2)
# red dashes, blue squares and green triangles
[Link](t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
[Link]([0, 6, 0, 150]) # x and y range of axis
[Link]()
Panchatcharam M December 2025 171
Matplotlib-plot function
◼ import numpy as np
import [Link] as plt
# evenly sampled time at .2 intervals
t = [Link](0., 5., 0.2)
# red dashes, blue squares and green triangles [Link](t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
[Link]([0, 6, 0, 150]) # x and y range of axis
[Link]()
Panchatcharam M December 2025 172
Matplotlib-plot function
import numpy as np
import [Link] as figure
t = [Link](0, 5, .2)
f = [Link]()
axes = f.add_subplot(111)
[Link](t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
[Link]([0, 6, 0, 150])
Panchatcharam M December 2025 173
Matplotlib-subplot function
◼ A script can generate multiple figures, but
typically you’ll only have one.
◼ To create multiple plots within a figure, either use the subplot()
function which manages the layout of the figure or use add_axes().
Panchatcharam M December 2025 174
Matplotlib-plot function
import numpy as np
import [Link] as plt
import [Link]
def Legendre(t,n):
p=[Link](n)
return p(t)
def Bessel(t,n):
return [Link](t,n)
t1 = [Link](0.0, 5.0, 0.1) #50
t2 = [Link](0.0, 5.0, 0.02) #250
[Link](1)
n=6
[Link](211) # 2 rows, 1 column, 1st plot
[Link](t1, Legendre(t1,n), 'bo', t2, Legendre(t2,n), 'k')
[Link](212) # 2 rows, 1 column, 2nd plot
[Link](t2, Bessel(t2,4), 'r--')
[Link]()
Panchatcharam M December 2025 175
Matplotlib-plot function
Panchatcharam M December 2025 176
Matplotlib-plot function
import numpy as np
import [Link] as plt
import [Link]
def Legendre(t,n):
p=[Link](n)
return p(t)
def Bessel(t,n):
return [Link](t,n)
t1 = [Link](-1.0, 1.0, 0.1)
t2 = [Link](-1.0, 1.0, 0.02)
[Link](1)
n=6
[Link](t1, Legendre(t1,n), 'bo', t2, Legendre(t2,n), 'k')
[Link](t2, -Bessel(t2,4), 'r--')
[Link](['$P_6(x)$','$-J_4(x)$'])
[Link]()
Panchatcharam M December 2025 177
Matplotlib-plot function
Panchatcharam M December 2025 178
Matplotlib-plot function
• text(): to add text in an arbitrary location
• xlabel(), ylabel(), title(), axes labels and title
• clear() removes all plots from the axes.
Panchatcharam M December 2025 179
Matplotlib-plot function
import numpy as np
from [Link] import norm
import [Link] as plt
mu, sigma = 100, 15
x = mu + sigma*[Link](100000)
# the histogram of the data
n, bins, patches = [Link](x, 50, density=True, facecolor='green', alpha=0.75)
# add a 'best fit' line
y = [Link]( bins, mu, sigma)
l = [Link](bins, y, 'r--', linewidth=1)
[Link]('Smarts')
[Link]('Probability')
[Link](r'$\mathrm{Histogram\ of\ IQ:}\ \mu=100,\ \sigma=15$')
[Link]([40, 160, 0, 0.03])
[Link](True)
[Link]()
Panchatcharam M December 2025 180
Matplotlib-plot function
Panchatcharam M December 2025 181
Matplotlib-plot function
#FDM Discretization
import numpy as np
x=[Link](0,1,num=10,endpoint=True)
y=[Link](0,1,num=10,endpoint=True)
X,Y=[Link](x,y)
import [Link] as plt
[Link](X,Y,'*')
[Link]([0,1,0,1])
[Link]()
Panchatcharam M December 2025 182
Matplotlib-plot function
Panchatcharam M December 2025 183
Exercises
Produce the following Graph using Matplotlib
Panchatcharam M December 2025 184
Exercises
Produce the following Graph using Matplotlib
Panchatcharam M December 2025 185
Matplotlib-plot function
import numpy as np
from [Link] import imread
import [Link] as plt
img = imread('[Link]')
img_tinted = img * [1, 0.95, 0.9]
[Link](1, 2, 1)
[Link](img)
[Link](1, 2, 2)
[Link](np.uint8(img_tinted))
[Link]()
Panchatcharam M December 2025 186
Matplotlib-plot function
##Dog
import numpy as np
from [Link] import imread
import [Link] as plt
def rgb2gray(rgb):
r, g, b = rgb[:,:,0], rgb[:,:,1], rgb[:,:,2]
return 0.2989 * r + 0.5870 * g + 0.1140 * b
img = imread('[Link]')
grayscale=rgb2gray(img)
print([Link])
[Link](1, 2, 1)
[Link](img)
[Link](1, 2, 2)
[Link](grayscale)
[Link]()
Panchatcharam M December 2025 187
Matplotlib-plot Slicing
[Link](2, 2, 1)
[Link](img)
[Link](2, 2, 2)
[Link](grayscale)
[Link](2, 2, 3)
[Link](grayscale[150:600,650:1150])
[Link]()
Panchatcharam M December 2025 188
Exercises
Produce the following Graph using Matplotlib
Panchatcharam M December 2025 189
Matplotlib-plot function
import [Link] as plt
labels = 'BTech', 'MTech', 'MS', 'PhD'
sizes = [100, 30, 15, 10]
explode = (0.1, 0.1, 0, 0) # only "explode"
fig1, ax1 = [Link]()
[Link](sizes, explode=explode,
labels=labels, autopct='%1.1f%%',
shadow=True, startangle=90)
[Link]('equal')
[Link]()
Panchatcharam M December 2025 190
Matplotlib-plot function
import [Link] as plt
import numpy as np
fig = [Link]()
ax = fig.add_subplot(111, projection='3d')
# Make data
u = [Link](0, 2 * [Link], 100)
v = [Link](0, [Link], 100)
x = 10 * [Link]([Link](u), [Link](v))
y = 10 * [Link]([Link](u), [Link](v))
z = 10 * [Link]([Link]([Link](u)),
[Link](v))
# Plot the surface
ax.plot_surface(x, y, z, color='b')
[Link]()
Panchatcharam M December 2025 191
Matplotlib Challenge
Reproduce the following 3D Heart Equation
Panchatcharam M December 2025 192
End of Python Basics
12/4/2025 193