Python Notes
Python Notes
Class Notes
Lecture 1: Introduction
What is Python?
Python is a very popular general-purpose interpreted,
interactive, object-oriented, and high-level programming
language.
Python is dynamically-typed and garbage-collected programming
language.
Python is a programming language as well as a scripting
language.
It was created by Guido van Rossum during 1985- 1990.
2 9/28/2025
Differences between program
and scripting language
3 9/28/2025
Why to Learn Python?
Python is consistently rated as one of the world's most popular
programming languages.
4 9/28/2025
Why to Learn Python?
There are many other good reasons which makes Python as the
top choice of any programmer:
5 9/28/2025
Advantages of learning Python
Python is Interpreted − Python is processed at runtime by the
interpreter. You do not need to compile your program before
executing it. This is similar to PERL and PHP.
Python is Interactive − You can actually sit at a Python prompt
and interact with the interpreter directly to write your programs.
Python is Object-Oriented − Python supports Object-
Oriented style or technique of programming that encapsulates
code within objects.
Python is a Beginner's Language − Python is a great
language for the beginner-level programmers and supports the
development of a wide range of applications from simple text
processing to WWW browsers to games.
6 9/28/2025
Characteristics of Python
It supports functional and structured programming methods as
well as OOP.
It can be used as a scripting language or can be compiled to byte-
code for building large applications.
It provides very high-level dynamic data types and supports
dynamic type checking.
It supports automatic garbage collection.
It can be easily integrated with C, C++, COM, ActiveX, CORBA,
and Java.
7 9/28/2025
Applications of Python
Easy-to-learn − Python has few keywords, simple structure, and
a clearly defined syntax. This allows the student to pick up the
language quickly.
Easy-to-read − Python code is more clearly defined and visible
to the eyes.
Easy-to-maintain − Python's source code is fairly easy-to-
maintain.
A broad standard library − Python's bulk of the library is very
portable and cross-platform compatible on UNIX, Windows, and
Macintosh.
Interactive Mode − Python has support for an interactive
mode which allows interactive testing and debugging of snippets
of code.
8 9/28/2025
Applications of Python
Portable − Python can run on a wide variety of hardware
platforms and has the same interface on all platforms.
Extendable − You can add low-level modules to the Python
interpreter. These modules enable programmers to add to or
customize their tools to be more efficient.
Databases − Python provides interfaces to all major commercial
databases.
GUI Programming − Python supports GUI applications that
can be created and ported to many system calls, libraries and
windows systems, such as Windows MFC, Macintosh, and the X
Window system of Unix.
Scalable − Python provides a better structure and support for
large programs than shell scripting.
9 9/28/2025
Installing Python
Windows Installation
Open a Web browser and go
to https://www.python.org/downloads/.
From the above link download latest
version of python IDE and install, recent
version is 3.11.5
But most of the people uses version 2.7.7
only.
After installing version 2.7.7 , go to start
menu, click on python 2.7, select
python(command line), it will prompt with
>>>
10 9/28/2025
Installing Python
11 9/28/2025
Running Python
Example
12 9/28/2025
Python code execution
13 9/28/2025
Python Identifiers
A Python identifier is a name used to identify a variable, function,
class, module or other object.
An identifier starts with a letter A to Z or a to z or an underscore
(_) followed by zero or more letters, underscores and digits (0 to
9).
Python does not allow punctuation characters such as @, $, and %
within identifiers.
Python is a case sensitive programming language.
Thus, Manpower and manpower are two different
identifiers in Python.
14 9/28/2025
Python Identifiers
Class names start with an uppercase letter. All other identifiers
start with a lowercase letter.
Starting an identifier with a single leading underscore indicates
that the identifier is private.
Starting an identifier with two leading underscores indicates a
strongly private identifier.
If the identifier also ends with two trailing underscores, the
identifier is a language-defined special name.
15 9/28/2025
Reserved Words
16 9/28/2025
Lines and Indentation
Python provides no braces to indicate blocks of code for class and
function definitions or flow control.
Blocks of code are denoted by line indentation, which is rigidly
enforced.
The number of spaces in the indentation is variable, but all
statements within the block must be indented the same amount.
For example −
17 9/28/2025
Lines and Indentation
However, the following block generates an error −
18 9/28/2025
Multi-Line Statements
Statements in Python typically end with a new line.
Python does, however, allow the use of the line continuation
character (\) to denote that the line should continue.
For example −
19 9/28/2025
Multi-Line Statements
Statements contained within the [], {}, or () brackets do not need
to use the line continuation character. For example −
20 9/28/2025
Quotation in Python
Python accepts single ('), double (") and triple (''' or """) quotes
to denote string literals, as long as the same type of quote starts
and ends the string.
The triple quotes are used to span the string across multiple lines.
For example, all the following are legal −
21 9/28/2025
Comments in Python
A hash sign (#) that is not inside a string literal begins a comment.
All characters after the # and up to the end of the physical line are
part of the comment and the Python interpreter ignores them.
22 9/28/2025
Variable
Variables are nothing but reserved memory locations to store
values. This means that when you create a variable you reserve
some space in memory.
Based on the data type of a variable, the interpreter allocates
memory and decides what can be stored in the reserved memory.
Therefore, by assigning different data types to variables, you can
store integers, decimals or characters in these variables.
23 9/28/2025
Assigning Values to Variables
Python variables do not need explicit declaration to reserve
memory space. The declaration happens automatically when you
assign a value to a variable.
24 9/28/2025
Multiple Assignment
Python allows you to assign a single value to several variables
simultaneously. For example −
Here, an integer object is created with the value 1, and all three
variables are assigned to the same memory location.
You can also assign multiple objects to multiple variables. For
example −
25 9/28/2025
Scope of Variable
A variable's scope is basically the lifespan of that variable. It is the
section of code to which a variable is alive. Depending on their
scope, variables are divided into:
I. Global variables
II. Local variables
26 9/28/2025
Local variables
• Local variables are declared inside the function blocks. In
Python, local variables can be declared at any location in the code
block.
• Only statements that are written inside a function can access local
variables. They are secure in the way that no other function or
variable of that program can access them.
Output: 10
27 9/28/2025
Global variables
• Global variables are the types of variables that are declared
outside of every function of the program.
• The global variable, in contrast to local variables, is accessible by
all functions in a program. Global variables are not very reliable
because any function in the program can alter its value.
Output: 10
28 9/28/2025
Standard Data Types
Python has five standard data types −
➢ Numbers
➢ String
➢ List
➢ Tuple
➢ Dictionary
29 9/28/2025
Python Numbers
Number data types store numeric values. Number objects are
created when you assign a value to them.
For example −
You can also delete the reference to a number object by using the
del statement. The syntax of the del statement is −
30 9/28/2025
Python Numbers
Python supports four different numerical types −
➢ int (signed integers)
➢ long (long integers, they can also be represented in octal and
hexadecimal)
➢ float (floating point real values)
➢ complex (complex numbers)
31 9/28/2025
Python Strings
Strings in Python are identified as a contiguous set of characters
represented in the quotation marks.
Python allows for either pairs of single or double quotes.
Subsets of strings can be taken using the slice operator ([ ] and [:] )
with indexes starting at 0 in the beginning of the string and
working their way from -1 at the end.
The plus (+) sign is the string concatenation operator and the
asterisk (*) is the repetition operator.
32 9/28/2025
Python Strings
For example −
33 9/28/2025
Python List Data Type
Python Lists are the most versatile compound data types.
A Python list contains items separated by commas and enclosed
within square brackets ([]).
The values stored in a Python list can be accessed using the slice
operator ([ ] and [:]) with indexes starting at 0 in the beginning of
the list and working their way to end -1.
The plus (+) sign is the list concatenation operator,
The asterisk (*) is the repetition operator.
34 9/28/2025
Python List Data Type
For example −
35 9/28/2025
Python Tuple Data Type
Python tuple is another sequence data type that is similar to a list.
A Python tuple consists of a number of values separated by
commas.
Unlike lists, however, tuples are enclosed within parentheses.
The main differences between lists and tuples are: Lists are
enclosed in brackets ( [ ] ) and their elements and size can be
changed, while tuples are enclosed in parentheses ( ( ) ) and
cannot be updated.
Tuples can be thought of as read-only lists.
36 9/28/2025
Python Tuple Data Type
For example −
37 9/28/2025
Python Dictionary
Python dictionaries are kind of hash table type.
They work like associative arrays or hashes found in Perl and consist
of key-value pairs.
A dictionary key can be almost any Python type, but are usually
numbers or strings.
Values, 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 ([]).
Python dictionaries have no concept of order among elements. It is
incorrect to say that the elements are "out of order"; they are simply
unordered.
38 9/28/2025
Python Dictionary
For example −
39 9/28/2025
Python Boolean Data Types
Python Boolean type is one of built-in data types which represents
one of the two values either True or False.
Python bool() function allows you to evaluate the value of any
expression and returns either True or False based on the expression.
Following is a program which prints the value of Boolean variables a
and b −
40 9/28/2025
Python Data Type Conversion
To convert data between different Python data types, simply use the
type name as a function.
Conversion to int
An example to convert number, float and string into integer data type:
41 9/28/2025
Python Data Type Conversion
Conversion to float
An example to convert number, float and string into float data type:
42 9/28/2025
Python Data Type Conversion
Conversion to string
An example to convert number, float and string into string data type:
43 9/28/2025
Data Type Conversion Functions
44 9/28/2025
Data Type Conversion Functions
45 9/28/2025
Data Type Conversion Functions
46 9/28/2025
Python Operators
Python operators are the constructs which can manipulate the value
of operands.
These are symbols used for the purpose of logical, arithmetic and
various other operations.
Types of Python Operators
Python language supports the following types of operators.
➢ Arithmetic Operators
➢ Comparison (Relational) Operators
➢ Assignment Operators
➢ Logical Operators
➢ Bitwise Operators
➢ Membership Operators
➢ Identity Operators
47 9/28/2025
Python Arithmetic Operators
Python arithmetic operators are used to perform mathematical
operations on numerical values.
48 9/28/2025
Python Arithmetic Operators
49 9/28/2025
Python Comparison Operators
Python comparison operators compare the values on either sides of
them and decide the relation among them. They are also called
relational operators.
50 9/28/2025
Python Comparison Operators
51 9/28/2025
Python Assignment Operators
Python assignment operators are used to assign values to
variables.
52 9/28/2025
Python Assignment Operators
53 9/28/2025
Python Logical Operators
There are following logical operators supported by Python language.
Assume variable a holds 10 and variable b holds 20 then
54 9/28/2025
Python Membership Operators
Python’s membership operators test for membership in a sequence,
such as strings, lists, or tuples. There are two membership operators as
explained below −
55 9/28/2025
Python Identity Operators
Identity operators compare the memory locations of two objects.
There are two Identity operators explained below −
56 9/28/2025
Python - Decision Making
Decision making is anticipation of conditions occurring while
execution of the program and specifying actions taken according to
the conditions.
Following is the general form of a typical decision making structure
found in most of the programming languages −
1. If statements
2. If…else statements
3. Nested if statements
57 9/28/2025
Python if Statement
The if statement contains a logical expression using which data is
compared and a decision is made based on the result of the
comparison.
58 9/28/2025
Python if Statement
59 9/28/2025
Python if…else Statement
An else statement can be combined with an if statement. An else
statement contains the block of code that executes if the conditional
expression in the if statement resolves to 0 or a FALSE value.
60 9/28/2025
Python if…else Statement
61 9/28/2025
The elif Statement
The elif statement allows to check multiple expressions for TRUE and
execute a block of code as soon as one of the conditions evaluates to
TRUE.
62 9/28/2025
The elif Statement
63 9/28/2025
Python - Loops
• In general, statements are executed sequentially: The first statement
in a function is executed first, followed by the second, and so on.
There may be a situation when you need to execute a block of code
several number of times.
• Programming languages provide various
control structures that allow for more
complicated execution paths.
• A loop statement allows us to execute a
statement or group of statements multiple
times. The following diagram illustrates a
loop statement −
64 9/28/2025
Python - Loops
• Python programming language provides following types of
loops to handle looping requirements.
1. while loop
2. for loop
3. nested loops
65 9/28/2025
Python while Loop Statements
• A while loop statement in Python programming language
repeatedly executes a target statement as long as a given
condition is true.
Syntax
while expression:
statement(s)
while expression:
statement(s)
68 9/28/2025
Using else Statement with
while Loop
• Python supports to have an else statement associated with a
loop statement.
• If the else statement is used with a while loop, the else
statement is executed when the condition becomes false.
69 9/28/2025
Python for Loop Statements
It has the ability to iterate over the items of any sequence, such as a list or a
string.
Syntax
for iterating_var in sequence:
statements(s)
71 9/28/2025
Python for Loop Statements
Iterating by Sequence Index
An alternative way of iterating through each item is by index offset
into the sequence itself. Following is a simple example −
72 9/28/2025
Using else Statement with
for Loop
Python supports to have an else statement associated with a loop
statement
If the else statement is used with a for loop, the else statement is
executed when the loop has exhausted iterating the list.
73 9/28/2025
Python-Nested loops
Python programming language allows to use one loop inside another
loop. Following section shows few examples to illustrate the
concept.
74 9/28/2025
Python-Nested loops
Example: Output:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
75 97 is prime 9/28/2025
Good bye!
Loop Control Statements
Loop control statements change execution from its normal sequence.
When execution leaves a scope, all automatic objects that were
created in that scope are destroyed.
76 9/28/2025
Python break statement
It terminates the current loop and resumes execution at the
next statement, just like the traditional break statement in C.
Example:
Output:
77 9/28/2025
Python continue statement
It causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating. The continue statement can
be used in both while and for loops.
Example:
Output:
78 9/28/2025
Python pass statement
The pass statement in Python is used when a statement is required
syntactically but you do not want any command or code to
execute.
The pass statement is a null operation; nothing happens when
it executes. The pass is also useful in places where your code
will eventually go, but has not been written yet
Example: Output:
79 9/28/2025
Python Numbers
Number data types store numeric values. Number objects are
created when you assign a value to them.
For example −
You can also delete the reference to a number object by using the
del statement. The syntax of the del statement is −
80 9/28/2025
Python Numbers
Python supports four different numerical types −
➢ int (signed integers)
➢ long (long integers, they can also be represented in octal and
hexadecimal)
➢ float (floating point real values)
➢ complex (complex numbers)
81 9/28/2025
Python Numbers
Mathematical Functions
Python includes following functions that perform mathematical
calculations.
82 9/28/2025
Python Numbers
83 9/28/2025
Python Numbers
84 9/28/2025
Python-Strings
Creating strings is as simple as assigning a value to a variable.
For example −
To access substrings, use the square brackets for slicing along with
the index or indices to obtain your substring.
For example −
Output-
85 9/28/2025
Python-Strings
Built-in String Methods
86 9/28/2025
Python-Strings
Built-in String Methods
87 9/28/2025
Python-Strings
Built-in String Methods
88 9/28/2025
Python-Lists
The most basic data structure in Python is the sequence.
Each element of a sequence is assigned a number - its position or
index.
The first index is zero, the second index is one, and so forth.
The list is a most versatile datatype available in Python which can be
written as a list of comma-separated values (items) between square
brackets.
Important thing about a list is that items in a list need not be of the
same type.
89 9/28/2025
Python-Lists
Creating a list is as simple as putting different comma-separated
values between square brackets.
To access values in lists, use the square brackets for slicing along with
the index or indices to obtain value available at that index.
For example −
Output-
90 9/28/2025
Python-Lists
Updating Lists
Updating single or multiple elements of lists is possible by giving the
slice on the left-hand side of the assignment operator, and we can add to
elements in a list with the append() method. For Example-
Output-
91 9/28/2025
Python-Lists
Delete List Elements
To remove a list element, you can use either the del statement if you
know exactly which element(s) you are deleting or the remove()
method if you do not know. For example −
Output-
92 9/28/2025
Python-Lists
Indexing, Slicing, and Matrixes
Because lists are sequences, indexing and slicing work the same way for
lists as they do for strings.
Assuming following input −
L = ['spam', 'Spam', 'SPAM!']
93 9/28/2025
Python-Lists
Built-in List Functions & Methods
94 9/28/2025
Python-Tuple
A tuple is a collection of objects which ordered and immutable. Tuples are
sequences, just like lists. The differences between tuples and lists are, the
tuples cannot be changed unlike lists and tuples use parentheses, whereas lists
use square brackets.
To explicitly remove an entire tuple, just use the del statement. For
example −
tup = ('physics', 'chemistry', 1997, 2000);
print tup;
del tup;
print "After deleting tup : ";
print tup;
98 9/28/2025
Python-Tuple
This produces the following result:
99 9/28/2025
Python-Tuple
Basic Tuples Operations
100 9/28/2025
Python-Tuple
Indexing, Slicing, and Matrixes
Because tuples are sequences, indexing and slicing work the same way
for tuples as they do for strings. Assuming following input −
101 9/28/2025
Python-Tuple
Built-in Tuple Functions
102 9/28/2025
Python-Dictionary
Each key is separated from its value by a colon (:), the items are
separated by commas, and the whole thing is enclosed in curly
braces.
An empty dictionary without any items is written with just two curly
braces, like this: {}.
Keys are unique within a dictionary while values may not be.
The values of a dictionary can be of any type, but the keys must be of
an immutable data type such as strings, numbers, or tuples.
103 9/28/2025
Python-Dictionary
Accessing Values in Dictionary
To access dictionary elements, you can use the familiar square brackets
along with the key to obtain its value. Following is a simple example −
104 9/28/2025
Python-Dictionary
Updating Dictionary
Dictionary can be updated by adding a new entry or a key-value pair,
modifying an existing entry, or deleting an existing entry as shown
below in the simple example −
105 9/28/2025
Python-Dictionary
Delete Dictionary Elements
You can either remove individual dictionary elements or clear the entire
contents of a dictionary.
106 9/28/2025
Python-Dictionary
Built-in Dictionary Functions & Methods
107 9/28/2025
Python - Functions
A function is a block of organized, reusable code that is used to perform
a single, related action. Functions provide better modularity for your
application and a high degree of code reusing.
Defining a Function
Function blocks begin with the keyword def followed by the function
name and parentheses ( ( ) ).
Any input parameters or arguments should be placed within these
parentheses.You can also define parameters inside these parentheses.
The first statement of a function can be an optional statement - the
documentation string of the function or docstring.
The code block within every function starts with a colon (:) and is
indented.
108 9/28/2025
Python - Functions
Defining a Function
Example:
109 9/28/2025
Python - Functions
Calling a Function
Defining a function only gives it a name, specifies the parameters that
are to be included in the function and structures the blocks of code.
Output:
Hello from a function 9/28/2025
110
Python - Functions
Arguments
Information can be passed into functions as arguments.
Arguments are specified after the function name, inside the parentheses.
You can add as many arguments as you want, just separate them with a
comma. The following example has a function with one argument
(fname). When the function is called, we pass along a first name, which
is used inside the function to print the full name:
Example:
Output:
Emil Refsnes
Tobias Refsnes
111 Linus Refsnes 9/28/2025
Python - Functions
Function Arguments
You can call a function by using the following types of formal arguments
−
Required arguments
Keyword arguments
Default arguments
Variable-length arguments
112 9/28/2025
Python - Functions
Required arguments
Required arguments are the arguments passed to a function in correct
positional order. Here, the number of arguments in the function call
should match exactly with the function definition.
113 9/28/2025
Python - Functions
114 9/28/2025
Python - Functions
Keyword arguments
Keyword arguments are related to the function calls. When you use
keyword arguments in a function call, the caller identifies the
arguments by the parameter name.
This allows you to skip arguments or place them out of order because
the Python interpreter is able to use the keywords provided to match
the values with parameters. You can also make keyword calls to the
printme() function in the following ways −
Output:
My string
115 9/28/2025
Python - Functions
Default arguments
A default argument is an argument that assumes a default value if a
value is not provided in the function call for that argument.
Output:
Name: miki
Age 50
Name: miki
Age 35
116 9/28/2025
Python - Functions
Variable-length arguments
You may need to process a function for more arguments than you
specified while defining the function. These arguments are called
variable-length arguments and are not named in the function definition,
unlike required and default arguments.
Output:
Output is:
10
Output is:
70
60
50
118 9/28/2025
Python Lambda
These functions are called anonymous because they are not declared
in the standard manner by using the def keyword.We can use the
lambda keyword to create small anonymous functions.
Lambda forms can take any number of arguments but return just
one value in the form of an expression.They cannot contain
commands or multiple expressions.
An anonymous function cannot be a direct call to print because
lambda requires an expression
Lambda functions have their own local namespace and cannot
access variables other than those in their parameter list and those
in the global namespace.
119 9/28/2025
Python Lambda
Syntax:
120 9/28/2025
Python Lambda
Example:
121 9/28/2025
Python-Object Oriented
class MyClass:
x=5
p1 = MyClass()
print(p1.x) Output: 5
125 9/28/2025
The __init__() Function
All classes have a function called __init__(), which is always
executed when the class is being initiated.
Use the __init__() function to assign values to object
properties, or other operations that are necessary to do when
the object is being created:
126 9/28/2025
The __init__() Function
Example
Create a class named Person, use the __init__() function to
assign values for name and age:
Output:
John
36
Output:
128 9/28/2025
The __str__() Function
Example: The string representation of an object WITH
the __str__() function:
Output:
John(36)
129 9/28/2025
Object Methods
Objects can also contain methods. Methods in objects are
functions that belong to the object.
Let us create a method in the Person class:
Output:
Hello my name is John
130 9/28/2025