Introduction to Python Programming
Introduction to Python Programming
• Programmers have some tools that allow them to build new tools
Computer
Programmer
Hardware + Software
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?
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
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.
[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.
A=10
print(A)
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(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.
30 or 30.5
Performing different operations on Variables
a=10
b=20.5
Print(a+b)
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
• 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
is equivalent to
== 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.
>>> 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
the operands of the logical operators should be boolean expressions, but Python is not very strict. Any
nonzero number is interpreted as “true.”
>>> 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
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
>>> 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
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;
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)
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
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)
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
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)
(For example if input unit is 350 than total bill amount is Rs2000)
Practice Programs
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”.
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
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.
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’
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):
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.
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
• 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.
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
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
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
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)
2. Get a substring 4 characters long, starting from the 3rd character of the 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"
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”
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=“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:”
s[[Link]("[")+1:[Link]("]")]
or
s[[Link]("[")+1:[Link]("]")]
Problem 2:
s=“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:”
s[[Link]("@")+1:[Link]("w")-1]
or
s[[Link]("@")+1:[Link](" ",[Link]("@"))]
Practice Program
s= “Reply from [Link]: bytes=32 time=90ms TTL=48”
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
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.
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.
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.
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
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
[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’)
[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
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
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)?
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]
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)
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’)
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.
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)
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’
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]
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
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’]}
>>>[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’]}
>>>[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
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’]}
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.
>>>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’]}
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?
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 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
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’
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
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’
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”
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
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
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
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”
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"
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
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)
After Crawling the webpages, find all the emails and mobile numbers
from that webpages and save them in a separate text file