0% found this document useful (0 votes)
41 views385 pages

Introduction to Python Programming

The document provides an introduction to Python programming, emphasizing its importance for automating tasks and solving problems. It covers the features, advantages, and disadvantages of Python, as well as its applications in various fields like game development, machine learning, and web scraping. Additionally, it discusses Python's syntax, variable management, and memory storage concepts.

Uploaded by

stanishka047
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
41 views385 pages

Introduction to Python Programming

The document provides an introduction to Python programming, emphasizing its importance for automating tasks and solving problems. It covers the features, advantages, and disadvantages of Python, as well as its applications in various fields like game development, machine learning, and web scraping. Additionally, it discusses Python's syntax, variable management, and memory storage concepts.

Uploaded by

stanishka047
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming (CST310)

Lecture 01: Introduction to Programming & Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
August 11, 2025
Syllabus
Why to Program?
Why to Learn Programming Language?
Computers Want to be Helpful...
• Computers are built for one purpose - to
do things for us What
Next?
• But we need to speak their language to
describe what we want done.

• Learning Programming is important to give


instructions & to make the hardware to
work as we want. What What What
Next? Next? Next?
• Users have it easy - someone already put
many different programs (instructions) into What What What
the computer and users just pick the ones Next? Next? Next?
they want to use
Users vs. Programmers
• Users see computers as a set of tools - word processor, spreadsheet, map,
to-do list, etc.

• Programmers learn the computer “ways” and the computer language

• Programmers have some tools that allow them to build new tools

• Programmers sometimes write tools for lots of users and sometimes


programmers write little “helpers” for themselves to automate a task
Why be a Programmer?

• To get a good JOB (Secondary Goal)


• To be able to write code to automate your tasks and to solve some
of your problems (Primary Goal).
• To produce something for others to use.
User

Computer
Programmer
Hardware + Software

Data Information .... Networks

From a software creator’s point of view, we build the software. The end
users (stakeholders/actors) are our masters - who we want to please -
often they pay us money when they are pleased. But the data,
information, and networks are our problem to solve on their behalf.
The hardware and software are our friends and allies in this quest.
What is Code? Software? A Program?

• A sequence of stored instructions

- It is a little piece of our intelligence in the computer

• A piece of creative art - particularly when we do a good job on user


experience
Programs for Python...
the clown ran after the car and the car ran into the tent and
the tent fell down on the clown and the car

Task 1: Count the number of Words in the given Text.


Task 2: Which is the mostly used word in the given text?
Python Code to automate the Word Count Task
name = input('Enter file:')
handle = open(name)

counts = dict() python [Link]


for line in handle:
words = [Link]() Enter file: [Link]
for word in words: to 16
counts[word] = [Link](word,0) + 1

bigcount = None
bigword = None
for word,count in [Link]():
if bigcount is None or count > bigcount:
bigword = word python [Link]
bigcount = count Enter file: [Link]
the 7
print(bigword, bigcount)
Why to use and Learn Python?
1. Easy to Read, Learn and Write
Python is a high-level programming language that has English-
like syntax. This makes it easier to read and understand the code.
Python is really easy to pick up and learn, that is why a lot of
people recommend Python to beginners. You need less lines of
code to perform the same task as compared to other major
languages like C/C++ and Java.
2. Improved Productivity
Python is a very productive language. Due to the simplicity of
Python, developers can focus on solving the problem.
They don’t need to spend too much time in understanding the
syntax or behavior of the programming language. You write less
code and get more things done.
Why to use and Learn Python?
3. Interpreted Language
Python is an interpreted language which means that Python
directly executes the code line by line. In case of any error, it
stops further execution and reports back the error which has
occurred.
Python shows only one error even if the program has multiple
errors. This makes debugging easier.
4. Dynamically Typed
Python doesn’t know the type of variable until we run the code.
It automatically assigns the data type during execution.
The programmer doesn’t need to worry about declaring
variables and their data types.
Why to use and Learn Python?
5. Vast Libraries Support
The standard library of Python is huge, you can find almost all
the functions needed for your task.
6. Portability
In many languages like C/C++, you need to change your code to
run the program on different platforms.
That is not the same with Python. You only write once and
run it anywhere.
Disadvantages of Python
1. Slow Speed:
Python is an interpreted language and dynamically-typed
language. The line by line execution of code often leads to slow
execution.
The dynamic nature of Python is also responsible for the slow
speed of Python because it has to do the extra work while
executing code. So, Python is not used for purposes where speed
is an important aspect of the project.
Applications of Python
1. Game Development: There are libraries such as PySoy which is a 3D game
engine supporting Python 3, PyGame which provides functionality and a library
for game development. Games such as Civilization-IV, Disney’s Toontown
Online, Vega Strike etc. have been built using Python.
2. Machine Learning, Artificial Intelligence and Data Science: Pandas, Scikit-
Learn, NumPy, etc. are few python libraries for ML and AI. Matplotlib, Seaborn,
which are helpful in plotting graphs and much more.
3. Web Scraping: Python is a savior when it comes to pull a large amount of data
from websites which can then be helpful in various real-world processes such
as price comparison, job listings, research and development and much more.
4. Network Security and audit Tools
5. Research
6. Drone Programming
7. Computer Vision
PYTHON Programming (CST310)
Lecture 2:
Introduction to PYTHON Programming,
Installation,
Identifiers
Variables

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
August 12, 2025
Python Programming Language
• Python is a general-purpose interpreted, interactive, object-oriented,
and high-level programming language.
• It was created by Guido van Rossum during 1985- 1990.
• Like Perl, Python source code is also available under the GNU General
Public License (GPL).

Used by:
• Google, Yahoo!, Youtube, Netflix, Facebook, Instagram
• Many Linux distributions
• Games and apps (e.g. Eve Online)
Few Features of 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.
• Easy to read and Learn: Python has few keywords, simple structure, and a clearly defined
syntax.
• Python supports 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.
• A broad support for libraries
• Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
• Databases: Python provides interfaces to all major commercial databases.
• GUI Applications can be designed in python using libraries like Tkinter.
History of Python
• Python was developed by Guido van Rossum in the late eighties and
early nineties at the National Research Institute for Mathematics and
Computer Science in the Netherlands.

• Python is derived from many other languages, including ABC, Modula-


3, C, C++, Algol-68, SmallTalk, and Unix shell and other scripting
languages.

• Python is copyrighted. Like Perl, Python source code is available


under the GNU General Public License (GPL).
Installing Python
• Python comes pre-installed in Operating Systems like Linux and Mac
OS X.
• In Windows, it does not come pre-installed.
• So, for installing the python on WINDOWS based OS,
goto : [Link]
Python has two main different versions:
1. Python 2.7: Support for python 2 has stopped and is no longer used much.
2. Python 3: Python 3 is used nowadays.
Python 2.7 was widely used in early days, however, in python 3 various
improvements and syntax changes were incorporated.
So, python 3 is not backward compatible with the Python 2, i.e., code of
python 3 will not work in python 2 and vice-versa.
Running Python
There are two different ways to start Python:
1. Interactive Interpreter using CMD
2. Python IDLE (Integrated Development and Learning Environment) :
You can run Python from a Graphical User Interface (GUI)
environment as well.
First Python Program
You can write your python program in one of following modes:
1. Interactive Mode: You interact directly with the python interpreter.
In this mode, whatever python statement you will write,
interpreter will give you its output as soon as you press the return key
(Enter).
This mode is used when you want to test and execute some 2-3
python Statements
This mode can be used as calculator also.
This mode is not used when you want to write code for solving complex
problems.
First Python Program
2. Script Mode: So, script mode is used for writing long codes in
python.
When we want to write a program, we use a text editor to write the
Python instructions into a file, which is called a script.
By convention, Python scripts have names that end with .py

[Link]
Our First Python Program
• Python does not have a main method like Java
• The program's main code is just written directly in the file
• Python statements do not end with semicolons
Comments in Python
• Comments are used for proper documentation of programs.
• They are used to tell you ‘what a particular piece of code does’ in English.
• They are also used to disable parts of your program if you need to remove them
temporarily.
There are two types of Comments:
1. Single Line Comments: # is used for commenting a line of code in python.

2. Multi Line Comments


Ït can be done using
Identifiers in Python
• Identifiers means the possible legal name that can be given to a variable,
function, class or object.
• A Python identifier is a name used to identify a variable, function, class,
module or other object.
• A legal identifier will follow the following rules
• Identifier will always start with an alphbhet (a-z or A-Z) or underscore _)
• And it can have zero or more alphabets, underscore and digit (0-9)

Which of following are Valid Variable Names?


_variable1
Variable_1
1variable
$name
Name$
______
Variables in Python
• Variables are nothing but reserved memory locations to store some values.
• Variables are the name given to a memory location.
• It is a basic unit of storage in a program.
• Variables in Python are not statically typed.
• The variables are dynamically typed in Python. We do not need to declare variables before using
them or declare their type. A variable is created the moment we first assign a value to it
• The data-types of a variable is given to that variable during the execution based upon the value that
is stored by the user in that variable.
age=10
will create a variable with name age and value 10.
Since, value 10 is stored in variable age, so during the execution, python interpreter will give the type
Integer to this variable.
• To check the datatype of any variable, use the type() function as :
type(variable_name)
• The value stored in a variable can be changed during program execution.
• A variable is only a name given to a memory location, all the operations done on the variable effects
that memory location.
Printing the value of a Variable in Python

A=10
print(A)

Output will be: 10


Similarly,
print(“value of variable A is ”,A)

Output will be: value of variable A is 10


• If we have following two variables:
fname=“John”
lname=“Smith”

How you will get the output as following using the above two variables:
My first name is John and My last name is Smith
How you will get the output as following using the above two variables:
My first name is John and My last name is Smith

print(“My first name is”,fname,”My last name is”,lname);


Age=10
AGE=20
age=30
If we declare the above three variables with same name, then what will
be the output of following statement

print(AGE)
Python is a Case-Sensitive Language
Age=10
AGE=20
age=30

print(AGE) #20
print(age) #30
How Variables are stored in memory
• Whenever you write the statement
‘a=100’
Object of type integer with value 100 is getting stored in some memory
location and variable with name “a” is pointing to that memory location.
So, variable with name “a” will point to a memory location where object 100
is stored.
You can check the memory location by id(variable_name)
id(a)
You can check the data-type of the variable using
type(a)
How Variables are stored in memory
Suppose, a=100
id(a) gives some memory location
If, we write a=200, then object with value 200 will be stored in some
new memory location and variable with name a will start pointing to
that memory location of 200.
id(a) will give new value.
How Variables are stored in memory
Suppose, a=100
b=100
So, here b will point to the same memory location where a was
pointing.
Because, value 100 was already stored as an object in some memory
location and for proper memory utilization, python does not store the
same value.
So, variable will point to the same memory location.
id(a)
Id(b)
How Variables are stored in memory
There are two types of memory which are used by python
• Stack Memory: used for storing the state of the program
• Stack memory is used for managing function calls and local variables within those
functions.
• When you call a function in Python, a new block (or frame) is added to the stack. This
frame contains all the local variables and context needed for that function.
• The stack follows the LIFO principle. The last function call made is the first one to be
completed and removed from the stack.
• Once a function completes its execution, its stack frame is automatically removed from
the stack, and the memory is freed.
• Heap Memory: used for storing the variables/objects
• Heap memory is where Python stores objects and data that need to persist beyond the
lifetime of a single function call.
• This includes global variables, objects, and any dynamically allocated memory.
• Objects are created and allocated memory in the heap. They remain there until they are
no longer needed and are garbage collected.
How Stack and Heap Work Together:
When you define a variable in a function
(e.g., a = 10),
a is stored in the stack frame of that function, but the actual integer object 10
resides in the heap.

The stack contains references (or pointers) to objects in the heap.


When the function finishes, the reference is removed from the stack, but the
object may still exist in the heap if there are other references to it.
How Variables are stored in memory
Python manager uses the concept called Reference counting, whenever a new
object is created it will update the reference count of the object.
A=100
b=100
Here, python memory manager creates only one object i.e "100" and reference
count is "2".
Whenever a new object is created python manager will checks the memory for
the object.
If object already exists python manager will not create new object instead it
references the name to the object and increases the reference counter of the
object.
Interned Small Integers and Interned Small Strings
• In Python, heap memory is used to store objects.
• Most objects are regular objects that are created on demand in the heap and managed by Python’s garbage
collector (GC).
• Python uses reference counting as the primary memory management technique. When an object’s reference
count reaches 0, it becomes eligible for deallocation. In CPython, memory for such objects is eventually freed
(often returned to Python’s internal memory allocator, not always immediately to the OS).
However, there are some special cases:
• Interned small integers: In Python, integers in the range -5 to 256 are preallocated in the heap at interpreter
startup. These objects persist for the entire lifetime of the program. Any variable assigned a value in this
range will refer to the same preallocated object (id() will return the same value every time).
• Interned strings: Certain short and identifier-like strings (e.g., variable names, some literals) are interned by
default, meaning a single shared object is used. These also live for the program’s lifetime. Additional strings
can be interned manually using [Link]().
• Floating-point numbers are not interned by default, since there are too many possible values and they’re
more expensive to store/cache.
So:
a = 256 and b = 256 → same object (id(a) == id(b) is True).
a = 256.0 and b = 256.0 → different objects (id(a) != id(b) is usually True)
Re-declaring the Variable:
We can re-declare the python variable once we have declared the
variable already.
Number = 100
print(“Initial Value: ", Number)

# re-declare the var


Number = 120.3
print("After re-declare:", Number)
Assigning a single value to multiple variables:
• Also, Python allows assigning a single value to several variables
simultaneously with “=” operators.
a = b = c = 10
print(a)
print(b)
print(c)
Assigning different values to multiple
variables:
• Python allows adding different values in a single line with
“,”operators.
a, b, c = 1, 20.2, “Nit Srinagar“
print(a)
print(b)
print(c)
Can we use the same name for different
types?
a = 10
a = “NIT Srinagar“
A=“NIT Srinagar”
print(a)

Output? Error or 10 or NIT Srinagar


Can we use the same name for different
types?
• If we use the same name, the variable starts referring to a new value
and type.
a = 10
a = “NIT Srinagar“
A=“NIT Srinagar”
print(a)
Performing different operations on Variables
a=10
b=20
Print(a+b) # this will add the two integers and give output 30
Performing different operations on Variables
a=10
b=20.5
Print(a+b) # What will be the output?

30 or 30.5
Performing different operations on Variables
a=10
b=20.5
Print(a+b)

Output will be 30.5


This concept is called as Type Promotion.
When you perform the addition a + b, the integer a is implicitly converted to a
floating-point number before the addition takes place.
Performing different operations on Variables
a=10
c=“NIT Srinagar”
d=“CSE”
print(c+d) // This will do the concatenation of String
Print(a+c) // this will give us error. (TypeError: unsupported
operand type(s) for +: 'int' and 'str’)
Output?
a=10
b=True
c=False
print(a+b)
print(a+c)
print(b+c)
Explanation of Previous Program
In Python,
the True boolean value is internally represented as an integer with the value 1.
False boolean value is internally represented as an integer with the value 0.

This allows you to perform arithmetic operations with boolean values as if they were
integers

When you perform the operation 10 + True, Python treats True as 1 and performs
the addition as follows: 10+1
Similarly, print(True+False) will perform addition as 1+0 and gives O/P 1
print(True==1) // Outputs True
Output?
x=10
y=x
print(x)
print(y)

x=20
print(y)
Python is an Interpreted Language
Since Python is an interpreted language, it executes the code line by line.
Suppose we have written 1000 lines of code and line 100 has some
issue/error.
What will happen?
Will it execute till 99 lines and while executing the 100th line, it will stop the
execution?
Or
It will not execute at all?
Output?
print("Line 1")
print("Line 2")
if True # Error in this line as : is not inserted here
print("Line 3")
print("Line 4")
Output?
print("Line 1")
print("Line 2")
error
print("Line 3")
print("Line 4")
The life of your Python code
When you run a .py file, Python doesn’t just start reading line 1 and executing right away.
The process looks like this:
Lexical Analysis (Tokenizing)
• Python breaks the source code (text) into tokens (keywords, identifiers, numbers, operators, etc.).
• Example:
if x > 5:
print("Hi")
Becomes
IF NAME(x) OP(>) NUMBER(5) COLON NEWLINE INDENT NAME(print) ...
Parsing:
• Python takes these tokens and checks if they fit the Python grammar rules.
• It builds an internal parse tree (or AST – Abstract Syntax Tree) that represents the structure of your code.
• If something breaks the rules (e.g., missing colon, wrong indentation), Python raises a SyntaxError here — before executing
anything.

Bytecode Creation
• If parsing succeeds, Python compiles the AST into bytecode (low-level instructions for the Python Virtual Machine).
• Execution
• The bytecode is executed line by line in the Python interpreter.
PYTHON Programming (CST310)
Lecture 3: Taking input from Users

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
August 14, 2025
How to get Input from Users in Python
• A Program often have a need to interact with users, either to get data
or to provide some sort of result.
• In Python, Using the input() function, we take input from a user, and
using the print() function, we display output on the screen.

• Using the input() function, users can give any information to the
application in the string format.
In Python 3, we have the input() built-in functions to accept the input
from a user.
input(prompt):
The prompt argument is optional.
The prompt argument is used to display a message to the user.
For example,
input(“Please enter your name”)
When the input() function executes, the program waits until a user
enters some value.
Next, the user enters some value on the screen using a keyboard.

Finally, the input() function reads a value from the screen, converts it
into a string, and returns it to the calling program.
>>> input()

or

>>>print(“please enter your name”)


>>>input()

is equivalent to

>>>input(“please enter your name”)


Program to Accept Inputs From a User
Let see how to accept employee information from a user.
1. First, ask employee name, salary, and company name from the user
2. Next, we will assign the input provided by the user to the variables
3. Finally, we will use the print() function to display those variables on
the screen.
Program to Accept Inputs From a User
Let see how to accept employee information from a user.
1. First, ask employee name, salary, and company name from the user
2. Next, we will assign the input provided by the user to the variables
3. Finally, we will use the print() function to display those variables on
the screen.
Python Program to take two values as input
and printing their Sum
Python Program to take two values as input
and printing their Sum
a=input("Enter no1")
b=input("Enter no 2")
sum=a+b
print(sum) // it will print the concat of a and b
print(type(a)) // type of a will be string
print(type(b)) // type of b will be string
As you know whatever you enter as input, the input() function always
converts it into a string.
Type Casting:
Take an Integer Number as input from User
• We need to convert an input string value into an integer using an int()
function.
num1=int(input(“enter the number”)
PYTHON Programming (CST310)
Lecture 4: Operators in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
August 21, 2025
Operators

• Operators are used to perform operations on variables and values.


Operators in Python
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Bitwise operators
Operators in Python
Arithmetic operators
Arithmetic operators are used with numeric values to perform common mathematical
operations:
+ Addition x+y
- Subtraction x-y
* Multiplication x*y
/ Division x/y
% Modulus (Remainder) x%y
** Exponent x**y
Operators in Python
Python Assignment operators
Assignment operators are used to assign values to variables:
= x=10
+= x+=5 x=x+5
-= x-=5 x=x-5
*= x*=5 x=x*5
/= x/=5 x=x/5
**= x**=5 x=x**5
Operators in Python
Python Comparison operators
Comparison operators are used to compare two values.
Output of these expressions is either True or False

== Equal to x==10
!= Not Equal to x!=5
> Greater than x>5
< Less than x<5
>= Greater or Equal to x>=5
<= Less than or equal to x<=5
Operators in Python
Python Logical operators
Logical operators are used to combine conditional statements:

and age>18 and age<60 //returns True if both conditions are true.
or age>18 or age<60
not not(age>18 and age<60)
Boolean Expressions in Python
A boolean expression is an expression that is either true or false.

>>> 5 == 5
In the above example, == is used which compares the value of given
two operands and returns true if they are equal, else False.
Operators in Python
In Python, True and False are equivalent to 1 and 0, respectively.

>>> 0 == False #Bool is a subclass of int in Python. Python converts


implicitly int(False)
>>> 1 == True
>>> 2 == True

Use the int() method on a boolean to get its int values.


>>>X= True
>>>Y=False
>>>print(int(X))
>>>print(int(Y))
Numbers as Boolean Values

>>> bool(0) // it will cast the integer to its equivalent Boolean value: False

>>> bool(1) // it will cast the integer to its equivalent Boolean value: True
>>> bool(2) // it will cast the integer to its Boolean value: True
>>>bool(-2) // it will cast the integer to its Boolean value: True

While casting to Boolean, All other values, including non-zero numbers, non-empty
strings (like "hello"), non-empty lists, and other non-empty collections, are considered
True.
Operators in Python
>>> True + (False / True) // Output?
Operators in Python
>>> True + (False / True) // Output?

Since, arithmetic operator is used, so each bool value is converted implicitly to their Integer
equivalent before performing the operation.

In the above example, True + (False / True) can be expressed as 1 + (0/1) whose output is 1.0

5/2? #float because / always give float


5//2? #int because // gives integer division (floored).
Operators in Python
>>> 17 and True // Output?

the operands of the logical operators should be boolean expressions, but Python is not very strict. Any
nonzero number is interpreted as “true.”

>>> -1 and True # Output?


>>> 0 or True # Output?
>>> 0 and True # Output ?
Operators in Python
Case 1: and operator and First Expression is Truthy Value (True, 1)

Then, output will be the second expression as it is.

Case 2: and operator and First Expression is Falsely Value (False, 0)

Then output will be the first expression as it is

Case 3: or operator and First Expression is Truthy Value

Then output will be the first expression as it is

Case 4: or operator and First Expression is False

Then output will be the second expression as it is


Operators in Python
>>> 17 and True
>>> True and 17
>>> -1 and True
>>> True and -1
>>> 0 and True
>>> 1 or False
>>> False or 1
>>> 1 or False or 18
>>> 1 and False and 18
>>> False or 0 or "“
>>> ‘' or False or 0
>>> True and 10 and "Hello"
>>>False and 20 and "World“
>>>True and False and 1
>>>0 or 100 or "AI“
>>>False and True or 10 / 2 and 0 or "Python" * 3
Operators in Python
The not Boolean Operator:
• The only Boolean operator with one argument is not.
• The not operator always returns a boolean (True or False), not the original object.
• It takes one argument and returns the opposite result:
False for True and True for False.

>>> not True // outputs False


>>> not False // outputs True
>>> not 0 // Outputs True
>>> not 1 // outputs False
>>> not 2 // outputs False
What will be the Output?
>>> 1 == 1
>>> 1 == 2
>>> 1 == 1.2
>>> 1 == 1.0

>>> 1 == "1"
What will be the Output?
>>> 1 == 1 Both operands are int and Values are the same (1 equals 1). So True
>>> 1 == 2 Left side: 1 (an int), Right side: 1.2 (a float). When comparing int and float,
Python converts the int to a float (so 1 → 1.0).
>>> 1 == 1.2
>>> 1 == 1.0

>>> 1 == "1“ False


Python does not auto-convert between numbers and strings.
1 is an integer, "1" is a string → types are incompatible.
Always False (unless you explicitly convert: int("1") == 1 → True).
Python Bitwise operators
are used to perform bit-level operations on integers. They
Python Bitwise operators
manipulate individual bits of data and can be very efficient for certain types of
calculations
Bitwise AND (&): Sets each bit to 1 if both bits are 1.
a=5 # 0b0101
b=3 # 0b0011
result = a & b # 0b0001 -> 1

Bitwise OR (|): Sets each bit to 1 if at least one of the bits is 1.


a=5 # 0b0101
b=3 # 0b0011
result = a | b # 0b0111 -> 7

Bitwise NOT (~): Inverts all the bits (flips 0 to 1 and 1 to 0).
~5 returns output -6 (Formula: -(N+1)

Bitwise XOR (^): Sets each bit to 1 if only one of the bits is 1.
PYTHON Programming (CST310)
Lecture 5:
Short-Circuit Expression Evaluation
Indentation Concept in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
August 25, 2025
Short-circuit evaluation of logical expressions

When Python is processing a logical expression such as


x >= 2 and (x/y) > 2
it evaluates the expression from left to right.
Because of the definition of and, if x is less than 2, the expression x >= 2 is
False and so the whole expression is False regardless of whether (x/y) > 2
evaluates to True or False

Python detects that there is nothing to be gained by evaluating the rest of a


logical expression, it stops its evaluation and does not do the computations
in the rest of the logical expression.
It is called short-circuiting the evaluation.
Short-circuit evaluation of logical expressions
>>> x=6
>>>y=2
>>> x >=2 and (x/y) > 2
>>> ??

>>> x=1
>>>y=0
>>> x >=2 and (x/y) > 2
>>> ??

>>> x=6
>>>y=0
>>> x >=2 and (x/y) > 2
>>>??

>>> x=6
>>>y=0
>>> x >=2 or (x/y) > 2
>>>??
Guarding Pattern
The short-circuit behavior leads to a clever technique called the guardian pattern.
We can construct the logical expression to strategically place a guard evaluation just before the evaluation that might cause an error.

>>> x = 1
>>> y = 0
>>> x >= 2 and y != 0 and (x/y) > 2
False

>>> x = 6
>>> y = input()
>>> x >= 2 and (x/y) > 2 #This expression can lead to error when user inputs value 0 for y
>>> x >= 2 and y != 0 and (x/y) > 2
False

>>> x >= 2 and (x/y) > 2 and y != 0


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero

In the second expression, we say that y != 0 acts as a guard to insure that we only execute (x/y) if y is non-zero.
Concept of Indentation
Curly braces { } to show the start and end of a block of codes is not used in
Python
if(condition)
{ #start of block
Statement 1;
Statement 2:
} # end of block
Statement 3;

Instead, the concept of Indentation is used.


Concept of Indentation
if(condition)
Statement 1;
Statement 2:
Statement 3;

For showing the start and end of a Block, the concept of Indentation is used in python.
Indentation in Python Programming is simply the spaces at the beginning of a code
line.
In Indentation for showing the block, some equal whitespace (usually tab) is placed
before the statements which are part of the block.

Python treats the statements with the same indentation level (statements with an
equal number of whitespaces before them) as a single code block
Concept of Indentation
if(condition)
Statement 1;
Statement 2:
Statement 3;
Statement 4;
If(condition2)
Statement5
Statement6
Statement7
Important Points regarding Indentation
• All the statements which are on the same level of Indentation(Same no of
whitespaces before them) belong to a single block.

if 18>10:
print(“hello world”)
print(“18 is greater than 10”) # this will lead to indentation error
print(“bye world”)
PYTHON Programming (CST310)
Lecture 6:
Flow Control Statements in Python
Conditional Statements (if, if-else, elif)

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
August 25, 2025
Flow Control Statements in Python
The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements.
Conditional statements in PYTHON
• In Python, condition statements act depending on whether a given
condition is true or false.
• You can execute different blocks of codes depending on the outcome
of a condition.
• Condition statements always evaluate to either True or False.
There are three types of conditional statements.
[Link] statement
[Link]-else
[Link]-elif-else
If statement in Python
• In control statements, The if statement is the simplest form.
• It takes a condition and evaluates to either True or False.
• Only one condition is checked for True or False.
• If Condition comes to true, then only the block of code is executed.
• If the condition is False, then the block of code is skipped, and The
controller moves to the next line
Syntax of the if statement:
if(condition): if condition:
statement 1 statement 1
statement 2 or statement 2
statement n statement 3
Example of IF Statements in Python
number=11
if(number>10):
print(“value in variable number is greater than 10”)
If – else statement
• The if-else statement checks the condition and executes the if block
of code when the condition is True, and if the condition is False, it will
execute the else block of code.
Syntax of the if-else statement:
If(condition):
statement 1
statement 2
else:
statement 3
Example of IF-Else Statements in Python
password=input(“enter the password”)
if(password==‘NIT’):
print(“password is correct”)
print(“welcome”)
else:
print(“Incorrect Password”)
Chain multiple if statement in Python
• In Python, the if-elif-else condition statement has an elif blocks to chain multiple conditions one
after another.
• This is useful when you need to check multiple conditions.
Syntax of the if-elif-else statement:
if condition-1:
statement 1
elif condition-2:
stetement 2
elif condition-3:
stetement 3
...
else:
statement
Example of IF-Else Statements in Python
choice=input(“Enter your Choice”)
if(choice == 1):
print("Admin")
elif(choice == 2):
print("Editor")
elif(choice == 3):
print("Guest")
else:
print("Wrong entry")
Is it mandatory to have else block after the elif block?

If condition:
statement1
Elif condition2:
statement2
Practice Program:
WAP which test the following conditions:
• If the number is positive(>0), we print an appropriate message
• if number is 0, prints number is 0
• if number is less than 0, prints the message (no is less )
• else prints wrong input
PYTHON Programming (CST310)
Lecture 07:
Iterative Statements in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
August 26, 2025
Flow Control Statements in Python
The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements.
Iterative Statements in PYTHON
• In Python, the iterative statements are also known as looping
statements or repetitive statements.
• The iterative statements are used to execute a part of the program
repeatedly as long as a given condition is True.
Python provides the following iterative statements.
1. while statement
2. for statement
while statement in Python
• In Python, the while statement is used to execute a set of statements repeatedly.
• In Python, the while statement is also known as entry control loop statement
because in the case of the while statement, first, the given condition is verified then
the execution of statements is determined based on the condition result.
• The general syntax of while statement in Python is as follows.
while condition:
Statement_1
Statement_2
Statement_3
...
Python don’t use curly braces for specifying the block of while statements.
Indentation is used in Python for the above purpose.
The indentation is a series of white-spaces. Here, the number of white-spaces may
variable, but all statements must use the identical number of white-spaces.
Example Program of While Statement
n=int(input("Enter no of times you want to print hello"))
while(n>0):
print("Hello")
print(n)
n=n-1
while statement with 'else' clause in Python
• In Python, the else clause can be used with a while
statement.
• The else block gets executed whenever the condition of
the while statement is evaluated to false.
• But, if the while loop is terminated with break statement
then else doesn't execute.
Example Program of while statement with
'else' clause in Python
n=int(input("Enter no of times you want to print hello"))
while(n>0):
print("Hello")
print(n)
n=n-1
else:
print("hello has been printed 5 number of times")
print("job is done")
If condition within While Block
n=int(input("Enter no of times you want to print hello"))
while(n>0):
if(n==5):
print("n is equal to 5.. Exiting")
break
print("Hello")
print(n)
n=n-1
else:
print("hello has been printed 5 number of times")
print("job is done")
if the while loop is terminated with break statement then else
doesn't execute.
for statement in Python
• In Python, the for statement is used to iterate through a sequence like a
list, a tuple, a set, a dictionary, or a string.
• The for statement is used to repeat the execution of a set of statements for
every element of a sequence.
The general syntax of for statement in Python is as follows.
for <variable> in <sequence>:
Statement_1
Statement_2
Statement_3
...
Using For Loop on a String
name=“nit srinagar”
for i in name:
print(i)
Python code to illustrate for statement with
Range function
# Python code to illustrate for statement with Range function
for value in range(1, 6):
print(value)
print('Job is done!’)

Output:
1
2
3
4
5
Python code to illustrate for statement with
Range function
Range(start_value,end_value, step)

Range(1,5) 1234
Range(5) 01234
Range(1,10,2) 13579
range(5,1,-1) 5432
Printing Without Newline
# Python code to illustrate for statement with Range function
for value in range(1, 6):
print(value, end=“”)
print('Job is done!’)

Output:
12345
for statement with 'else' clause in Python
• In Python, the else clause can be used with a for a statement.
• The else block gets executed whenever the for statement is does not
terminated with a break statement.
• But, if the for loop is terminated with break statement then else block
doesn't execute.
PYTHON Programming (CST310)
Lecture 08
Transfer Control Statements (Break, Continue, Pass)

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
August 26, 2025
Control Flow Statements in Python
The flow control statements are divided into three categories
1. Conditional statements
2. Iterative statements.
3. Transfer statements.
Transfer Controls Statements in PYTHON
• In Python, transfer statements are used to change execution from its
normal sequence.
1. Break
2. Continue
3. Pass
Break Statement:
• The break statement is used to terminate the loop containing it, the
control of the program will come out of that loop.
• Break brings the control out of the loop.

for item in “nit srinagar”:


if(item==‘i’):
break
print(item)
Continue Statement:
• When the program encounters a continue statement, it will skip the
statements which are present after the continue statement inside the
loop and proceed with the next iterations..
• Continue brings the control out of the current iteration and moves to
the next iteration.

for item in “nit srinagar”:


if(item==‘i’):
continue
print(item)
Pass Statement:
• Pass is the no-op statement.
• Pass is used to create an empty class or loop.
• It does nothing and is used when a statement is syntactically required but
you don't want to execute any code at that point.
• It's often used as a placeholder for future code that you haven't written yet.
• Pass can be used to print the last element of a string
• Pass can be used in loops, conditional statements, functions, classes/

if some_condition:
pass # Placeholder for future code
else:
# Some code here
Pass Statement:
• Pass can be used to print the last element of a string

for item in ‘NIT Srinagar’:


pass
print(item)
Continue vs Pass
• Pass is used as a placeholder or a no-op statement.
Continue is used within loops to skip the rest of the current iteration and
move on to the next iteration.
• Pass It doesn't have any effect on the program's logic; it simply satisfies
syntax requirements.
Continue It affects the flow of the loop by immediately moving to the next
iteration.
• Pass is typically used when you need a syntactically correct statement but
don't want to execute any code at that point.
Continue is Used when you want to skip specific steps of a loop's iteration
based on a certain condition.
Continue vs Pass
if item in ‘NIT Srinagar’:
pass
print(item)

if item in ‘NIT Srinagar’:


continue
print(item)
Continue vs Pass
We cannot use 'pass' in place of 'continue', because in the case of 'pass',
statements following the 'pass' will still be executed, which is not the case
with 'continue'.

for item in range(1,10): for item in range(1,10):


if item==5: if item==5:
continue pass
print(item) print(item)
Output?

for item in range(1,10):


print("outer loop",item)
for item1 in range(1,10):
if item1==5:
break
print("inner loop",item1)

In above example, will Break take the control out of the inner loop only or all
the loops?
What if we want to Exit out of both inner as well as
Outer loop when Break is encountered?
for item in range(1,10):
print("outer loop",item)
for item1 in range(1,10):
if item1==5:
break
print("inner loop",item1)

There is no Labelled break in Python


What if we want to Exit out of both inner as well as
Outer loop when Break is encountered?
for item in range(1,10):
print("outer loop",item)
for item1 in range(1,10):
if item1==5:
break_outer=True
break
print("inner loop",item1)
if break_outer:
break
Practice Programs
1. Write a program to calculate the electricity bill (accept number of unit
from user) according to the following criteria :
Unit Price
First 100 units no charge
Next 100 units Rs 5 per unit
After 200 units Rs 10 per unit

(For example if input unit is 350 than total bill amount is Rs2000)
Practice Programs

1. Python Program to count the number of characters in a given string.


2. Python Program to count the number of vowels in a given string.
Practice Programs
1. Given two numbers, write a Python code to find the Maximum of these two numbers.
Input: a = 2, b = 4
Output: 4
2. Write a program to find factorial of a number.
3. Write a program to print the ASCI value of all the characters in a string.
Hint: ord() is used to find the ASCI value of a character
4. Simple Calculator
Select operation.
[Link]
[Link]
[Link]
[Link]
5. Exit
Enter choice(1/2/3/4): 3
Enter first number: 15
Enter second number: 14
15.0 * 14.0 = 210.0
PYTHON Programming (CST310)
Lecture 09: Functions in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
August 28, 2025
Functions in Python
• In any programming language, functions facilitate code reusability.
• A function can be defined as the organized block of reusable code, which
can be called whenever required.
• A function can be called multiple times to provide reusability.
• Input() and Print() are also the functions (in-built) that you have used so
far.
• The Function helps to programmer to break the program into the smaller
part.
• It organizes the code very effectively and avoids the repetition of the code.
Types Of Functions

There are mainly two types of functions.


• Built-in functions - The built-in functions are those functions that are
pre-defined in Python.
• User-defined functions - The user-defined functions are those
defined by the user to perform the specific task.
Functions in Python
• Python provide us various inbuilt functions like range(), input(),
print(), ord(), int(),str(), all(), any(), etc.
• The user can also create its functions, which can be called user-
defined functions.
Advantage of Functions in Python
There are the following advantages of Python functions.
• Using functions, we can avoid rewriting the same logic/code again
and again in a program.
• We can call Python functions multiple times in a program and
anywhere in a program.
• We can track a large Python program easily when it is divided into
multiple functions.
• Reusability is the main achievement of Python functions.
Creating your own Function in Python
Every function consist of three components:
1. Function Declaration
2. Function Definition
3. Function Calling

def function_name(arguments):
# Do something on arguments
# What the function does goes here
return result # the result of operations on the arguments
Function Creation Syntax in Python:
def function_name(arguments):
# Do something on arguments
# What the function does goes here
return result # the result of operations on the arguments
• The def keyword, along with the function name is used to define the
function.
• The identifier rule must follow while giving the function name.
• A function accepts the parameter (argument), and they can be optional.
• The function block is started with the colon (:), and block statements must
be at the same indentation.
• The return statement is used to return the value. A function can have only
one return
• Note that the arguments and the return statement are optional.
Creating our First Simple Function in Python
This function that we are going to create, whenever called, will print
the string “hello Class”.

def my_first_func(): #function declaration


print(“hello class”) #function definition

my_first_func() # function calling


Function without arguments to add two
numbers
def addition_of_two_numbers(): #Declaration
n1=int(input("Enter no 1"))
n2=int(input("Enter no 2")) #Definition
sum=n1+n2
print("sum of two numbers is", sum)

addition_of_two_numbers() #function calling


Function with arguments to add two numbers
def addition_of_two_numbers(n1,n2): #Declaration
sum=n1+n2
print("sum of two numbers is", sum) #Definition

n1=int(input("Enter no 1"))
n2=int(input("Enter no 2"))
addition_of_two_numbers(n1,n2) #function calling
Function with return
The return statement is used to return the value. A function can have only one
return.

# Defining function
def sum():
a = 10
b = 20
c = a+b
return c

# calling sum() function in print statement


print("The sum is:",sum())
Function without return
# Defining function
def sum():
a = 10
b = 20
c = a+b

# calling sum() function in print statement


print("The sum is:",sum())

Output: The sum is None


Function with return value

def display(): #function declaration


print(“hello class”)
return “bye”
print(“bye class”)
return “bye bye”

display() # function calling


Required Arguments
• The arguments which are required to be passed at the time of function calling should be the
exact match of their positions in the function call and function definition.
• If either of the arguments is not provided in the function call, the Python interpreter will
show the error.

def print_age_name( age, name):


print(“Name of the person is ”,name)
print(“age is ”,str(age))

print_age_name()
print_age_name(20)
print_age_name(“Joginder")
print_age_name(“Joginder“,23)
print_age_name(name=“Joginder",age=23)
Default Arguments
• Python allows us to initialize the arguments at the function definition.
• If the value of any of the arguments is not provided at the time of function call,
then that argument can be initialized with the value given in the definition even
if the argument is not specified at the function call.

def print_age_name(age, name="demo"):


print("Name of the person is ",name)
print("age is ",str(age))
print_age_name(23)#the variable name is not passed into the function however t
he default value of name is considered in the function
print_age_name(23,“Joginder")
#the value of name is overwritten here, Joginder will be printed as name
Note: Default argument should not be followed by non-default argument
Output?
def print_message():
message = "hello !! I am going to print a message."
print(message)

print_message()
print(message)
Output?
def calculate(a,b,c):
sum=a+b+c
print("The sum is",sum)
sum=0
calculate(10,20,30)
print("Value of sum is:",sum)

Output: ?
Can we Do this?
def input(msg):
print(msg)

a=input("hello")
Can we Do this?
def print():
print("hello”)

print()
Can we Do this?
def print():
#global a #global makes the variable ‘a’ scope global
a=‘hello’

print()
print(a)
How to call built-in Print()
def print():
#global a
a=‘hello’

print() #overridden print will be called

import builtins
[Link](“hello”) #this is how we can call the built-in print() after it is overridden
Scope and Lifetime of Variables
• The scopes of the variables depend upon the location where the variable is
being declared.
• The variable declared in one part of the program may not be accessible to
the other parts.
• In python, the variables can be categorized as following in terms of the
their scope and lifetime:
1. Global variables
2. Local variables
The variable defined outside any function is known to have a global scope,
whereas the variable defined inside a function is known to have a local
scope.
Local Variables
def print_message():
message = "hello !! I am going to print a message."
print(message)
print_message()
print(message)

This will cause an error since a local variable cannot be accessible outside
the function.
Global Variable
def calculate(a,b,c):
sum=a+b+c
print("The sum is",sum)
sum=0
calculate(10,20,30)
print("Value of sum outside the function:",sum)

Output: ?
The sum is 60
Value of sum outside the function: 0
Global and Local Variables
Hashim="Hashim Account 1"

def NITSrinagar():
Ayushman="Ayushman Account"
#global Hashim
#Hashim="Hashim from NIT Srinagar"
print("Money from ",Ayushman,"debited")
print("Money from",Hashim,"debited")

NITSrinagar()
print("Money from",Ayushman,"debited")
print("Money from",Hashim,"debited")
Scope and Lifetime of Variables
• Variables Defined Inside Loops or Conditional Statements are not
considered local variables in the same sense as local variables in
functions. They have a broader scope and are accessible outside the
loop or conditional block. They can be accessed after the loop or
conditional statement has completed.
for i in range(3):
loop_variable = i # Variable within loop
print(loop_variable)
What will be the output?
def sum(a,b):
c=10
sum=a+b+c
print("sum of three nos is ",str(sum))

def sum(a,b):
sum=a+b
print("sum of two no.s is ",str(sum))

sum(2,3)
What will be the output?
def sum(name,age):
print(f"name is {name} and age is {age}")

def sum(age,weight):

print(f"age is {age} and weight is {weight}")

sum(2,30)
sum(“Sneha",21)
What will be the output?
def sum(a,b,c):
sum=a+b+c
print(“sum of three nos is ”,str(sum))

def sum(a,b)
sum=a+b
print(“sum of two no.s is ”,str(sum))

sum(2,3)
sum(2,3,5)
No Function Overloading in Python
Function overloading refers to the ability to define multiple functions with the
same name but different parameter lists.
The correct function to call is determined at compile-time based on the number
and types of arguments provided during the function call.

Python does not directly support Function Overloading like it is in languages


such as Java or C++, as python does not provide datatypes for function
parameters (Dynamically typed language).
Python doesn't differentiate between them based on the number of arguments
The previous function having the same name(but different parameters) gets
overridden with the new function having the same name.
The last defined function with a particular name will override any previous
definitions, regardless of the number of arguments it takes.
What if want to Implement Function Overloading related Concept in
Python?
What if want to Implement Function Overloading
related
def sum(a=None, b=None, c=None):
Concept
if (a==None and b==None and c==None):
print("sum with no arguments called")
elif (b==None and c==None):
print("sum with 1 argument called")
print("value of 1 argument passed is",a)
elif (c==None):
print("sum with 2 arguments called")
print("Sum of 2 numbers is",a+b)
else:
print("sum with 3 arguments called")
print("sum of 3 numbers is ",a+b+c)
sum()
sum(1)
sum(1,2)
sum(1,2,3)
What will be the output?
def foo(x):
x=x+1
x = 10
foo(x)
print(x)
What modifications can be done to make changes
to global variable x inside the function foo
def foo(x):
x=x+1
x = 10
foo(x)
print(x)
What will be the O/P
x=10
def foo():
x=‘nit’
print(“local variable”,x)
foo()
print(“global variable”,x)
If we have a global variable and local variable with
same name, and we want to access them both
inside the function.
x=10
def foo():
x=‘nit’
print(“local variable”,x) #prints nit
print(“global variable”,x) #prints nit
foo()
If we have a global variable and local variable with
same name, and we want to access them both
inside the function.
x=10
def foo():
x=‘nit’
print(“local variable”,x) #prints nit
print(“global variable”,globals()[“x”]) #prints nit

foo()
If we have a global variable and local variable with
same name, and we want to MODIFY the Global
Variable inside the function.
x=10
def foo():
x=‘nit’
print(“local variable”,x)
globals()[“x”]=‘Srinagar’
print(“global variable”,globals()[“x”])
foo()
What will be the O/P
x=10
def foo():
x=‘nit’
global x
x=20
print(“local variable”,x)
foo()
print(“global variable”,x)
What will be the O/P
def foo(a, b=0):
return a + b
x = foo(2, 3)

def foo(a):
return a * 2
y = foo(5)
print(x, y)
PYTHON Programming (CST310)
Lecture 10: Standard Data-types supported by Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 02, 2025
Data Types Supported by Python

• Variables can hold some value, and every value has a data-type.
• Python is dynamically typed language (We don’t need to define the
data-type for the variable, Interpreter implicitly gives the datatype to
the variable based on the value).
Age=18
Python interpreter will automatically interpret variables age as an
integer type.
Standard built-in Data-types in Python
Following are the standard datatypes in Python language:
1. Numeric
a. int:
b. Float:
c. Complex:
2. Boolean
a) bool (values are true or false)
3. Sequence Type:
a. String (Immutable): Collection/Sequence of Characters
b. List (Mutable): Collection of elements (same or different)
c. Tuple (Immutable) (Collection of elements
4. Set: (unordered collection of unique elements, Cannot be accessed via indexes)
5. Dictionary (collection of elements stored in key-value pairs)
Standard built-in Data-types in Python
Following are the standard datatypes in Python language:
1. Numeric
a. int: (Integer) for storing the integer values.
It contains positive or negative whole numbers (without fraction or decimal).
Standard built-in Data-types in Python
int: (Integer) for storing the integer values.
a. Arithmetic Operations: You can perform various arithmetic operations on integers,
including addition, subtraction, multiplication, division, floor division (//), and
modulo (%).

b. Unlimited Precision: Python's int type supports unlimited precision arithmetic. This
means that integer values can be as large as the available memory allows.
In Python there is no limit to how long an integer value can be.
Standard built-in Data-types in Python
In Python there is no limit to how long an integer value can be.
Standard built-in Data-types in Python
int: (Integer) for storing the integer values.
• Immutable: Integers are immutable, which means their values cannot be changed
after they are created. When you perform operations on integers, new integer objects
are created.
• Binary, Octal, and Hexadecimal Literals: Integers can be written in various number
bases, such as binary (base 2), octal (base 8), and hexadecimal (base 16), using
prefixes like 0b, 0o, and 0x, respectively.
Standard built-in Data-types in Python
• Type Conversion: Integers can be converted to other data types using built-in
functions like str(), float(), and bool().
• Memory Efficiency: In Python 3, integers are dynamically allocated and managed by
the interpreter, which allows for efficient memory usage.
Finding Size of int object in python: [Link]() function allows you to find the
memory size of an object in bytes.

• Math Module: Python's built-in math module provides various mathematical


functions that work with integers, such as finding absolute value, factorial, and more.
Standard built-in Data-types in Python
Numeric
b. float:
For storing the decimal numeric values
The float data type is used to represent floating-point numbers, which are numbers
with decimal points or fractional parts
Standard built-in Data-types in Python
float:
• Floating-Point Arithmetic:
• Type Conversion: Floats can be converted to other data types using built-in functions like int()
and str().
• Math Module: Python's built-in math module provides various mathematical functions that
work with floating-point numbers, such as trigonometric functions, logarithms.
• Finite Precision: Floating-point numbers in Python have Finite precision due to the way they
are stored in memory. Floating-point numbers are stored in computers using their binary
representation, specifically the IEEE 754 standard for floating-point arithmetic.
• This means that some calculations might result in small rounding errors.
a=1.1
b=2.2
c=a+b #Output? 3.3?
Floating-point numbers in computers are stored using a finite number of binary digits, which
can lead to small rounding errors.
When you assign a floating-point number like 1.1 to a variable in Python, the value is stored in
its binary representation using the chosen format (typically double precision). The binary
representation is used for calculations and storage internally, and when you access the value,
it's converted back to its decimal representation for display.
Standard built-in Data-types in Python

b. Complex:
For storing the complex numbers
Complex number is represented by complex class.
It is specified as (real part) + (imaginary part)j.
For example: 2+3j
Standard built-in Data-types in Python
Following are the standard datatypes in Python language:
2. Boolean
Boolean datatypes take one of the two values: True or False.
Standard built-in Data-types in Python
3. Sequence data-types
In Python, sequence is the ordered collection of values of similar or different
data types.
Sequences allows to store multiple values in an organized and efficient
fashion.
a. String:
A string is a collection of one or more characters put in a single quote, double-quote or
triple quote.
In python, there is no character data type, a character is a string of length one. It is
represented by str class.
Standard built-in Data-types in Python
How to store the following strings in a variable

My name is ‘Joginder' and I love Programming.

My name is ‘Asma' and I love “Programming”.

My name is ‘Alok' and I love ''' "Programming"


Standard built-in Data-types in Python
Accessing the elements of a String:

city=“NIT Srinagar”

print(city[0])
print(city[30])
Standard built-in Data-types in Python
3. Sequence data-types
b. List:
Lists are just like the arrays, declared in other languages which is a ordered collection of
data.
It is very flexible as the items in a list do not need to be of the same type.
Standard built-in Data-types in Python
4. SET
Set is also the collection of values but has no duplicate elements

S= { 1, 2, 3}
S2={ 1, 2.3, ‘cse’ }

S3= { 1, 1, 2 }
print(S3) //What will be the output
PYTHON Programming (CST310)
Lecture 11: Strings in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 04, 2025
Strings in Python
• String is a sequence data type in python.
• It is a organized collection of elements i.e. ‘characters’
• Strings in Python can be created by enclosing characters in quotes
(Double or Single or Triple).
• Python treats single quotes the same as double quotes.
• Creating strings is as simple as assigning a value to a variable.
name=“nit Srinagar”
city=‘Srinagar’
Accessing Values in Strings
• Python does not support a character data type
• In Python, strings are treated as the sequence of characters.
• Python doesn't support the character data-type; instead, a single character written as
'p' is treated as the string of length 1.
• To access substrings, use the square brackets for slicing along with the index or
indices to obtain your substring.
• Like other languages, the indexing of the Python strings starts from 0.
• For example − Accessing Individual Characters in Strings

msg1 = ‘NIT Srinagar’


print(msg1[0])
print(msg1[1])
print(msg1[2])
print(msg1[3])
print(msg1[16]) # This will give error. Because 16th index doesn’t exist
Accessing Individual Characters in Strings
msg1 = ‘NIT Srinagar’

for i in msg1:
print(i)

or
for i in range(0,len(msg1)):
print(msg1[i])
Accessing Substrings in Strings
• The slice operator or square brackets [] is used to access the individual characters
of the string.
• However, we can use the : (colon) operator in Python to access the substring from
the given string.
string[start:end:step]
where,
start: The starting index of the substring. The character at this index is
included in the substring. If start is not included, it is assumed to equal to 0.
end: The terminating index of the substring. The character at this index is not
included in the substring. If end is not included, or if the specified value
exceeds the string length, it is assumed to be equal to the length of the
string by default.
step: Every "step" character after the current character to be included. The
default value is 1. If step is not included, it is assumed to be equal to 1.
Accessing Substrings in Strings
string[start:end] Get all characters from start to end – 1
string[:end] Get all characters from the beginning of the string to end - 1

string[start:] Get all characters from start to the end of the string

string[start:end:step] Get all characters from start to end - 1, not including


every step character

Note:
The start or end index can be a negative number.
A negative index means that you start counting from the end of the string
instead of the beginning (from the right to left).
Accessing Substrings in Strings
msg2= "Python Programming“
msg2[1:5] #this will give substring starting from index 1 to (5-1)

msg2[:] #this will give the whole original string


msg2[0:] #this will give the whole original string
msg2[:len(msg2)] #this will give the whole original string
msg2[:4] # this will give substring starting from index 0 to (4-1)
msg2[:-1] #this will print complete string except the last character
msg2[:-2] #this will print complete string except the last two characters
msg2[: - len(msg2)] #this will an empty string
msg2[-1:] #this will print the last character
msg2[-2:] #this will print the last two characters
Problems:
n=“Jammu and Kashmir”
n[2:4]
n[:3]
n[:-3]
n[-2:]
Practice Problems
string = “NIT Srinagar 2023"

1. Print First 5 Characters

2. Get a substring 4 characters long, starting from the 3rd character of the string

3. Get the last character of the string

4. Get the last 5 characters of a string

5. Get a substring which contains all characters except the last 4 characters and the 1st character

6. Reverse of String

7. string[-1:-10:-1] ?
Practice Problems
string = “NIT Srinagar 2022"

1. #Print First 5 Characters


print(string[0:5])
2. Get a substring 4 characters long, starting from the 3rd character of the string
print(string[3:7])
3. Get the last character of the string
print(string[-1:]
4. Get the last 5 characters of a string
print(string[-5:])
5. Get a substring which contains all characters except the last 4 characters and the 1st
character
print(string[1:-4])
6. Reverse of String
string[len(string):0:-1]
Strings are immutable in Python.
• The string cannot be modified.
• The string object doesn't support item assignment i.e., A string can
only be replaced with new string since its content cannot be partially
replaced.
say if s=“NIT Srinagar”
i.e. s[0]="s“ is not allowed.
However, s=“Kashmir” will work.
But, here also modification was not done on the original string. Here,
now the s is pointing to a new object with value “Kashmir”
Deleting the String
• As we know that strings are immutable.
• We cannot delete or remove the characters from the string.
• But we can delete the entire string using the del keyword.

s=“NIT SRINAGAR”
del s will delete the string object “NIT Srinagar”
print(s) # will give error

We cannot delete individual characters of string. i.e. del s[0] will not work
String Operators
Operator Description
It is known as concatenation operator used to join the strings given either side of the
+
operator.
It is known as repetition operator. It concatenates the multiple copies of the same
*
string.
[] It is known as slice operator. It is used to access an element from a particular string.
It is known as range slice operator. It is used to access the substring from the
[:]
specified range.
It is known as membership operator. It returns if a particular sub-string is present in the
in
specified string.
It is also a membership operator and does the exact reverse of in. It returns true if a
not in
particular substring is not present in the specified string.
It is used to specify the raw string. Raw strings are used in the cases where we need to
r/R print the actual meaning of escape characters such as "C://python". To define any string
as a raw string, the character r or R is followed by the string.
String Methods
• A method is like a function, but it runs "on" an object.
Suppose s=“NiT Srinagar”
1. [Link](): returns the lowercase version of the string
2. [Link](): returns the uppercase version of the string
3. [Link](): method splits a string into a list by using whitespace as
separator. For example: [Link] will return a list with two strings
“NIT” and “Srinagar”. We can split the strings using some other
separator also.
[Link](‘a’)
String Methods
4. [Link](): Returns the number of times a specified value occurs
in a string
5. [Link](“nit”): searches for the given string “nit” (not a regular
expression) within s, and returns the first index where it begins or -1 if
not found
6. [Link]('old', 'new') -- returns a string where all occurrences of
'old' have been replaced by 'new'
S=“NIT Srinagar”

• WAP to count the total occurrence of a character/substring in a string.


• WAP to reverse a string using slicing operator
• WAP to reverse a string using loops
• WAP to reverse a string using Recursion
PYTHON Programming (CST310)
Lecture 12: String Data Type- Part 2

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 08, 2025
String comparison in Python

• The comparison operators work on strings.


• To see if two strings are equal, we will use Equal to (==) operator.
a=“demo”
b=“demo”
c=“Demo”
print(a==b) #produces True if string in a and b are equal
print(a==c) #produces False, if a and c are not equal.
id(a)
id(b)
id(c) #in the above example, id of a and b will be equal,
while, id of c will be different from a and b.
String comparison
• Other comparison operators for strings.
name1=‘Kundan’
name2=‘Kamran cse’
name1 < name2 # what will be the output? Error? Or True or False?

In comparison of Strings, the characters of both the strings are compared one by one.
When different characters are found, their Unicode value is compared.
The character with lower Unicode value is considered to be smaller.

• Python does not handle uppercase and lowercase letters the same way that people do.
• All the uppercase letters come before all the lowercase letters
a=“abhishek”
b=“Prince”
a>b
Method vs Functions
• Calling a method is similar to calling a function (it takes arguments and
returns a value) but the syntax is different.
• We call a method by appending the method name to the variable name
using the period as a delimiter
• For example:
[Link]() # method calling syntax
lower(s) #function calling syntax
Some useful Functions and Methods for
Strings
s=“NIT Srinagar”
1. type(s): returns the data type of variable s
2. dir(s): lists all the methods that can be applied on variable s of type
String.
3. help(str.function_name): gives the description of a method
4. [Link](‘NIT’): checks if the string starts with ‘NIT’ or not.
Split method in Python
Split method breaks the given string into Substrings using space
(default) as separator and put the substrings as elements in a list.

S=“NIT SRINAGAR is in Srinagar”


[Link]()

#[Link] will return the following list


[“NIT”, “SRINAGAR”, “is”, “in”, “Srinagar”]
find method in Python
Find method finds if a substring is in the given string or not.
If the string is present, it returns the starting index of that substring in the given
string.
If substring not found, then it returns -1

S=“Ayushman Yadav”
[Link](“Yadav”) # this will return the starting index of “Yadav”

S=“Singh1 Singh2”
[Link](“Singh”) # this will return the starting index of first occurrence of Singh
[Link](“Singh”, 7) # here we are searching the keyword from the 7th index.
index method in Python
Index method works same like the find method.
Difference is incase of substring not found, Index method generates an
Error(Value not found)
Check if a string contains only numbers
isnumeric() returns True if all characters are numeric.

“20030”.isnumeric()
'1.0'.isnumeric()
String Parsing
s=“Pinging [Link] [[Link]] with 32 bytes of data:”

s1=“Pinging [Link] [[Link]] with 32 bytes of data:”

Suppose, our requirement is to fetch the substring IP address from the


above String. How we can do it?

Hint: We will use the Slicing Concept


Possible Solution for Previous Problem
s=“Pinging [Link] [[Link]] with 32 bytes of data:”

Suppose, our requirement is to fetch the substring IP address from the


above String. How we can do it?

s[[Link]("[")+1:[Link]("]")]
or
s[[Link]("[")+1:[Link]("]")]
Problem 2:
s=“Pinging [Link] @[Link] w 32 bytes of data:”

s2=“Pinging [Link] @[Link] w 32 bytes of data:”

Suppose, our requirement is to fetch the IP address from the above String.
How we can do it?
Possible Solution to Previous Problem
s=“Pinging [Link] @[Link] with 32 bytes of data:”

Suppose, our requirement is to fetch the IP address from the above


String. How we can do it?

s[[Link]("@")+1:[Link]("w")-1]
or
s[[Link]("@")+1:[Link](" ",[Link]("@"))]
Practice Program
s= “Reply from [Link]: bytes=32 time=90ms TTL=48”

Fetch the ip address from the above given string.


Possible Solution
s= “Reply from [Link]: bytes=32 time=90ms TTL=48”

Split_in_list= [Link]() # split will split the above string into


substring with whitespace as separator
and save the strings in a list
for item in splitted_list:
if [Link](“.”)!=-1:
print(item)
Practice Problem
Take the following Python code that stores a string:
str = ’X-DSPAM-Confidence:0.8475’

Use find and string slicing to extract the portion of the string after the
colon character and then use the float function to convert the
extracted string into a floating point number.
Program to find the IP address of a Website
(using Ping in cmd)
import subprocess #spawn new subprocesses and let you run system
#commands directly from your python code
url=input("enter the website name")
output=subprocess.check_output(["ping",url],shell=True)

s=str(output)
a=[Link]()
for item in a:
if item[0].isnumeric():
print(item[:])
break
What Will be the Output?

animal = “Bear”
more_animal = animal

print(animal == more_animal) # == checks only the equality


print(animal is more_animal) # is operator checks the id(memory location)

new_animal = “Bear”
print(animal == new_animal) #=> True
print(animal is new_animal) #=> True
To check if each word in a string begins with a
capital letter?
The istitle() function checks if each word in a given string is capitalized.

print(“Shreya”.istitle()) # returns True


print(“kundan”.istitle()) #returns False
Print(“Hatim is”.istitle()) #returns False
print(“Joginder Cse”.istitle()) #returns True
PYTHON Programming (CST310)
Lecture 13: Files Handling in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 09, 2025
File Handling
• So far, whatever program we were writing and executing was
interacting with CPU and Main Memory (RAM).
• But, the data in RAM and CPU is temporarily stored and gets erased
once the power is turned off.
• So, now we will see how to interact with the Secondary memory and
store or write the programs results and data in the hard disk.
• Also, how to read the data from the secondary memory into the
program will be discussed,
File Handling in Python
• Python has the support for file handling and allows users to handle
files i.e., to read and write files, along with many other file handling
options, to operate on files.
• The concept of file handling can be seen in various other languages
also, but the implementation is either complicated or lengthy.
• In case of python, handling of files is very simple.
Opening a File Stored in Secondary Memory in Python
• When we want to read or write a file (say on your hard drive), we first must open the file.
• When you open a file, you are asking the operating system to find the file by name and
make sure the file exists.
• We use open () function in Python to open a file in read or write mode.
Syntax: open(filename, mode)
mode argument is optional. It tells the mode in which to open the file. Following
types of modes exist which tells how to open the file:
“ r “, for reading.
“ w “, for writing.
“ a “, for appending.
“ r+ “, for both reading and writing
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)

The mode argument is not mandatory. If not passed, then Python will assume it to be “ r ”
and “t” by default.
Opening a File Stored in Secondary Memory in Python
f = open(‘filename’) #the file should be in same folder where your python program is
or
f = open(‘complete_path_of_file_to_open’)

If the open is successful, the operating system returns us a file handle (file
object).

Using the file handle(object) we can perform further operations on that file
like reading, writing, etc.
The file handle is not the actual data contained in the file, but instead it is a
“handle” that we can use to read the data.

The above code will open the file in read mode.


Opening a File Stored in Secondary Memory in
Python
• If the file does not exist, open will fail with a traceback and you will not get a handle to access the contents of the file:
fhand = open('[Link]’)

Traceback (most recent call last):


File "<stdin>", line 1, in <module>
FileNotFoundError: [Errno 2] No such file or directory: '[Link]'
Reading files
• A text file can be thought of as a sequence of lines, much like a
Python string can be thought of as a sequence of characters.

f=open('[Link]’)
for line in f:
print(line)

We can read the data from the file line by line to prevent out of
memory errors when the file size is in gigabytes.
Reading files- Way 2
• If you know that the file you want to read is not too big, then you can
use this method.
• In this method, you will read all the contents at once as a single
string.
• If you need to extract a string that contains all characters in the file
then we can use [Link]().
f=open('[Link]’)
print([Link]())
Reading files- Way 3
[Link]() this will read individual lines from the file
[Link]() this will return a list of lines in a file
Closing a opened File
• It is a good practice to always close the file when you are done with it.
[Link]()
Counting number of Lines in a File
f=open(“c:\\[Link]”)
count=0
for lines in f:
count=count+1
print(count)
[Link]()
Searching through a file
Searching through a file involves the following:
• reading the entire file
• ignoring the lines that is not satisfying certain condition
• Processing the lines which satisfies certain required condition

For example, if we wanted to read a file and only print out lines which started with the
prefix “From:”

F=open(“filename”)
for lines in F:
if [Link](“From”):
print(lines)
Letting the User choose the File name
We can take the file name to read as input from the user so that
everytime we have to work on different files, we don’t need to
change the filename in the python code.

filename=input(“enter the filename:”)


F=open(filename)
for lines in F:
if [Link](“From”):
print(lines)
What will Happen if filename provided Doesn’t Exist
filename=input(“enter the filename:”)
F=open(filename)
for lines in F:
if [Link](“From”):
print(lines)

We will get File not Found Exception and our program will halt.
Important Variables in File Handling
• [Link]: checks if file is closed or not
• [Link]: Returns access mode with which file was opened.
• [Link]: Returns name of the file.
PYTHON Programming (CST310)
Lecture 14: Writing & Appending to Files in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 11, 2025
tell() method
f= open(‘[Link]’, ‘r’)

str= [Link]() # this will read all the contents of [Link] in one go
# Problem when size of file is big as it will bring all the
contents of the file [Link] into memory

str=[Link](10) # in this, 10 characters will be read from the file


str=[Link](10) # next 10 characters will be read

[Link]() #tells the current position in the file. It tells how many
characters/bytes it has read so far
seek() method
f= open(‘[Link]’, ‘r’)

str=[Link](10) # in this, 10 characters will be read from the file


str=[Link](10) # next 10 characters will be read

[Link]() #tells the current position in the file.

[Link](0) # it changes the current position of read to the specified location


# seek(0) is used to start reading from the beginning of the file
Creating a file using write() mode in Python
Step 1:
file = open(‘[Link]’, ’w’) # this will open the file in write mode. If file
exists, it will open the file for writing. If file doesn’t
exist, it will create a new file with that name.
Step 2:
[Link]("This is the write command")
[Link]("It allows us to write in a particular file")
Step 3:
[Link]() #manually called to flush the data into the created file
[Link]() # The close() command terminates all the resources in use and
frees the system of this particular program.
Using Seek() while writing to a file
file = open(‘[Link]’, ’w’)
[Link](“Test")
[Link](0) # this will take the writing cursor to 0th position
[Link](“R")
[Link]()
Appending to a File
Step 1:
file = open(‘[Link]’, ’a’) # this will open the file in append mode
Step 2:
[Link]("This is the write command") #
[Link]("It allows us to write in a particular file")
Step 3:
[Link]() # The close() command terminates all the resources in
use and frees the system of this particular program.
Writing to a file open in Read Mode
WAP to create an empty text file
WAP to create an empty text file
f= open(“[Link]”, ‘w’)
[Link]()
How to read all the content of a File character
by character
How to read all the content of a File character
by character
f=open("[Link]")
while(True):
char=[Link](1)
if not char:
break
print(char,end="")
WAP to Read the contents of a file “[Link]”
and writing it to another file “[Link]”
WAP to Read the contents of a file “[Link]”
and writing it to another file “[Link]”
rf= open(“[Link]”, ‘r’)
wf= open(“[Link]”, ‘w’)

for lines in rf:


[Link](lines)
[Link]()
[Link]()
Creating a copy of a Image file

[Link] Dal_copy.jpg
Creating a copy of a Image file
f=open("d:\\[Link]", 'rb’)

f1=open("d:\\dal_copy.jpg",'wb’)

for lines in f:
[Link](lines)

[Link]()
[Link]()
PYTHON Programming (CST310)
Lecture 15: Lists in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 15, 2025
Lists
• The list is one of the most widely used data types in Python.
• Like a string, a list is a sequence of values.
• In a string, the values are characters, but in a list, they can be any type.
• The values in list are called elements or sometimes items.
• Lists are used to store the data items where each data item is separated by a
comma (,).
• A Python List can have data items of any data type, be it an integer type or a
boolean type.
• There are several ways to create a new list.
• The simplest is to enclose the elements in square brackets (“[" and “]”)
For example: [1, 20, 30, 40] #this is list of 4 integers.
[“Asma”, “Sneha”, “Hatim”, “Kamran”] # list of 4 strings
Creating Lists
a= [1, 20, 30, 40] #this is list of 4 integers assigned to variable ‘a’.
b = [“Asma”, “Sneha”, “Hatim”, “Kamran”] # list of 4 strings assigned to ‘b’

c= [ 2.5, “Nit”, 24] #The elements of a list don’t have to be the same type

d= [ “Srinagar”, “Jammu”, [“JU”, “KU”, 23]] # This is nested list, i.e., list in
another list.
• A list with no elements is called as an empty list. An empty list can be
created as:
empty= []
Accessing List values or Elements
• Like Strings, the elements of Lists can be accessed using the indexes.
List_name[index]
• Indexing in a List are of two types:
1. Positive Indexing – Here the indexing starts from 0, moving from left
to right.
2. Negative Indexing – In this, the indexing starts from right to left and
the rightmost element has an index value of -1.
a = ['Hello', 1, 4.63, True, "World", 2.0, "False"]
Lists are Mutable
• Unlike Strings which are immutable, Lists are mutable which means
that the value of elements of Lists can be modified.
• you can change the order of items in a list or reassign an item in a list.
• Delete an element, add new element, update the value of an element
of a list.
For example:
a= [ 2020, “NIT Srinagar”]
a[0]=2020
print(a) #[2020,”NIT SRINAGAR”]
In operator Works in Lists
CSE2023= [ “Kamran”, “Ayushman”, “Kundan”]
>>> “Kundan” in CSE2023
True

>>> “Sneha” in CSE2023


False
Traversing the elements of a List
• The most common way to traverse the elements of a list is with a for loop.
• The syntax is the same as for strings:
for item in list_name:
print(item)
The above syntax is used when we just want to read the elements of list
• Using Index values also, the elements can be traversed as follow:
for i in range(len(list_name)):
list_name[i]=list_name[i]*3
print(list_name)
This method of traversal is used when we also want to update the elements of
list
What will be the Output?
x=[]

for item in x:
print(“hello”)
Traversing a Nested List
• A nested List contains another list as its element.
• For example: a= [“Car”, “Bike”, [“Bicycle”, “ Rikshaw”]]

for item in a:
print(item)

Although a list contain another list, the nested list still counts as a
single element.
Traversing a Nested List
How to Traverse all the elements of a List (including the nested list
element)?

a= ["Car", "Bike", ["Bicycle", "Rikshaw"]]

Output:
How to Traverse all the elements of a List
(including the nested list element)?
a= ["Car", "Bike", ["Bicycle", "Rikshaw"]]

for item in a:
if str(type(item)).find('list')!=-1:
for i in item:
print(i)
else:
print(item)
How to Traverse all the elements of a List
(including the nested list element)?
a = ["Car", "Bike", ["Bicycle", "Rikshaw", ["Bus", "Truck", ["Scooter",[1,2]]]]]

def print_list(a):
for items in a:
if 'list' in str(type(items)):
print_list(items)
else:
print(items)

print_list(a)
List operations
1. + Operator: between two lists performs the concatenation of two lists.
a= [ 1, 2, 3]
b= [10, 20, 30]
C=a+b #will return [1, 2, 3, 10, 20, 30]

2. The * operator repeats a list a given number of times.


a=[kamran’, asma']
print(a*3)
[‘kamran', ‘asma', ‘kamran', ‘asma', ‘kamran', ‘asma']
List Slicing
• The slice operator also works on lists.
t = ['a', 'b', 'c', 'd', 'e', ‘f’]
t[1:3] #will return a list [‘b’, ‘c’]
t[:] #will return a list containing all the elements of a list t
t[2:] # will return list containing elements from index 2 till end.

Since lists are mutable, it is often useful to make a copy before


performing operations.
t[1:3] = ['x', 'y’]
print(t) #outputs['a', 'x', 'y', 'd', 'e', 'f']
List Methods
Python provides methods that operate on lists.
1. Append: this method is used to add new element to a list in the end of
the list.
For example: a=[ 62, 30, 50]
[Link](300) #will append 300 in the list a in last.
2. Extend: this method takes a list as argument and append all the
elements of that list to the main list.
b= [300, 500]
[Link](b)
Print(a) # outputs [62, 30, 50, 300, 500]
3. Sort: this method arranges the elements of the list from low to high.
[Link]() # will sort the list a in ascending order
Most list methods are void; they modify the list and return None.
a=[Link]() # Output? None
List Methods
4. Clear: this method will delete all the elements of a list and return
empty list.
For example: [Link]()
5. Count: this method counts the occurrence of a element in a list.
[Link](23)
6. Reverse: this method reverses the list.
7. insert(): this method inserts new element in a specified index.
[Link](2,’cse’)
Deleting element from a list
• There are several ways to delete elements from a list.
• If you know the index of the element you want, you can use pop:
t = ['a', 'b', 'c’]
[Link](1) # will pop the element at index 1

Pop method modifies the list and returns the element that was
removed.
x= [Link](1)
If you don’t provide an index, it deletes and returns the last element.
Deleting elements of a List
• If you know the element you want to remove (but not the index), you
can use remove:
[Link](10) # this will remove the first occurrence of
element 10 from the list.
if element to delete is not in list, then this method gives
“ValueError: element not in list” exception
To delete more than one values, use the del method with slice operator
del t[2:3]
PYTHON Programming (CST310)
Lecture 16: Lists in Python (Part-2)

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 16, 2025
Inserting elements in a specific location
• New elements can be appended to a list using append() method.
• However, the append() method adds the new element to the end of the list.
For example,
a = [1,2,31,11]
[Link](100) #will insert 100 to the end of the list

What if we want to insert the element in between a list? Like in first or in


between a list.
Insert method
• The Python List insert() method is an inbuilt function in Python that inserts
a given element at a given index in a list.
[Link](index,element_to_insert)

a = [1,2,31,11]
[Link](0,1000)
This method does not return any value but it inserts the given element at the
given index.
If in above example, we write the following code:
[Link](1000,’a’)

What will be the output? Error or What?


Lists can have Duplicate elements
a= [ 1,2, 2, 2, 1, 1, 1, 2] # a list in python can have duplicate elements

Suppose we want to have a list with distinct and unique elements only.
How we can do that?
Storing only the unique elements in list
• a= [ 1,2, 2, 2, 1, 1, 1, 2]
Way 1: Using Set
• Unique=list(set(a))

• You can use a set to get the unique elements. Then, turn the set into a list.
Way 2 – Using Iteration to Identify Unique Values
>>> a= [ 1, 1, 1, 1, 2,1, 2]
>>> unique=[]
>>> for i in a:
if i in unique:
pass
else:
[Link](i)
Removing all the same element from a List
• Suppose, a= [ 1, 1, 1, 1, 2,1, 2]
[Link](1) # removes first occurrence of 1 in the list.

What if want to remove all the occurrence of 1 from the list?


What if want to remove all the occurrence of
1 from the list?
• Suppose, a= [ 1, 1, 1, 1, 2,1, 2]

for i in range([Link](1)):
[Link](1)
Built-in Functions in List
a= [ 1, 1, 1, 1, 2,1, 2]
1. Sum() Function in List
sum(a) # returns the sum of all the elements of the list
2. max(): returns the maximum elements in the list. max(a)
3. min(): returns the minimum element in the list. min(a)
4. len(): returns the total number of elements in a list. len(a)

• sum() function only works when all elements are numbers.


• The other functions (max(), len(), etc.) work with lists of strings and other types
that can be comparable.
Strings to Lists
• string is a sequence of characters and a list is a sequence of values,
but a list of characters is not the same as a string.
• To convert from a string to a list of characters, you can use list:
>>> a="NIT Srinagar"
>>> list(a)
['N', 'I', 'T', ' ', 'S', 'r', 'i', 'n', 'a', 'g', 'a', 'r']
Strings to Lists
• The list function breaks a string into individual letters. If you want to
break a string into words, you can use the split method
>>> a='NIT Srinagar’
>>> [Link]()
['NIT', 'Srinagar']
Lists to Strings
• Join() is the inverse of split.
• It takes a list of strings and concatenates the elements.
• join is a string method, so you have to invoke it on the delimiter and pass the list as a parameter.
a=“nit Srinagar 2023”
b= [Link]() # b will have a list [‘nit’, ‘Srinagar’, ‘2023’]
c= str(b) # Output will not be original string “nit Srinagar 2023”

del=‘’
[Link](b) #outputs a string “nitSrinagar2023”
# joins all elements of the list b into a single string, using a space " " as the separator.
del=‘ ’
[Link](b) #outputs a string “nit Srinagar 2023”
Objects and Values
If we write the following assignment statements in python:
a = 'banana’
b = 'banana’

we know that a and b both refer to a same string object ‘banana’.


Python only created one string object, and both a and b refer to it.
• To check whether two variables refer to the same object, you can use the is
operator.
>>> a is b
True
• when you create two lists, you get two objects:
>>> a = [1, 2, 3]
>>> b = [1, 2, 3]
>>> a is b
False

In this case we would say that the two lists are equivalent, because
they have the same elements, but not identical, because they are not
the same object.
Aliasing
• If a refers to an object and you assign b = a, then both variables refer to the same
object:
>>> a = [1, 2, 3]
>>> b = a
>>> b is a
True
An object with more than one reference has more than one name, so we say that
the object is aliased.
If the aliased object is mutable, changes made with one alias affect the other.
>>> b[0] = 17
>>> print(a)
[17, 2, 3]
What will be the Output?
def delete_head(t):
del t[0]

letters = ['a', 'b', 'c']


delete_head(letters)
print(letters)
What will be the Output?
>>> t1 = [1, 2]
>>> t2 = [Link](3)
>>> print(t1)
>>> print(t2)
PYTHON Programming (CST310)
Lecture 17: Tuples in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 18, 2025
Tuples in Python
• A tuple is a sequence of values much like a list.
• The values stored in a tuple can be any type, and they are indexed by
integers.
• The important difference is that tuples are immutable.
• Syntactically, a tuple is a comma-separated list of values:
>>> t = 'a', 'b', 'c', 'd', ‘e’,1,2,3
Although it is not necessary, it is common to enclose tuples in parentheses to
help us quickly identify tuples when we look at Python code:
>>> t = ('a', 'b', 'c', 'd', 'e')
Creating a tuple with Single Element
• To create a tuple with a single element, you have to include the final
comma:
>>> t1 = ('a',)
>>> type(t1)
<type 'tuple’>

Without the comma, Python treats ('a') as an expression with a string in


parentheses that evaluates to a string:
>>> t2 = ('a')
>>> type(t2)
<type 'str'>
Creating Tuple using tuple() function
• Another way to construct a tuple is the built-in function tuple.
• With no argument, it creates an empty tuple:
>>> t = tuple()
>>> print(t)
()

t= tuple((“a”,1,”c”)) #this will create a tuple with elements a,1,c

If the argument is a sequence (string, list, or tuple), the result of the call to tuple is a tuple
with the elements of the sequence:
>>> t = tuple('lupins')
>>> print(t)
('l', 'u', 'p', 'i', 'n', 's')
Accessing the values of a Tuple
• t= ‘a’,1,2,3,’b’,’c’,0,1,2,
The values of a tuple can be accessed as:
t[integer_index]

t[0]
Iterating through the values of a Tuple
• t= ‘a’,1,2,3,’b’,’c’

for item in t:
print(item)
Operators for tuple
• Most list operators also work on tuples.
• Slicing Operator works on tuples as well.
t = ('a', 'b', 'c', 'd', 'e’)
t[0:2] # will return a tuple with range of elements between index 0 and 2 (not inclusive)
• if you try to modify one of the elements of the tuple, you get an error:
>>> t[0] = 'A’
TypeError: object doesn't support item assignment
+ Operator: Concatenates the two tuples.
* Operator: Repeats the elements of tuples.
Comparing Tuples
• The comparison operators work with tuples.
• Python starts by comparing the first element from each sequence. If
they are equal, it goes on to the next element, and so on, until it finds
elements that differ.
• Subsequent elements are not considered (even if they are really big).
>>> (0, 1, 2) < (0, 3, 4)
True
>>> (0, 1, 2000000) < (0, 3, 4)
True
Methods in Tuples
• Index: returns the index of element in tuple.
• Count: returns the total occurrence of an element in a tuple.
Methods in Tuples
t=(1,2,3)
dir(t)
this will return all the methods applicable on tuple ‘t’.

Methods like __add__, __contains__ are the Special methods also called as
Double underscore methods that are used to perform different operations on the
tuple object.
When different operators are used, these special methods are invoked implicitly
and we cannot call them directly.
PYTHON Programming (CST310)
Lecture 18: Dictionaries in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 18, 2025
Dictionaries Data-type in Python
• Dictionary is another datatype in Python, which is similar to a list in
that it is a collection of elements (objects). But it is a Mapping data-
type
• In Lists, the index positions are integers only. But in Dictionaries, the
indices can be (almost) any type.
• In Dictionaries in python, the items are stored as key-value pair inside
the curly braces.
student= {key:value, key2:value2, key3:value3}
• We can think Dictionaries as a mapping between set of indices (which
are keys) and set of values.
• Each key maps to a value.
• The association of a key and a value is called as key-value pair.
How to Create a Dictionary
The elements in dictionaries in python are enclosed inside the Curly Braces {}.
student= {key:value, key2:value2, key3:value3}
>>> student = {"name":“kamran", 'age’:21, "courses":['python', ‘Database’]}

In Lists, elements are enclosed inside the Square Brackets []


In Dictionaries, elements are enclosed inside the Curly Braces {}
Empty Dictionary
Dictionary with no elements is called as Empty Dictionary.
Empty Dictionary can be created as : empty= {}
The function dict also creates a new dictionary with no items.
>>>d= dict()
>>>print(d)
>>>{}
So, dict() will create a empty dictionary (dictionary with no items).
The curly brackets, {}, represent an empty dictionary
Accessing Elements of the Dictionary
>>> student = {"name":“joginder", 'age’:21, "courses":['python', ‘Database’]}

To access the elements (key-value pairs) of a dictionary, use the following syntax:
student[key]

For example,
>>> student[‘name’]
>>> student[‘age’]
Keys in Dictionaries
a={ 123:[1,2,3] }
b= { [1,2]:'b’ } # Output?
Keys in Dictionaries
a={ 123:[1,2,3] }
b= { [1,2]:'b’ } # Output?

In Python, dictionaries are implemented as hash tables, which means that they require
their keys to be hashable.
A key is hashable if it has a hash value that never changes during its lifetime and can be
compared to other objects.
Lists in Python are mutable, meaning they can be changed after they are created. Since
lists are mutable, they are unhashable, and therefore, they cannot be used as keys in
dictionaries.
Use immutable data types (such as strings, numbers, or tuples) as keys in your
dictionary.
Accessing all Keys of a Dictionary
>>> student = {"name":“joginder", 'age’:21, "courses":['python',
‘Database’]}

To access all the keys of a dictionary, use the key() method:

>>>[Link]()
dict_keys(['name', 'age', 'courses’]) #this will be the output
Accessing all Values of a Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

To access all the values of a dictionary, use the values() method:

>>>[Link]()
dict_values(['rahul', 23, ['python', 'Operating System’]]) #output
Accessing all Elements (Key-Value) of a
Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

To access all the items (key-value pairs) of a dictionary, use the items() method:

>>>[Link]()
dict_items([('name', 'rahul'), ('age', 23), ('courses', ['python’, Database'])
Accessing Items of a Dictionary using Loops
All the Elements(key-value) of a Dictionary can also be accessed using loops.
>>>student={"name":“kamran", 'age’:21, "courses":['python', ‘Database’]}

for key in student: #Python iterates over the keys of the dictionary student
print(key) # we will get only the keys of the dictionary
or
for keys in [Link]():
print(keys) # this will print all the keys

for values in [Link]():


print(values) # this will print all the values
or
for key in student:
print(student[key])

for items in [Link]():


print(items) #this will print all the elements (key-values pairs)
Accessing Non-Existing Key of a Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

Suppose in above defined dictionary, we try to access key index which does not
exist:
print(student[‘city’]) # Interpreter will give error
Traceback (most recent call last):
File "<pyshell#22>", line 1, in <module>
print(student['city’])
KeyError: 'city
Accessing Non-Existing Key of a Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

We know on accessing non-existing key of a dictionary, python gives error.

Suppose, we don’t want to get the error for non-existing key, we will use the
get() method.
print([Link](‘city’)) # this will return none, if key doesn’t exist.

If we want to have some custom message for non-existing key:


print([Link](‘city’, ‘KEY Not Found’))
Adding new Items (Key-Value) to an Existing Dictionary
>>> student = {"name":"rahul", 'age':23, "courses":['python', ‘Database’]}

>>>student[‘city’]=‘Srinagar’
# This will insert the item with key city and value Srinagar in the dictionary
student
# If key ‘city’ is already there in the dictionary, then it will update the value of
existing key ‘city’

print(student)
{'name': 'rahul', 'age': 23, 'courses': ['python', 'Operating System'], 'city’: Srinagar'}
Method 2:
Adding/updating new Items (Key-Value) to an Existing
Dictionary
>>> student = {"name":“kamran", 'age':23, "courses":['python', ‘Database’]}

Suppose, we want to do following tasks in above dictionary:


1. Updation of ‘kamran’ to ‘Sneha’
2. Updation of age 23 to 21
3. Insertion of new item (key-value) City:Srinagar
Method 2:
Adding/updating new Items (Key-Value) to an Existing
Dictionary
>>> student = {"name":“kamran", 'age':23, "courses":['python', ‘Database’]}

Suppose, we want to do following tasks in above dictionary:


1. Updation of ‘kamran’ to ‘Sneha’
2. Updation of age 23 to 21
3. Insertion of new item (key-value) City:Srinagar

One way is
Student[‘name’]=‘Sneha’
student[‘age’]=21
student[‘city’]=‘Srinagar’

If We want to do the above 3 tasks in one statement, we will use the update() method.
[Link]({‘name’:Sneha’, ‘age’:21, ‘city’: ‘Srinagar’})
Deletion in Dictionaries
Deletion of items in dictionaries can be done by following ways:
1. Using del
del student[‘city’]
2. Using pop method
[Link](‘city’)
pop method returns the value it has deleted.
Dictionaries in Python are Mutable
• Like Lists, the dictionaries in python are mutable in nature.
• So, updation in the same object of dictionaries are allowed.
Methods/Functions in Dictionaries
• len(): Counting keys of a dictionary.
• Copy() method: this method creates a copy of elements of a
dictionary
Output?
student = {"name":"rahul", 'age':23, “name”: ”Arjun” }
Output?
Can we do This?

student = {[‘’fname’’, ‘’lname”]: “NIT Srinagar" } #list is used as a key

student = {(‘’fname’’, ‘’lname”]): “NIT Srinagar" } #tuple is used as a key


Only Immutable objects can be used as a key
Since lists are mutable, we can't use a list as a key in a dictionary.
This is because only an immutable object can be used as a key in a dictionary.
Thus, we can use tuples as dictionary keys if needed
PYTHON Programming (CST310)
Dictionaries Practice Programs

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 22, 2025
1. Creating Dictionaries from given lists
Given following two lists:
keys = ['Ten', 'Twenty', 'Thirty']
values = [10, 20, 30]

WAP to Convert the above two lists into a Dictionary such that the final
created dictionary contains elements as following:
{'Ten': 10, 'Twenty': 20, 'Thirty': 30}
Solution:
• >>>d={} # empty dictionary
• >>> for i in range(len(keys)): # iterating till length of list
• [Link]({keys[i]:values[i]}) #adding elements from list to dictionary
D[keys[i]=value[i]

• >>> d
• {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
Program 2:
Merge following two Python dictionaries into one
>>>dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
>>> dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}

WAP to Merge the above given two dictionaries into one Dictionary

Output should be as:


{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
Solution to Problem 2:
>>> [Link](dict2)

Output will be
{'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
Problem 3
What if we want to merge two dictionaries (dict1 and dict2) and save
their content in dict3?
>>>dict1 = {'Ten': 10, 'Twenty': 20, 'Thirty': 30}
>>> dict2 = {'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
Dict3= {'Ten': 10, 'Twenty': 20, 'Thirty': 30, 'Fourty': 40, 'Fifty': 50}
Solution to Problem 3
dict3=[Link]()
[Link](dict2)
Problem 4
Given this dictionary
sampleDict = { "class":{ "student":{ "name":"Mike", "marks":{ "physics":70,
"history":80 }}}}
1. Compute the length of this dictionary
2. How to access the value of Key “history” from above dictionary.
Solution to Problem 4
sampleDict = { "class":{ "student":{ "name":"Mike", "marks":{
"physics":70, "history":80 }}}}
1. Compute the length of this dictionary:
len(sampleDict) # output 1
2. How to access the value of Key “history” from above dictionary.
sampleDict["class"]["student"]["marks"]["history"]
Problem 5:
Check if a value 200 exists in a dictionary
sampleDict = {'a': 100, 'b': 200, 'c': 300}
Problem 6:
sampleDict = {'a': 100, 'b': 200, 'c': 300, ‘d’=200}
Check if a value 200 exists in a dictionary. If yes, then what is its corresponding
key.
Solution to Problem 6
for k,v in [Link]():
if 200 == v:
print(k)
or
for item in [Link]():
if 200 in item:
print(item[0])
Problem 7
• Rename key “city” to “location” in the following dictionary
sampleDict = { "name": "Kelly", "age":25, "salary": 8000, "city":
"New york“ }

Expected Output
sampleDict = { "name": "Kelly", "age":25, "salary": 8000,
“location": "New york“ }
Solution 7
sampleDict = { "name": "Kelly", "age":25, "salary": 8000, "city":
"New york“ }

sampleDict['location'] = [Link]('city')
print(sampleDict)
Problem 9:
Find key of a minimum value from the following
dictionary
sampleDict = { 'Physics': 82, 'Math': 65, 'history': 75 }
Solution to Problem 9:
Find key of a minimum value from the following
dictionary
sampleDict = { 'Physics': 82, 'Math': 65, 'history': 75 }
min(sampleDict)
Problem 10:
• Change Brad’s salary to 8500 from a given Python dictionary:
sampleDict = {
'emp1': {'name': 'Jhon', 'salary': 7500},
'emp2': {'name': 'Emma', 'salary': 8000},
'emp3': {'name': 'Brad', 'salary': 6500}
}
Problem 11:
Delete set of keys from a dictionary
sampleDict = {
"name": "Kelly",
"age":25,
"salary": 8000,
"city": "New york"
}
keysToRemove = ["name", "salary"]
Solution to Problem 11
for i in keysToRemove:
del sampleDict[i]
PYTHON Programming (CST310)
Lecture 20: Regular Expressions in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 23, 2025
Regular Expression in Python
• Regular Expression also called as Regex
• Regular Expression is a pattern matching technique in which first a Search
Pattern is provided, and then all the strings in a given Text which satisfy the
search pattern criteria is returned.
• We can use also use existing String searching methods for finding whether a
required substring is within a given string or not. But, for complex searching,
the use of existing string searching method becomes difficult.

For Example:
In the below given text, find out all the dates.
“Deep learning has 23-04-2022 emerged as 31-April-2022 promising technique
for kind [Link].2022 of elements 21/09/2022 of communicable 12-Oct-2022
disease monitoring and detection, including TB.”
Regular Expression in Python
• Definition 1: A Regular Expressions (RegEx) is a special sequence of
characters that uses a search pattern to find a string or set of strings.
• Definition 2: A Regular Expression (RegEx) is a sequence of characters that
defines a search pattern. For Example:
^a….s$ is a RegEx pattern that will search for a string with six letters and
which starts with character ‘a’ and ends with character ‘s’

• It can detect the presence or absence of a text by matching with a particular


pattern, and also can split a pattern into one or more sub-patterns.
• Its primary function is to offer a search, where it takes a regular expression
and a string.
Applications of Regular Expressions
• Web Scraping: (Fetching all the emails, mobile nos, urls, etc. from a webpage
• Phone no extraction
• Password Strength Verifier
• Email extraction and verification
Using Regular Expression in Python

For implementing the Regex in python for pattern matching, following steps
are needed to be performed:
1. Importing the Module:
import re #re module is used for Regex in python

2. Defining the Search Pattern


3. Fetching the strings satisfying the Search Pattern
4. Iterating through the results and performing some further processing as
per the requirement.
Search Patterns
A search pattern in regex is a sequence of characters that defines the rules for the
text you want to match.
This sequence can include:
• Literal characters → match exact characters, e.g., cat matches "cat".
• Metacharacters → special characters with a specific meaning in regex, e.g., . (any
character), \d (digit), ^ (start of string), $ (end of string), [] (character class), etc.

For example,
if we want to search for all the substrings of length 5 which starts with a digit ‘0’ and
ends with digit ‘9’

0…9 #search pattern for above task


or
0[a-z][a-z][a-z] 9
Defining a Search Pattern
Compile function compiles a regex pattern into a regex object, which
can then be used multiple times for searching, matching, or other
operations.
Defining the pattern: You still write the regex string, e.g., "a....s".
Compiling the pattern: [Link]("a....s") creates a regex object from
the string, which is more efficient if you are going to use the same
pattern multiple times.
import re
Pattern = [Link](“here we will provide our pattern”)
Regex Functions :
[Link]
• Search: This method returns the match object if there is a match
found in the string.

import re
line=“NIT Srinagar is located in Jammu and Kashmir”
match=[Link](‘Jammu’,line)
print(“Start Index”,[Link]())
print(“End Index”[Link]())
[Link]()
• Return all non-overlapping matches of pattern in string, as a list of
strings.
• The string is scanned left-to-right, and matches are returned in the
order found.
MetaCharacters in RE
Metacharacters are the characters which are treated in a special way in RE.

MetaCharacters Description
Used to drop the special meaning of character
\
following it
[] Represent a character class
^ Matches the beginning
$ Matches the end
. Matches any character except newline
Means OR (Matches with any of the characters
|
separated by it.
? Matches zero or one occurrence
* Any number of occurrences (including 0 occurrences)
+ One or more occurrences
Indicate the number of occurrences of a preceding
{}
regex to match.
() Enclose a group of Regex
^ Caret
• Caret (^) symbol matches the beginning of the string i.e. checks whether the
string starts with the given character(s) or not.
• For example:
^g will check if the string starts with g such as geeks, globe, girl, g, etc.

$ – Dollar
Dollar($) symbol matches the end of the string i.e. checks whether the string ends
with the given character(s) or not. For example:
s$ will check for the string that ends with a such as geeks, ends, s, etc.

. Dot
Dot(.) symbol matches only a single character except for the newline character
(\n). For example – a.b will check for the string that contains any character at
the place of the dot such as acb, adb, abb, etc
\ Backslash
• The backslash (\) makes sure that the character is not treated in a special way.
• For example: Suppose you want to search for the occurrence of dot(.) in string s
>>>import re
>>>s=“[Link]”
>>>pattern=[Link](‘.’) #dot(.) here will be taken as metacharacter
>>>match=[Link](s)
>>>print(match)
>>>match=[Link](“\.”,s) #so \. will tell the python to not to treat . in special way.
[] – Square Brackets
• Square Brackets [] represents a character class consisting of a set of
characters that we wish to match.
• For example, the character class [abc] will match any single a or b or
c,
• If we write
[Link](“[NJK]….”,”NIT Srinagar Jammu and Kasshmir”)
This will return a string which of length 5 having first character as
either N or J or K
* – Star
• Star (*) symbol matches zero or more occurrences of the regex
preceding the * symbol. For example –
ab*c will be matched for the string ac, abc, abbbc, etc. but will not be
matched for abdc because b is not followed by c.
+ – Plus
• Plus (+) symbol matches one or more occurrences of the regex
preceding the + symbol. For example –
• ab+c will be matched for the string abc, abbc, but will not be matched
for ac, abdc because there is no b in ac and d is not followed by c in
abdc.
Special Sequences
\d Matches any decimal digit, this is equivalent to the set class [0-9]
Prog. 1: Find all numbers from the string
>>>a="1 is 23 located 9999“

In the above string, extract all the numeric data like 1, 23, 9999
Solution to Prog. 1:
Find all numbers from the string
import re
matches=[Link]("[0-9]+",a)
for match in matches:
print(match)
Or
importre
pattern= [Link]('\d+')
matches=[Link](a)
for match in matches:
print(match)
Prog. 2: Find all mobile numbers from a string
>>>text=“ as sd d 9999999999 asahj 3739475983 asjak 4817394729”

In the above string, extract all the mobile numbers


Solution to
Prog. 2: Find all mobile numbers from a string
text=“ as sd d 9999999999 asahj 3739475983 asjak 4817394729”

Import re

Pattern = [Link](‘\d\d\d\d\d\d\d\d\d\d’)
#Pattern = [Link](‘[0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9] [0-9]’)
#pattern = [Link](‘\d{10}’)

matches= [Link](pattern)
for match in matches:
print(match)
PYTHON Programming (CST310)
Lecture 21: Regular Expressions in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 25, 2025
Using Regular Expression in Python

For implementing the Regex in python for pattern matching, following steps
are needed to be performed:
1. Importing the Module:
import re #re module is used for Regex in python
2. Defining the Search Pattern
3. Iterating through the results and performing some further processing as
per the requirement.
Program 1: Find all the emails from a text
• Given some data.
• WAP that will extract all the emails from that data.
Solution to Program:
Find all emails
text="hello demo@[Link] how d@[Link] ahj as cse@[Link]"

import re
pattern=[Link](r"[a-zA-Z0-9._]+@[a-zA-Z0-9._]+\.[a-zA-Z0-9._]+")
a=[Link](text)
for item in a:
print(item)
Program 2:
Program to check whether the user has entered a
valid email or not
User enters: demo@[Link]
Program Outputs: Valid email

User enters: daaj_.com


Output: Invalid Email
Solution to Program:
Check whether the user has entered a valid email
or not
import re #module importing
email=input("enter the email") #taking email from user
pattern=[Link](r"[a-zA-Z0-9._]+@[a-zA-Z0-9._]+\.[a-zA-Z0-9._]+")

if [Link](email):
print("Email is valid")
else:
print("Invalid email")
Program 3:
WAP to find all the lines starting with
“<script” tag in a Webpage stored in a Text File
Given Sample data:
Solution to Program:
WAP to find all the lines starting with
“<script” tag in a text file
import re #importing module
f=open("[Link]") #opening the text file
pattern=r"^<script“ #search pattern
for line in f:
s=[Link](pattern,line)
if s == None:
pass
else:
print(line)
[Link]()
Program 4
WAP to check the password Strength
• Password length must be 8 or more
• Password must contain special character
Solution to Program:
WAP to check the password Strength
import re

password=input("enter the password")

pattern=[Link]("[a-zA-Z0-9@$_!]{8,}")
pattern2=[Link]('[@$_!]')
if [Link](password) and [Link](password)!=None:
print("Password is strong")
else:
print("Week Password")
Python program 5
Python program to check that a string entered by the user contains
only a certain set of characters (in this case a-z, A-Z and 0-9).
Solution to Program:
Python program to check that a string entered by the user contains only a certain
set of characters (in this case a-z, A-Z and 0-9).

import re

pattern=r"^[a-zA-Z0-9]+$"
while True:
data=input("enter the string")
if [Link](pattern,data):
print("entered string contains only the allowed characterset")
else:
print("entered string contains special characters")
Prog. 6: Extracting IP Addresses from a text
“This is some random text [Link] containing different ip addresses
[Link] Our task is to extract the ip [Link] from this text for
practice”

IP address formats: _ _ _._ _ _._ _ _._ _ _


Solution:
text="This is some random text [Link] containing different ip addresses
[Link] Our task is to extract the ip [Link] from this text for
practice"

import re # importing module


pattern=[Link]("\d+\.\d+\.\d+\.\d+") #search Pattern

matches = [Link](text) #finding the matches


for match in matches:
print(match)
Prog. 7:
Extracting IP Addresses from a text
“"This is some random text [Link] containing different ip addresses
[Link] Our task is to extract the ip [Link] from this
[Link] text for practice 2222.2222.222.2222"”

The RE Pattern ("\d+\.\d+\.\d+\.\d+") will not work for this text. It will
fetch 2222.2222.222.2222 IP Address also, which is not valid IP.
Similarly, [Link] is also not a valid ip as maximum number in
a octet can be 255.
Solution
import re
data="This is some random text [Link] containing different ip addresses [Link] Our task is to extract the
ip [Link] from this [Link] text for practice 2222.2222.222.2222"

#for each octet


#1-255
#250-255 25[0-4]
#200-249 2[0-4]\d
#1-199 1?\d?\d

pattern=r'((25[0-4]|2[0-4]\d|1?\d?\d)\.(25[0-4]|2[0-4]\d|1?\d?\d)\.(25[0-4]|2[0-4]\d|1?\d?\d)\.(25[0-4]|2[0-
4]\d|1?\d?\d))\b'

#print([Link](pattern,data))

matches=[Link](pattern,data)
for item in matches:
print(item[0])
PYTHON Programming (CST310)
Lecture 22: URLLIB Module and RE in Python

Department of Computer Science and Engineering


National Institute of Technology, Srinagar, Jammu and Kashmir
September 30, 2025
[Link] Module
• [Link] module is used for interacting with the websites from
the python program.
• [Link]: This is a submodule of urllib specifically designed for
opening and reading URLs.
• It provides functions and classes to fetch data from the internet, send
HTTP requests, and handle responses.
• Using [Link] module, we can open a web URL and save the
source code of that webpage.
How to Open a website using Python and save
its Source Code
• We will see how we can open a website in a python program and save its
source code in a file or a variable.
>>>Import [Link]
>>>url=input(r“enter the website url”)
>>>requested_url=[Link](url) //Returns response object (similar to a file object.)
>>>data=str(requested_url.read()) #content is usually in bytes format (raw bytes from the server).
After obtaining the source code of a website, further tasks like extraction of
emails, mobile numbers, etc. can be performed.
Extracting the emails and Mobile no.s from the
fetched website`s source code
Steps involved in Extracting Emails and Mobile
Nos from a Given URL
• Step 1: Import the [Link] module and open the given URL.
• Step 2: Save the source code of the of webpage of the URL opened in
Step 1 to some text file or some variable.
• Step 3: Using the File Handling, open the saved text file where the
webpage source code is saved. (optional)
• Step 4: Using the RE module, create the pattern for Emails and Mobile
Extraction.
Extracting the emails and Mobile no.s from
the fetched website`s source code
import [Link]
url=input(r"enter the website url")
requested_url=[Link](url) #code for source code fetching
data=str(requested_url.read())

import re
pattern_mobile=[Link]("\d\d\d\d\d\d\d\d\d\d") #Mobile No. Search Pattern
pattern_email=[Link]("[a-zA-Z0-9._]+@[a-zA-Z.0-9]+\.[a-zA-Z]+") #Email Search Pattern
mobile_details=pattern_mobile.findall(data)
email_details=pattern_email.findall(data)

print("fetched mobile numbers are:")


for item in mobile_details:
print(item)
print("fetched emails are:")
for item in email_details:
print(item)
Extracting the emails and Mobile no.s from
the fetched website`s source code
Practice Program:
WAP to create a web Crawler
Suppose, user enters a website say [Link]
So, your web-crawler will find all the possible webpages of [Link].
For example:
[Link]
[Link]
[Link]

After Crawling the webpages, find all the emails and mobile numbers
from that webpages and save them in a separate text file

You might also like