0% found this document useful (0 votes)
16 views63 pages

Python Programming Basics Guide

Python is a versatile programming language created by Guido van Rossum in the late 1980s, known for its simplicity and readability. It supports various programming paradigms and includes features like variables, data types, operators, and control structures such as loops and conditionals. The document also covers Python's built-in data structures like lists and tuples, along with their methods and characteristics.

Uploaded by

tggoyarcs2004
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)
16 views63 pages

Python Programming Basics Guide

Python is a versatile programming language created by Guido van Rossum in the late 1980s, known for its simplicity and readability. It supports various programming paradigms and includes features like variables, data types, operators, and control structures such as loops and conditionals. The document also covers Python's built-in data structures like lists and tuples, along with their methods and characteristics.

Uploaded by

tggoyarcs2004
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

UNIT 1ST

Python Introduction
What is the brief history of Python?
Python was conceived in the late 1980s by Guido van Rossum at Centrum
Wiskunde & Informatica (CWI) in the
Netherlands as a successor to the ABC programming language, which
was inspired by SETL, capable of exception handling and interfacing with
the Amoeba operating system. Its implementation began in December
1989.

What is Python?
Python is a popular programming language. It was created by Guido
van Rossum, and released in 1991. It is used for:
• web development (server-side),
• software development,
• mathematics,
• system scripting.

✓ Python Syntax

>>> print("Hello,
World!") Hello,
World!

✓ Python Comments

• Comments can be used to explain Python code.


• Comments can be used to make the code more readable.

Comments starts with a #, and Python will ignore them:


Example
#This is a comment
print("Hello,
World!")

✓ Variables
Variables are containers for storing data values.

• Variable names should start with a letter or an underscore


• Variable names should not contain special characters, except for
underscores
• Variable names are case-sensitive
• Variable names should not be
Python keyword x = str(3) # x will
be '3'
y = int(3) # y will be 3
z = float(3) # z will be 3.0

1. Assigning single value to

multiple variables Eg:


1. x=y=z=50

2. print(x)
3. print(y)

4. print(z)
Output:
50
50
50
2. Assigning multiple values to multiple variables:
Eg:
1. a,b,c=5,10,15

2. print a
3. print b
4. print c
Output:
5
10
15
Python Variable Types
There are two types of variables in Python - Local variable and Global
variable. Let's understand the following variables.
Local Variable
A user can only access a local variable inside the function but never outside .
The variables that are declared within the function and have scope within
the function are known as local variables.
Example -
1. # Declaring a function

2. def add():
3. # Defining local variables. They has scope only within a function
4. a = 20
5. b = 30
6. c=a+b
7. print("The
sum is:", c) 8.
9. # Calling a function
10. add()
Output:
The sum is: 50
Global Variables
Global variables can be used inside or outside the function.
By default, a variable declared outside of the function serves as the global
variable.
Difference Between Local and Global Variables
Parameter Local Global Variables
Variables
Defined Defined outside
Definition inside a of all functions or
function blocks.
or block.
Keyword No Use the global
for special keyword to
Modificati keywo modify it inside a
on rd is function.
require
d.
Mem Stored in Stored in the
ory the stack. data segment of
Stora memory.
ge

Keywords in Python
Python Keywords are some predefined and reserved words in Python that
have special meanings. All the keywords in Python are written in lowercase
except True and False. There are 35 keywords in Python 3.11.
List of Python Keywords

Keywor Description
ds
and This is a logical operator which returns true if both the operands
are true else returns false.
or This is also a logical operator which returns true if anyone operand
is true else returns false.
not This is again a logical operator it returns True if the operand is
false else returns false.
if This is used to make a conditional statement.

elif Elif is a condition statement used with an if statement. The elif


statement is executed if the previous conditions were not true.

else Else is used with if and elif conditional statements. The else block
is executed if the given condition is not true.
for This is used to create a loop.
while This keyword is used to create a while loop.
break This is used to terminate the loop.
Keywor Description
ds
def It helps us to define functions.
pass This is a null statement which means it will do nothing.
return It will return a value and exit the function.
True This is a boolean value.
False This is also a boolean value.

Rules for Naming Python Identifiers


• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).
Examples of Python Identifiers
Valid identifiers:
• var1
• _var1
• _1_var
• var_1
Invalid Identifiers
• !var1
• 1var
• 1_var
• var#1
• var 1
standard type or data type
• Numeric – int, float, complex
• Sequence Type – string, list, tuple
• Mapping Type – dict
• Boolean – bool
• Set Type – set, frozenset
• Binary Types – bytes, bytearray, memoryview

Python Operators
Operators are used to perform operations on variables and values.
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common
mathematical operations:

Operat Name Example Try


or it
+ Addition x+y
- Subtraction x-y
* Multiplicati x*y
on
/ Division x/y
% Modulus x%y

Python Assignment Operators


Assignment operators are used to assign values to variables:

Operator Exampl Same As


e
= x=5 x=5
+= x += 3 x=x+3
-= x -= 3 x=x-3
*= x *= 3 x=x*3
/= x /= 3 x=x/3
%= x %= 3 x=x%3

Python Comparison Operators


Comparison operators are used to compare two values:

Operat Name Example Try


or it
== Equal x == y Try it
»
!= Not equal x != y Try it
»
> Greater x>y Try it
than »
< Less than x<y
Python Logical Operators
Logical operators are used to combine conditional statements:

Opera Description Example


tor
and Returns True if x < 5 and
both statements x < 10
are true
or Returns True if one x < 5 or x
of the statements <4
is true
not Reverse the result, not(x < 5
returns False if the and x <
result is true 10

Python Bitwise Operators


Bitwise operators are used to compare (binary) numbers:

Opera Na Description Examp


tor me le
& AN Sets each bit to 1 x&y
D if both bits are 1
| OR Sets each bit to 1 x|y
if one of two bits
is 1
^ XO Sets each bit to 1 x^y
R
if only one of two
bits is 1

Python Numbers
There are three numeric types in Python:
• int
• float
• comp
lex x = 1
# int
y = 2.8 # float
z = 1j # complexStrings
Strings
Strings in python are surrounded by either single quotation
marks, or double quotation marks. 'hello' is the same as "hello".
print("Hel
lo")
print('Hell
o')

Slicing
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a
part of the string.

b = "Hello, World!"
print(b[2:5])
The upper() method returns the
string in upper case: a = "Hello,
World!"
print([Link]())
The lower() method returns the
string in lower case: a = "Hello,
World!"
print([Link]())
String Concatenation
To concatenate, or combine, two strings you can use the + operator.
a = "Hello"
b = "World"
c=a+b
print(c)

String Methods

Method Description
[Link] Converts the first character
() to upper case
2. Returns a centered string
center(
)
[Link]() Returns the number of times
a specified value occurs in a
string
4. find() Searches the string for a
specified value and
returns the position of
where it was found
[Link]() Searches the string for a
specified value and
returns the position of
where it was found
6. Returns True if all characters
islower in the string are lower case
()
[Link] Returns True if all characters
() in the string are numeric
8. Returns True if all characters
isupper in the string are upper case
()
9. lower() Converts a string into lower
case
10. Returns a string where a
replace specified value is replaced
() with a specified value
11. rfind() Searches the string for a
specified value and
returns the last position of
where it was found
12. strip() Returns a trimmed version of
the string
13. Swaps cases, lower case
swapca becomes upper case and vice
se() versa
14. title() Converts the first character
of each word to upper case
15. Converts a string into upper
upper case
()
Boolean Values
In programming you often need to know if an
expression is True or False. Print a message based
on whether the condition is True or False:
a = 200
b = 33

if b > a:
print("b is greater
than a") else:
print("b is not greater than a")

Python Memory Allocation


Memory allocation is an essential part of the memory management for a
developer. This process basically allots free space in the computer's virtual
memory, and there are two types of virtual memory works while executing
programs.
o Static Memory Allocation
o Dynamic Memory Allocation

Python Conditions and If statements


Python supports the usual logical conditions from mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")
Elif
The elif keyword is Python's way of saying "if the previous conditions were
not true, then try this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater
than a") elif a == b:
print("a and b are equal")
Else
The else keyword catches anything which isn't caught by the preceding
conditions.
Example
a = 200
b = 33
if b > a:
print("b is greater
than a") elif a == b:
print("a and b
are equal") else:
print("a is greater than b")

And
The and keyword is a logical operator, and is used to combine
conditional statements: Example
Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Not
The not keyword is a logical operator, and is used to reverse the result of
the conditional statement:
Example
Test if a is NOT greater than b:
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
Nested If
You can have if statements inside if statements, this is called nested if
statements.
Exam
ple x
= 41

if x > 10:
print("Above
ten,") if x >
20:
print("and also
above 20!") else:
print("but not above 20.")
Python Loops
Looping means repeating something over and over until a particular
condition is satisfied.

Python has two primitive loop commands:


• while loops
• for
loops The
while
Loop
With the while loop we can execute a set of statements as long as a
condition is true
Print i as long as i is less than 6:
i=1
while i < 6:
prin
t(i) i
+= 1
The break Statement
With the break statement we can stop the loop even if
the while condition is true: i = 1
while i < 6:
print
(i) if i
== 3:
break
i += 1
The continue Statement
With the continue statement we can stop the current iteration,
and continue with the next: Example
Continue to the next iteration if i is 3:
i=0
while i < 6:
i += 1
if i == 3:
conti
nue
print(i)
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a
tuple, a dictionary, a set, or a string). Print each fruit in a fruit list:
fruits = ["apple",
"banana", "cherry"] for x
in fruits:
print(x)
Using the range()
function: for x in
range(6):
print(x)
ONE UNIT COMPLETE ………
UNIT 2ND
Python List methods
Python list methods are built-in functions that allow us to perform various
operations on lists,
such as adding, removing, or modifying elements.
In this article, we’ll explore all Python list methods with a simple example.
List Methods
Let’s look at different list methods in Python:
• append(): Adds an element to the end of the list.
• copy(): Returns a shallow copy of the list.
• clear(): Removes all elements from the list.
• count(): Returns the number of times a specified element appears in the
list.
• extend(): Adds elements from another list to the end of the current list.
• index(): Returns the index of the first occurrence of a specified element.
• insert(): Inserts an element at a specified position.
• pop(): Removes and returns the element at the specified position (or the
last element if no index is specified).
• remove(): Removes the first occurrence of a specified element.
• reverse(): Reverses the order of the elements in the list.
• sort(): Sorts the list in ascending order (by default).
• Examples of List Methods
• append():
• Syntax: list_name.append(element)

Tuple
Tuples are used to store multiple items in a single variable.
Tuple is one of 4 built-in data types in
Python used to store collections of data,
the other 3 are List, Set, and Dictionary,
all with different qualities and usage. A
tuple is a collection which is ordered and
unchangeable.
Tuples are written with round brackets.
Example
thistuple =
("apple",
"banana",
"cherry")
print(thistup
le)

Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item
has index [1] etc.

Ordered
When we say that tuples are ordered, it means that the items
have a defined order, and that order will not change.

Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or
remove items after the tuple has been created.

Tuple Characteristics
Tuples are:
• Ordered - They maintain the order of elements.
• Immutable - They cannot be changed after creation.
• Allow duplicates - They can contain duplicate values.
• Access Tuple Items
• Each item in a tuple is associated with a number, known as a index.
• The index always starts from 0, meaning the first item of a tuple is at index 0, the second item is at index 1, and so on.

•• languages = ('Python', 'Swift', 'C++')



• # access the first item
• print(languages[0]) # Python

• # access the third item
• print(languages[2]) # C++
Tuple Cannot be Modified
Python tuples are immutable (unchangeable). We cannot add, change, or delete items of a tuple.
If we try to modify a tuple, we will get an error. For example,
• cars = ('BMW', 'Tesla', 'Ford', 'Toyota')

• # trying to modify a tuple
• cars[0] = 'Nissan' # error

• print(cars)

Python Tuple Length


We use the len()
function to find the
number of items
present in a tuple. For
example, cars =
('BMW', 'Tesla',
'Ford', 'Toyota')
print('T
otal

Items:',

len(car

s)) #

Output

: Total

Items:

4
Iterate Through a Tuple
We use the for
loop to iterate
over the items of
a tuple. For
example, fruits =
('apple','banana','
orange')

#
iterate
throug
h the
tuple
for
fruit in
fruits:
pri
nt(
frui
t)
Ru
n
Co
de
Ou
tp
ut
ap
ple
ba
na
na
or
an
ge

Python Tuple Operations


Below are the Python tuple operations.
• Accessing of Python Tuples
• Concatenation of Tuples
• Slicing of Tuple
• Deleting a Tuple

Accessing of Tuples
We can access the elements of a tuple by using indexing and
slicing,
similar to how we access elements in a list. Indexing starts at 0
for the first element and goes up to n-1,
where n is the number of elements in the tuple. Negative indexing
starts from -1 for the last element and goes backward.

Example:
#
Accessi
ng
Tuple
with
Indexin
g tup =
tuple("
Geeks"
)
print(tu
p[0])

# Accessing
a range of
elements
using slicing
print(tup[1:4
])
print(tup[:3])

# Tuple unpacking
tup = ("Geeks", "For", "Geeks")

# This
line
unpack
values of
Tuple1
a, b, c =
tup
p
ri
n
t(
a
)
p
ri
n
t(
b
)
p
ri
n
t(
c
)

Output
G
('e', 'e', 'k')
('G', 'e', 'e')
G
e
e
k
s
F
o
r
G
e
e
k
s

Concatenation of Tuples
Tuples can be concatenated using the + operator. This operation
combines two or more tuples to create a new tuple.
Note- Only the same datatypes can be combined with
concatenation, an error arises if a list and a tuple are combined.

tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')

tup3 =
tup1 +
tup2
print(t
up3)
Output
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')
Concatenation of Tuples
Tuples can be concatenated using the + operator. This operation
combines two or more tuples to create a new tuple.
Note- Only the same datatypes can be combined with
concatenation, an error arises if a list and a tuple are combined.

tup1 = (0, 1, 2, 3)
tup2 = ('Geeks', 'For', 'Geeks')

tup3 =
tup1 +
tup2
print(t
up3)

Output
(0, 1, 2, 3, 'Geeks', 'For', 'Geeks')

Slicing of Tuple
Slicing a tuple means creating a new tuple from a subset of
elements of the original tuple. The slicing syntax is
tuple[start:stop:step].
Note- Negative Increment values can also be used to reverse the
sequence of Tuples.

# Slicing
of a
Tuple
with
Number
s tup =
tuple('G
EEKSF
ORGEE
KS')

#
Remo
ving
First
eleme
nt
print(t
up[1:])
#
Reve
rsing
the
Tuple
print(
tup[::
-1])

#
Printing
element
s of a
Range
print(tup
[4:9])

Output
('E', 'E', 'K', 'S', 'F', 'O', 'R', 'G', 'E', 'E', 'K', 'S')
('S', 'K', 'E',
'E', 'G', 'R',
'O', 'F', 'S',
'K', 'E', 'E',
'G') ('S', 'F',
'O', 'R', 'G')

Deleting a Tuple
Since tuples are immutable, we cannot delete individual elements of
a tuple. However, we can delete an entire tuple using del statement.
Note-
Printing of
Tuple after
deletion
results in an
Error. #
Deleting a
Tuple

tup = (0, 1, 2, 3, 4)
de

tu

pri

nt(

tu

p)
Python Set Methods

A Set in Python is a
collection of unique
elements which are
unordered and
mutable. Python
provides various
functions to work with
Set.
In this article, we will see a list of all the functions provided by
Python to deal with Sets.

Adding and Removing elements

We can add and remove elements form the set with the help of
the below functions –

• add(): Adds a given element to a set


• clear(): Removes all elements from the set
• discard(): Removes the element from the set
• pop(): Returns and removes a random element from the set
• remove(): Removes the element from the set

Intersection:
Elements
two sets
have in
common.
Union: All
the
elements
from both
sets.
Difference:
Symmetric Elements present
Difference: on from
Elements one set,
bothbut notthat
sets, on the
areother.
not present
on the other

………………………………………………………………..COMPLETED…………………………………
………………………………………………….
Dictionaries in Python
A Python dictionary is a data structure that stores the value in key: value
pairs. Values in a dictionary can be of any data type and can be duplicated,
whereas keys can’t be repeated and must be immutable.
Example: Here, The data is

stored in key:value pairs in

dictionaries, which makes it

easier to find values. d = {1:

'Geeks', 2: 'For', 3: 'Geeks'}

print(d)

Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
• From Python 3.7 Version onward, Python dictionary are Ordered.
• Dictionary keys are case sensitive: the same name but different cases of
Key will be treated distinctly.
• Keys must be immutable: This means keys can be strings, numbers, or
tuples but not lists.
• Keys must be unique: Duplicate keys are not allowed and any duplicate
key will overwrite the previous value.
• Dictionary internally uses Hashing. Hence, operations like search, insert,
delete can be performed in Constant Time.
Table of Content
• Accessing Dictionary Items
• Adding and Updating Dictionary Items
• Removing Dictionary Items
• Iterating Through a Dictionary
• Nested Dictionaries
• Accessing Dictionary Items
• d = { "name": "Alice", 1: "Python", (1, 2): [1,2,4] }

• # Access using key
• print(d["name"])

• # Access using get()
• print([Link]("name"))

• We can access a value from a dictionary by using the key within


square brackets orget()method.

• Alice
• Alice

Output
• Adding and Updating Dictionary Items
• d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}

• # Adding a new key-value pair
• d["age"] = 22

• # Updating an existing value
• d[1] = "Python dict"

• print(d)

• We can add new key-value pairs or update existing keys by using


assignment.

• {1: 'Python dict', 2: 'For', 3: 'Geeks', 'age': 22}

Output
Removing Dictionary Items
We can remove items from dictionary using the following methods:
• del: Removes an item by key.
• pop(): Removes an item by key and returns its value.
• clear(): Empties the dictionary.
• popitem(): Removes and returns the last key-value pair.
Iterating Through a Dictionary
We can iterate over keys
[using keys() method] , values
[using values() method] or
both [using item() method]
with a for loop.
Python Dictionary Methods
Last Updated : 25 Nov, 2024


Python dictionary methods is collection of Python functions that
operates on Dictionary.
Python Dictionary is like a map that is used to store data in the
form of a key: value pair. Python provides various built-in
functions to deal with dictionaries. In this article, we will see a list
of all the functions provided by Python to work with dictionaries.
List of Python Dictionary Methods
Python provides several built-in methods for dictionaries that allow
for efficient manipulation, access, and transformation of dictionary
data. Here’s a list of some important Python dictionary methods:
Functions Descriptions
Name
clear() Removes all
items from the
dictionary
copy() Returns a
shallow copy
of the
dictionary
get() Returns the
value for the
given key
Return the list
with all
items()
dictionary keys
with values
Returns a
view object
keys() that displays
a list of all
the keys in
the dictionary
in order of
insertion
Returns and
removes the
pop()
element with
the given key
Returns and
removes the
popitem()
item that was
last inserted
into the
dictionary.

Dictionary clear() Method


1.

The clear() method in Python is a built-in method that is used to


remove all the elements (key-value pairs) from a dictionary. It
essentially empties the dictionary, leaving it with no key-value
pairs.
my_dict = {'1':

'Geeks', '2': 'For',

'3': 'Geeks'}

my_dict.clear()

print(my_dict)

Output
{}

Dictionary get() Method


2.

In Python, the get() method is a pre-built dictionary function that


enables you to obtain the value linked to a particular key in a
dictionary. It is a secure method to access dictionary values
without causing a KeyError if the key isn’t present.
d = {'Name':

'Ram', 'Age': '19',

'Country': 'India'}

print([Link]('Name'

))

print([Link]('Gender'))

Output
Ra
m
No
ne

Dictionary keys() Method


3.

The keys() method in Python returns a

view object with dictionary keys, allowing

efficient access and iteration. d =

{'Name': 'Ram', 'Age': '19', 'Country':

'India'}

print(list([Link]()))
Output
['Name', 'Age', 'Country']

Dictionary pop() Method


4.

In Python, the pop() method is a pre-existing dictionary method


that removes and retrieves the value linked with a given key from a
dictionary. If the key is not present in the dictionary, you can set an
optional default value to be returned.
d = {'Name':

'Ram', 'Age': '19',

'Country': 'India'}

[Link]('Age')
print(d)

Output
{'Name': 'Ram', 'Country': 'India'}

Sorting Algorithms in Python


Sorting is defined as an arrangement of data in a certain

order. Sorting techniques are used to arrange data(mostly

numerical ) in an ascending or descending order. It is a

method used for the representation of data in a more

comprehensible format.

It is an important area of Computer Science. Sorting Techniques


The different implementations of sorting techniques in Python
are:
• Bubble Sort
• Selection Sort
• Insertion Sort

Sort Python Dictionary by Key or Value – Python

There are two elements in a Python

dictionary-keys and values. You can sort

the dictionary by keys, values, or both. In


this article, we will discuss the methods of

sorting dictionaries by key or value using

Python.

Sorting Dictionary By Key Using sort()


In this example, we will sort the

dictionary by keys and the result

type will be a dictionary. d =

{'ravi': 10, 'rajnish': 9, 'sanjeev':

15}

myKeys

list([Link]

ys())

myKeys.

sort()

# Sorted Dictionary
sd = {i:

d[i] for i in
myKeys}

print(sd)

Output
{'rajnish': 9, 'ravi': 10, 'sanjeev': 15}

File Handling
The key function for

working with files in

Python is the open()

function. The open()

function takes two

parameters; filename,

and mode.

There are four different methods (modes) for opening a file:

"r" - Read - Default

value. Opens a file for

reading, error if the file


does not exist "a" -

Append - Opens a file

for appending, creates

the file if it does not

exist

"w" - Write - Opens a

file for writing,

creates the file if it

does not exist "x" -

Create - Creates the

specified file, returns

an error if the file

exists

In addition you can

specify if the file should

be handled as binary or

text mode "t" - Text -

Default value. Text

mode
"b" - Binary - Binary mode (e.g. images)

Syntax
To open a file for

reading it is enough

to specify the name

of the file: f =

open("[Link]")
The code above is the same as:
f = open("[Link]", "rt")
Because "r" for read, and "t" for text are the default values, you do not need
to specify them.
What is the standard for Python file names?
From PEP8 "Package and Module Names":

Modules should have short, all-lowercase names.

Underscores can be used in the module name if it

improves readability. Python packages should also

have short, all-lowercase names, although the use

of underscores is discouraged.

In Python, files can broadly be categorized into two

types based on their mode of operation: Text Files :

These store data in plain text format. Examples

include .txt files. Binary Files : These store data in

binary format, which is not human-readable.

Note: Make sure the file exists, or else you will get an error.

––––––––––––––––––––––––––––––––––––––complete –––––––––––––––––
––––––––––––––––
Unit 4th

Regular Expression
A RegEx, or Regular Expression, is a sequence
of characters that forms a search pattern.
RegEx can be used to check if a string contains
the specified search pattern.
A regular expression is a special sequence of characters
that helps you match or find other strings or sets of strings,
using a specialized syntax held in a pattern. Regular
expression are popularly known as regex or regexp.

RegEx Module
Python has a built-in package called re, which
can be used to work with Regular Expressions.
Import the re module:
import re
RegEx in Python
When you have imported the re module, you can start using regular
expressions:
ExampleGet your own Python Server
Search the string to see if it starts with "The" and ends with "Spain":
import re

txt = "The rain in Spain"


x=
[Link]("^The.*
Spain$", txt)
RegEx Functions
The re module offers a set of functions that allows us to search a string for a
match:

Func Description
tion
findall Returns a list containing all matches
searchReturns a Match object if there is a match
anywhere in the string
split Returns a list where the string has been split at
each match
sub Replaces one or many matches with a string

Raw Strings
Regular expressions use the backslash character ('\')
to indicate special forms or to allow special characters
to be used without invoking their special meaning.

Metacharacters
Most letters and characters will simply match themselves. However, some
characters are special metacharacters, and don't match themselves. Meta
characters are characters having a special meaning, similar to * in wild card.
Here's a complete list of the metacharacters −
.^$*+?{}[]\|()
Python Exception Handling
Python Exception Handling handles errors
that occur during the execution of a program.
Exception handling allows to respond to the
error, instead of crashing the running
program. It enables you to catch and manage
errors, making your code more robust and
user-friendly.
Python Try Except
The try block lets you test
a block of code for errors.
The except block lets you
handle the error.
The else block lets you execute code when there is no error.
The finally block lets you execute code, regardless of the result of the try-
and except blocks.

Exception Handling
When an error occurs, or exception as we call it, Python will normally stop
and generate an error message.

Exception handling in Python is a mechanism that allows programs to keep


running or exit gracefully when errors occur. It's a fundamental concept in
Python programming.
`
UNIT 5TH

How to Connect Python with SQL Database?


Python is a high-level, general-purpose, and very popular programming
language. We can also use Python with SQL. In this article, we will learn how
to connect SQL with Python using the ‘MySQL Connector Python module.
The diagram given below illustrates how a connection request is sent to
MySQL connector Python.

Connecting MySQL with Python


To create a connection between the MySQL database and Python, the
connect() method of [Link] module is used. We pass the
database details like HostName, username, and the password in the
method call, and then the method returns the connection object.
The following steps are required to connect SQL with Python:
Step 1: Download and Install the free MySQL database from here.
Step 2: After installing the MySQL database, open your Command prompt.
Step 3: Navigate your Command prompt to the location of PIP. Click here to
see, How to install PIP?
Step 4: Now run the commands given below to download and install “MySQL
Connector”. Here, [Link] statement will help you to communicate
with the MySQL database.

Multithreading in Python
This article covers the basics of multithreading in Python programming
language. Just like multiprocessing , multithreading is a way of achieving
multitasking. In multithreading, the concept of threads is used. Let us
first understand the concept of thread in computer architecture.
What is a Process in Python?
In computing, a process is an instance of a computer program that is being
executed. Any process has 3 basic components:
• An executable program.
• The associated data needed by the program (variables, workspace, buffers,
etc.)
• The execution context of the program (State of the process)
An Intro to Python Threading
A thread is an entity within a process that can be scheduled for
execution. Also, it is the smallest unit of processing that can be
performed in an OS (Operating System). In simple words, a
thread is a sequence of such instructions within a program that
can be executed independently of other code.
For simplicity, you can assume that a thread is simply a subset of a
thread contains all this information in a Thread Control Block (TCB) :process! A
• Thread Identifier: Unique id (TID) is assigned to every new thread
• Stack pointer: Points to the thread’s stack in the process. The stack
contains the local variables under the thread’s scope.
• Program counter: a register that stores the address of the instruction
currently being executed by a thread.
• Thread state: can be running, ready, waiting, starting, or done.
• Thread’s register set: registers assigned to thread for computations.
• Parent process Pointer: A pointer to the Process control block (PCB) of the
process that the thread lives on.
• Each thread contains its own register set and local variables (stored in the
stack) .
• All threads of a process share global variables (stored in heap) and the
program code .
Multithreading

Multithre
ading in
Python
Step 1:
Import
Module
Step 2: Create a Thread
Step 3: Start a Thread
Step 4: End the thread Execution

COMPLETE

You might also like