Besant Technologies
Python Notes
What is Python?
Python is a programming language that is interpreted,
object-oriented, and considered high-level too.
Python is one of the easiest yet most useful programming
languages, which is widely used in the software industry.
People use for Competitive Programming, Web
Development, and creating software.
Due to its easiest syntax, it is recommended for beginners
who are new to the software engineering field.
Its demand is growing at a very rapid pace due to its vast
use cases in Modern Technological fields like Data
Science, Machine learning, and Automation Tasks.
History and Versions
o Python laid its foundation in the late 1980s.
o Guido Van Rossum at CWI in Netherland started the
implementation of in December 1989.
o In February 1991, Guido Van Rossum published the
code (labelled version 0.9.0) to alt.sources.
o In 1994, 1.0 was released with new features like lambda,
map, filter, and reduce.
o 2.0 added new features such as list comprehensions,
garbage collection systems.
o On December 3, 2008, 3.0 (also called "Py3K") was
released. It was designed to rectify the fundamental flaw
of the language.
o ABC programming language is said to be the predecessor
of language, which was capable of Exception Handling
and interfacing with the Amoeba Operating System.
o The following programming languages influence :
Besant Technologies
o ABC language.
o Modula-3
Features of :
o Easy to use and Read – Python 's syntax is clear and easy
to read, making it an ideal language for both beginners and
experienced programmers. This simplicity can lead to
faster development and reduce the chances of errors.
o Dynamically Typed - The data types of variables are
determined during run-time. We do not need to specify the
data type of a variable during writing codes.
o High-level - High-level language means human readable
code.
o Compiled and Interpreted - Python code first gets
compiled into bytecode, and then interpreted line by line.
o Garbage Collected - Memory allocation and de-
allocation are automatically managed. Programmers do
not specifically need to manage the memory.
o Purely Object-Oriented - It refers to everything as an
object, including numbers and strings.
o Cross-platform Compatibility - Python can be easily
installed on Windows, macOS, and various Linux
distributions, allowing developers to create software that
runs across different operating systems.
o Rich Standard Library - Python comes with several
standard libraries that provide ready-to-use modules and
functions for various tasks, ranging from web
development and data manipulation to machine
learning and networking.
o Open Source - Python is an open-source, cost-free
programming language. It is utilized pythp
xt
inhere
several sectors and
disciplines as a result.
Besant Technologies
Why Use :
Python is known for its general-purpose nature that makes it
applicable in almost every domain of software development.
makes its presence in every emerging field. It is the fastest-
growing programming language and can develop any
application.
Here, we are specifying application areas where can be
applied.
Besant Technologies
What is Virtual Environment in ?
A Virtual Environment is an isolated space where you can
work on your projects, separately from your system-installed .
You can set up your own libraries and dependencies without
affecting the system .
We will use virtualenv to create a virtual environment in .
Example of creating Virtual Environment
pip install virtualenv
$ virtualenv –-version
$ virtualenv my_env
$ virtualenv -p /usr/bin/3 virtualenv_name
pytpphp
Besant Technologies
Activate a Virtual Environment on Windows
$ cd <envname>
$ Scripts\activate
Once the Virtual Environment was activated, you can install
necessary libraries required.
What is PIP?
PIP is the package manager for . In other words, it is a tool
that allows us to install the packages and dependencies (the
software components required by your code to work without
throwing any errors), which are not automatically provided to
us by the Python's Standard Library.
Pip has become the standard package manager for .
Pip can download, install and manage packages in very
efficiently and in no time!
Variables (A variable name is an identifier that is
used to refer to a value stored in memory)
A variable is the name given to a memory location. A value-
holding variable is also known as an identifier.
Since is an infer language that is smart enough to determine
the type of a variable, we do not need to specify its type in .
Variable names must begin with a letter or an underscore, but
they can be a group of both letters and digits.
The name of the variable should be written in lowercase. Both
Rahul and rahul are distinct variables. python is case sensitive so Rahul
and rahul both not same
Besant Technologies
Variable/ Identifier Naming
o The variable's first character must be an underscore or
alphabet (_).
o Every one of the characters with the exception of the main
person might be a letter set of lower-case(a-z), capitalized
(A-Z), highlight, or digit (0-9).
o White space and special characters (!, @, #, %, etc.) are
not allowed in the identifier name. ^, &, *).
o Names of identifiers are case-sensitive; for instance, my
name, and MyName isn't something very similar.
o Examples of valid identifiers: a123, _n, n_9, etc.
o Examples of invalid identifiers: 1a, n%4, n 9, etc.
Data Types
In , Every value has a datatype, and variables can hold values.
we don't have to characterize the sort of variable while
announcing it. The interpreter binds the value implicitly to its
type.
For Example:
a =6
b=”Hi”
c=3.5
type(a) -> output ‘int’
type(b) -> output ‘str’
type(c) -> output ‘float’
here we did not specify any data type to the variable.
a data type defines the type of data a variable can hold,
such as integers, floating-point numbers, strings, or lists.
Besant Technologies
Standard data types
A variable can contain a variety of values. On the other hand, a
person's id must be stored as an integer, while their name must
be stored as a string.
specify the storage method for each of the standard data types
that provides. The following is a list of the -defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
keywords are reserved words that have
special meaning and cannot be used as identifiers
Besant Technologies
Keywords
Every scripting language has designated words or keywords,
with particular definitions and usage guidelines. is no
exception. The fundamental constituent elements of any
program are keywords.
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
To identity Keywords - help(“keywords”)
Operators
The operator is a symbol that performs a specific operation
between two operands, according to one definition. Operators
serve as the foundation upon which logic is constructed in a
program in a particular programming language. In every
programming language, some operators perform several tasks.
Same as other languages, also has some operators, and these
are given below -
o Arithmetic operators
o Comparison operators
o Assignment Operators
Besant Technologies
o Logical Operators
o Membership Operators
Arthimetic Operator
Arithmetic operators used between two operands for a
particular operation. There are many arithmetic operators. It
includes the exponent (**) operator as well as the + (addition),
- (subtraction), * (multiplication), / (divide), % (reminder), and
// (floor division) operators.
Comparison operator
Comparison operators mainly use for comparison purposes.
Comparison operators compare the values of the two operands
and return a true or false Boolean value in accordance. The
example of comparison operators are ==, !=, <=, >=, >, <.
Assignment Operators
The assignment operators, the right expression's value is
assigned to the left operand. There are some examples of
assignment operators like =, +=, -=, *=, /=, **=, //=.
Logical Operators
The assessment of expressions to make decisions typically uses
logical operators. The examples of logical operators are and, or,
and not. In the case of logical AND, if the first one is 0, it does
not depend upon the second one. In the case of logical OR, if
the first one is 1, it does not depend on the second one. supports
the following logical operators. In the below table, we explain
the works of the logical operators.
Membership Operators pxt here
Besant Technologies
The membership of a value inside a data structure can be
verified using membership operators. The result is true if the
value is in the data structure; otherwise, it returns false. [in, not
in]
1. x = ["Rose", "Lotus"]
2. print(' Is value Present?', "Rose" in x)
3. print(' Is value not Present?', "Riya" not in x)
Conditional Statements
If-else statements
Decision making is the most important aspect of almost all the
programming languages. As the name implies, decision making
allows us to run a particular block of code for a particular
decision. Here, the decisions are made on the validity of the
particular conditions. Condition checking is the backbone of
decision making.
In , decision making is performed by the following statements.
Statement Description
If Statement The if statement is used to test a specific condition. If
the condition is true, a block of code (if-block) will be
executed.
If - else The if-else statement is similar to if statement except
Statement the fact that, it also provides the block of the code for
the false case of the condition to be checked. If the
condition provided in the if statement is false, then the
else statement will be executed.
Besant Technologies
Nested if Nested if statements enable us to use if ? else statement
Statement inside an outer if statement.
The if statement
The if statement is used to test a particular condition and if the
condition is true, it executes a block of code known as if-block.
The condition of if statement can be any valid logical
expression which can be either evaluated to true or false.
Basic Syntax:
X=2
If x%2==0:
Print(‘this is an even number”)
The if-else statement
The if-else statement provides an else block combined with the
if statement which is executed in the false case of the condition.
If the condition is true, then the if-block is executed. Otherwise,
the else-block is executed.
Basic Syntax:
X=2
If x%2==0:
Print(‘this is an even number”)
Else:
Print(‘this is an odd number”)
The elif statement
The elif statement enables us to check multiple conditions and
execute the specific block of statements depending upon the
Besant Technologies
true condition among them. We can have any number of elif
statements in our program depending upon our need. However,
using elif is optional.
The elif statement works like an if-else-if ladder statement in
C. It must be succeeded by an if statement.
Basic Syntax:
x=1
y=2
If x>y:
print(‘x is greater”)
elif x<y:
print(‘Y is greater”
else:
print(“Both Values are equal”)
Loops
Loops allow us to execute a statement or group of statements
multiple times.
In general, statements are executed sequentially: The first
statement in a function is executed first, followed by the
second, and so on. There may be a situation when you need to
execute a block of code several number of times.
The following sorts of loops are available in the
programming language.
Besant Technologies
Sr.No. Name of Loop Type & Description
the loop
1 For loop This type of loop executes a code block
multiple times and abbreviates the code that
manages the loop variable.
2 While Repeats a statement or group of statements
loop while a given condition is TRUE. It tests the
condition before executing the loop body.
3 Nested We can iterate a loop inside another loop.
loops
Loop Control Statements
Statements used to control loops and change the course of
iteration are called control statements. All the objects
produced within the local scope of the loop are deleted when
execution is completed.
provides the following control statements. We will discuss
them later in detail.
Let us quickly go over the definitions of these loop control
statements.
Sr.No. Name of the Description
control
statement
Besant Technologies
1 Break This command terminates the loop's
statement execution and transfers the program's
control to the statement next to the loop.
2 Continue This command skips the current iteration
statement of the loop. The statements following the
continue statement are not executed once
the interpreter reaches the continue
statement.
3 Pass The pass statement is used when a
statement statement is syntactically necessary, but
no code is to be executed.
For Loop:
A for loop is used for iterating over a sequence (that is either a
list, a tuple, a dictionary, a set, or a string).
With the for loop we can execute a set of statements, once for
each item in a list, tuple, set etc.
Example 1:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
Besant Technologies
Looping Through a String:
Even strings are iterable objects, they contain a sequence of
characters
Example 2:
for x in "HelloWorld":
print(x)
The break Statement (For Loop):
With the break statement we can stop the loop before it has
looped through all the items
Example 3:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
The continue Statement (For Loop):
With the continue statement we can stop the current iteration
of the loop, and continue with the next
Example 4:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
Besant Technologies
The range() Function (For Loop):
The range() function returns a sequence of numbers, starting
from 0 by default, and increments by 1 (by default), and ends
at a specified number.
Example 5:
for x in range(6):
print(x)
Nested Loops (For Loop):
A nested loop is a loop inside a loop.
The "outer loop" will be executed one time for each iteration
of the "inner loop"
Example 6:
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
The pass Statement (For Loop):
for loops cannot be empty, but if you for some reason have
a for loop with no content, put in the pass statement to avoid
getting an error.
Example 7:
for x in [0, 1, 2]:
pass
Besant Technologies
While Loop:
While Loop is used to execute a block of statements
repeatedly until a given condition is satisfied. When the
condition becomes false, the line immediately after the loop in
the program is executed.
With the while loop we can execute a set of statements as long
as a condition is true.
Example 1:
i=1
while i < 6:
print(i)
i += 1
The break Statement (while loop):
With the break statement we can stop the loop even if the
while condition is true
Example 2:
i=1
while i < 6:
print(i)
if i == 3:
break
i += 1
The continue Statement (while loop):
With the continue statement we can stop the current iteration,
and continue with the next.
Besant Technologies
Example 3:
i=0
while i < 6:
i += 1
if i == 3:
continue
print(i)
The else Statement (while loop):
With the else statement we can run a block of code once when
the condition no longer is true
Example 4:
i=1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")
List in Python
Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in used to store
collections of data, the other 3 are Tuple, Set, and Dictionary,
all with different qualities and usage.
Lists are created using square brackets.
Besant Technologies
Example 1:
thislist = ["apple", "banana", "cherry"]
print(thislist)
List items are ordered, changeable, and allow duplicate
values.
List items are indexed, the first item has index [0], the second
item has index [1] etc.
Access Items
List items are indexed and you can access them by referring to
the index number.
Example 2:
thislist = ["apple", "banana", "cherry"]
print(thislist[1])
Negative Indexing
Negative indexing means start from the end . -1 refers to the
last item, -2 refers to the second last item etc.
Example 3:
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Besant Technologies
Range of Indexes:
You can specify a range of indexes by specifying where to
start and where to end the range.
When specifying a range, the return value will be a new list
with the specified items.
Example 4:
thislist =
["apple", "banana", "cherry", "orange", "kiwi", "melon", "man
go"]
print(thislist[2:5])
Change Item Value:
To change the value of a specific item, refer to the index
number
Example 5:
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
Besant Technologies
Insert Items:
To insert a new list item, without replacing any of the existing
values, we can use the insert() method.
The insert() method inserts an item at the specified index
Example 6:
thislist = ["apple", "banana", "cherry"]
thislist.insert(2, "watermelon")
print(thislist)
Append Items:
To add an item to the end of the list, use the append() method
Example 7:
thislist = ["apple", "banana", "cherry"]
thislist.append("orange")
print(thislist)
Extend List:
To append elements from another list to the current list, use
the extend() method.
Example 8:
thislist = ["apple", "banana", "cherry"]
tropical = ["mango", "pineapple", "papaya"]
thislist.extend(tropical)
print(thislist)
Besant Technologies
Remove Specified Item:
The remove() method removes the specified item.
Example 9:
thislist = ["apple", "banana", "cherry"]
thislist.remove("banana")
print(thislist)
If there are more than one item with the specified value,
the remove() method removes the first occurrence
Example 10:
thislist = ["apple", "banana", "cherry", "banana", "kiwi"]
thislist.remove("banana")
print(thislist)
Remove Specified Index:
The pop() method removes the specified index.
Example 11:
thislist = ["apple", "banana", "cherry"]
thislist.pop(1)
print(thislist)
If you do not specify the index, the pop() method removes the
last item.
Example 12:
Besant Technologies
thislist = ["apple", "banana", "cherry"]
thislist.pop()
print(thislist)
The del keyword also removes the specified index.
Example 13:
thislist = ["apple", "banana", "cherry"]
del thislist[0]
print(thislist)
List Comprehension:
List comprehension offers a shorter syntax when you want to
create a new list based on the values of an existing list.
Example 14:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
With list comprehension you can do all that with only one line
of code
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
Besant Technologies
newlist = [x for x in fruits if "a" in x]
print(newlist)
Sort List Alphanumerically:
List objects have a sort() method that will sort the list
alphanumerically, ascending, by default
Example 15:
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort()
print(thislist)
For Desceding, use the keyword reverse=True
thislist = ["orange", "mango", "kiwi", "pineapple", "banana"]
thislist.sort(reverse = True)
print(thislist)
Tuples in
Tuples are used to store multiple items in a single variable. A
tuple is a collection which is ordered and unchangeable.
Tuples are written with round brackets. Tuples are
unchangeable, meaning that we cannot change, add or remove
items after the tuple has been created.
Besant Technologies
Example 1:
thistuple = ("apple", "banana", "cherry")
print(thistuple)
Access Tuple Items
You can access tuple items by referring to the index number,
inside square brackets
Example 2:
thistuple = ("apple", "banana", "cherry")
print(thistuple[1])
Negative Indexing
Negative indexing means start from the end. -1 refers to the
last item, -2 refers to the second last item etc.
Example 3:
thistuple = ("apple", "banana", "cherry")
print(thistuple[-1])
Check if Item Exists:
To determine if a specified item is present in a tuple use
the in keyword
Example 4:
Besant Technologies
thistuple = ("apple", "banana", "cherry")
if "apple" in thistuple:
print("Yes, 'apple' is in the fruits tuple")
Loop Through a Tuple:
You can loop through the tuple items by using a for loop.
Example 5:
thistuple = ("apple", "banana", "cherry")
for x in thistuple:
print(x)
Loop Through the Index Numbers:
You can also loop through the tuple items by referring to their
index number.
Use the range() and len() functions to create a suitable
iterable.
Example 6:
thistuple = ("apple", "banana", "cherry")
i=0
while i < len(thistuple):
print(thistuple[i])
i=i+1
Dictionaries in
Dictionaries are used to store data values in key:value pairs.
A dictionary is a collection which is ordered*, changeable and
do not allow duplicates.
Besant Technologies
Example 1:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)
Duplicates Not Allowed
Dictionaries cannot have two items with the same key
Example 2:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)
Dictionary Items - Data Types
The values in dictionary items can be of any data type
Example 3:
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
Besant Technologies
Accessing Items
You can access the items of a dictionary by referring to its key
name, inside square brackets
Example 4:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]
There is also a method called get() that will give you the same
result
x = thisdict.get("model")
Get Keys
The keys() method will return a list of all the keys in the
dictionary.
The list of the keys is a view of the dictionary, meaning that
any changes done to the dictionary will be reflected in the
keys list
x = thisdict.keys()
Example 5:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Besant Technologies
x = car.keys()
print(x) #before the change
car["color"] = "white"
print(x) #after the change
Get Values
The values() method will return a list of all the values in the
dictionary.
The list of the values is a view of the dictionary, meaning that
any changes done to the dictionary will be reflected in the
values list.
x = thisdict.values()
Example 6:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["year"] = 2020
Besant Technologies
print(x) #after the change
Add a new item to the original dictionary, and see that the
values list gets updated as well
Example 7:
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = car.values()
print(x) #before the change
car["color"] = "red"
print(x) #after the change
Check if Key Exists
To determine if a specified key is present in a dictionary use
the in keyword
Example 8:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Besant Technologies
if "model" in thisdict:
print("Yes, 'model' is one of the keys in the thisdict
dictionary")
Change Values
You can change the value of a specific item by referring to its
key name
Example 9:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018
print(thisdict)
Update Dictionary
The update() method will update the dictionary with the items
from the given argument.
The argument must be a dictionary, or an iterable object with
key:value pairs
Example 10:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
Besant Technologies
}
thisdict.update({"year": 2020})
print(thisdict)
Adding Items
Adding an item to the dictionary is done by using a new index
key and assigning a value to it
Example 11:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)
Removing Items
There are several methods to remove items from a dictionary
The pop() method removes the item with the specified key
name
Example 12:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
Besant Technologies
thisdict.pop("model")
print(thisdict)
The popitem() method removes the last inserted item (in
versions before 3.7, a random item is removed instead)
Example 13:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict.popitem()
print(thisdict)
The del keyword removes the item with the specified key
name
Example 14:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
del thisdict["model"]
print(thisdict)
Loop Through a Dictionary
You can loop through a dictionary by using a for loop.
When looping through a dictionary, the return value are
the keys of the dictionary, but there are methods to return
the values as well.
Besant Technologies
Example 15:
Print all key names in the dictionary, one by one
for x in thisdict:
print(x)
Example 16:
Print all values in the dictionary, one by one
for x in thisdict:
print(thisdict[x])
Example 17:
You can also use the values() method to return values of a
dictionary
for x in thisdict.values():
print(x)
Example 18:
You can use the keys() method to return the keys of a
dictionary
for x in thisdict.keys():
print(x)
Example 19:
Loop through both keys and values, by using
the items() method
for x, y in thisdict.items():
print(x, y)
Besant Technologies
Sets in
Sets are used to store multiple items in a single variable.
A set is a collection which is unordered, unchangeable*,
and unindexed.
Set items are unordered, unchangeable, and do not allow
duplicate values.
Unordered means that the items in a set do not have a defined
order.
Set items can appear in a different order every time you use
them, and cannot be referred to by index or key.
Set items are unchangeable, meaning that we cannot change
the items after the set has been created.
Example 1:
thisset = {"apple", "banana", "cherry"}
print(thisset)
Duplicates Not Allowed
Sets cannot have two items with the same value.
Example 2:
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)
Besant Technologies
Note: True and 1 is considered the same value in set. As Same
False and 0 is considered the same value
Example 3:
thisset = {"apple", "banana", "cherry", True, 1, 2, False, 0}
print(thisset)
Access Items
You cannot access items in a set by referring to an index or a
key.
But you can loop through the set items using a for loop, or ask
if a specified value is present in a set, by using
the in keyword.
Example 4:
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
Add Items:
Once a set is created, you cannot change its items, but you can
add new items.
To add one item to a set use the add() method.
Example 5:
Besant Technologies
thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)
To add items from another set into the current set, use
the update() method.
Example 6:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
thisset.update(tropical)
print(thisset)
Remove Item
To remove an item in a set, use the remove(), or
the discard() method.
Note: If the item to remove does not exist, remove() will raise
an error
Example 7:
thisset = {"apple", "banana", "cherry"}
thisset.remove("banana")
print(thisset)
Besant Technologies
Remove "banana" by using the discard() method
Note: If the item to remove does not
exist, discard() will NOT raise an error.
Example 8:
thisset = {"apple", "banana", "cherry"}
thisset.discard("banana")
print(thisset)
Join Sets
There are several ways to join two or more sets in .
The union() and update() methods joins all items from both
sets.
The intersection() method keeps ONLY the duplicates.
The difference() method keeps the items from the first set that
are not in the other set(s).
The symmetric_difference() method keeps all items EXCEPT
the duplicates.
Union
The union() method returns a new set with all items from both
sets.
Example 1:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
Besant Technologies
set3 = set1.union(set2)
print(set3)
You can use the | operator instead of the union() method, and
you will get the same result.
Example 2:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = set1 | set2
print(set3)
Join Multiple Sets
All the joining methods and operators can be used to join
multiple sets.
When using a method, just add more sets in the parentheses,
separated by commas.
Example 3:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}
myset = set1.union(set2, set3, set4)
print(myset)
Besant Technologies
When using the | operator, separate the sets with
more | operators
Example 4:
set1 = {"a", "b", "c"}
set2 = {1, 2, 3}
set3 = {"John", "Elena"}
set4 = {"apple", "bananas", "cherry"}
myset = set1 | set2 | set3 |set4
print(myset)
Update
The update() method inserts all items from one set into
another.
The update() changes the original set, and does not return a
new set.
Example 5:
set1 = {"a", "b","c"}
set2 = {1, 2, 3}
set1.update(set2)
print(set1)
Intersection
Keep ONLY the duplicates
The intersection() method will return a new set, that only
contains the items that are present in both sets.
Besant Technologies
Example 6:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1.intersection(set2)
print(set3)
You can use the & operator instead of
the intersection() method, and you will get the same result.
Example 7:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 & set2
print(set3)
Difference
The difference() method will return a new set that will contain
only the items from the first set that are not present in the
other set.
Example 8:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1.difference(set2)
print(set3)
Besant Technologies
You can use the - operator instead of the difference() method,
and you will get the same result.
Example 9:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 - set2
print(set3)
Difference Update:
The difference_update() method will also keep the items from
the first set that are not in the other set, but it will change the
original set instead of returning a new set.
Example 10:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set1.difference_update(set2)
print(set1)
Symmetric Differences:
The symmetric_difference() method will keep only the
elements that are NOT present in both sets.
Example 11:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
Besant Technologies
set3 = set1.symmetric_difference(set2)
print(set3)
You can use the ^ operator instead of
the symmetric_difference() method, and you will get the same
result.
Example 12:
set1 = {"apple", "banana", "cherry"}
set2 = {"google", "microsoft", "apple"}
set3 = set1 ^ set2
print(set3)
Functions
is a block of code that is designed to perform a specific
1. Function Definition: task. You can call (or invoke) the function
from anywhere in your program
In , a function is defined using the def keyword, followed by
the function name, parameters in parentheses, and a colon.
The function’s code block is indented.
Syntax:
def function_name(parameters):
"""
Optional docstring
"""
# Function body
return result
Example:
Besant Technologies
def greet(name):
"""
Greets the person with the provided
name.
Parameters:
name (str): The name of the person
Returns:
str: Greeting message
"""
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello,
Alice!
2. Function with *args and **Kwargs
*args allows a function to accept any number of positional
arguments. It collects these arguments into a tuple.
**kwargs allows a function to accept any number of
keyword arguments. It collects these arguments into a
dictionary.
Example with *args:
def add_all(*args):
"""
Adds all the provided numbers
together.
Parameters:
*args: Any number of numbers
Besant Technologies
Returns:
int: Sum of all numbers
"""
return sum(args)
print(add_all(1, 2, 3))
# Output: 6
print(add_all(5, 10, 15, 20))
# Output: 50
Example with **kwargs:
def describe_person(**kwargs):
"""
Prints details about a person.
Parameters:
**kwargs: Key-value pairs for details
about the person
Returns:
None
"""
for key, value in kwargs.items():
print(f"{key}: {value}")
describe_person(name="John", age=30,
city="New York")
Output:
vbnet
name: John
Besant Technologies
age: 30
city: New York
3. Scope of Variables
Local Variables: Variables defined inside a function and
only accessible within that function.
Global Variables: Variables defined outside any
function and accessible anywhere in the code.
Example:
global_var = "I am global"
def my_function():
local_var = "I am local"
print(local_var) # Accessible
here
print(global_var) # Accessible
here
my_function()
print(global_var) # Accessible
here
# print(local_var) # Error:
local_var is not accessible here
Explanation:
global_var is defined outside of my_function, so
it’s accessible inside and outside the function.
local_var is defined inside my_function, so it’s
only accessible within that function.
Besant Technologies
4. Docstring
A docstring provides documentation for a function. It is a
string literal that appears right after the function definition.
Example:
def multiply(a, b):
"""
Multiplies two numbers.
Parameters:
a (int or float): The first number
b (int or float): The second number
Returns:
int or float: The product of a and b
"""
return a * b
print(multiply.__doc__)
Output:
Multiplies two numbers.
Parameters:
a (int or float): The first number
b (int or float): The second number
Returns:
int or float: The product of a and b
Explanation:
Besant Technologies
__doc__ is an attribute that contains the function's
docstring.
6. Modules and Standard Modules
Creating and Using Modules:
A module is a file containing code. Modules help organize
code into separate files.
Creating mymodule.py:
# mymodule.py
def greet(name):
return f"Hello, {name}!"
Using mymodule.py in another file:
# main.py
import mymodule
print(mymodule.greet("Alice")) # Output:
Hello, Alice!
Standard Modules:
’s standard library includes modules like math and
datetime.
Examples:
Using math module:
import math
print(math.sqrt(16)) # Output: 4.0
Besant Technologies
print(math.pi) # Output:
3.141592653589793
Using datetime module:
import datetime
now = datetime.datetime.now()
print(now) # Output: Current
date and time
Exception Handling in
Objective
The primary goal of this module is to give you a
comprehensive understanding of how to handle exceptions in ,
how to use built-in exceptions, and how to create your own
custom exception classes. Proper exception handling is crucial
in writing robust and error-free code.
1. What is an Exception?
An exception is an event that occurs during the execution of a
program that disrupts the normal flow of the program's
instructions. In , exceptions are objects that represent errors
that occur at runtime. When an exception occurs, it is said to
be "raised," and if not handled, it will terminate the program.
2. Common Built-in Exceptions
provides several built-in exceptions, including:
Besant Technologies
ZeroDivisionError: Raised when you divide by
zero.
IndexError: Raised when you try to access an index
that is out of range.
KeyError: Raised when a dictionary key is not found.
TypeError: Raised when an operation is applied to an
object of inappropriate type.
ValueError: Raised when a function receives an
argument of the correct type but inappropriate value.
3. Basic Exception Handling
To handle exceptions in , you can use the try, except,
else, and finally blocks.
try block: Code that might raise an exception is placed
in the try block.
except block: Code that handles the exception is
placed in the except block.
else block: Code that runs if no exception occurs is
placed in the else block.
finally block: Code that runs no matter what,
whether an exception occurs or not, is placed in the
finally block.
Example: Handling a Division by Zero Error
try:
numerator = int(input("Enter the
numerator: "))
denominator = int(input("Enter the
denominator: "))
result = numerator / denominator
Besant Technologies
except ZeroDivisionError:
print("Error: Division by zero is not
allowed.")
else:
print(f"Result: {result}")
finally:
print("This will always execute.")
Explanation:
If the denominator is zero, a ZeroDivisionError is
raised, and the except block is executed.
If no exception occurs, the else block is executed.
The finally block is executed regardless of whether
an exception occurs or not.
4. Catching Multiple Exceptions
You can catch multiple exceptions by specifying them as a
tuple in the except block.
Example: Handling Multiple Exceptions
try:
value = int(input("Enter an integer:
"))
result = 10 / value
except (ValueError, ZeroDivisionError) as
e:
print(f"Error occurred: {e}")
Explanation:
If the user inputs a non-integer value, a ValueError is
raised.
Besant Technologies
If the user inputs zero, a ZeroDivisionError is
raised.
The as e syntax allows you to capture the exception
object and print the error message.
5. Raising Exceptions
You can manually raise exceptions using the raise
keyword.
Example: Manually Raising an Exception
def check_age(age):
if age < 18:
raise ValueError("Age must be 18
or older.")
return "Access granted."
try:
print(check_age(16))
except ValueError as e:
print(e)
Explanation:
The check_age function raises a ValueError if the
age is less than 18.
The exception is caught in the except block and the
error message is printed.
6. Creating Custom Exception Classes
Besant Technologies
You can create your own exception classes by inheriting from
the Exception class or any other built-in exception class.
Example: Custom Exception Class
class CustomError(Exception):
def __init__(self, message):
self.message = message
def check_value(value):
if value < 0:
raise CustomError("Negative
values are not allowed.")
return value
try:
print(check_value(-5))
except CustomError as e:
print(e)
Explanation:
CustomError is a custom exception class that inherits
from the Exception class.
The check_value function raises a CustomError if
the value is negative.
The exception is caught in the except block and the
custom error message is printed.
Besant Technologies
File Handling in
File handling is an essential concept in programming that
allows you to create, read, write, update, and delete files using
a programming language. In , file handling is straightforward
and provides functions to manipulate files in various ways.
Files are used to store data permanently, making it possible to
save data for future use, share it between different programs,
or process large datasets that can't be stored in memory.
File Modes
When opening a file in , you must specify the mode, which
determines how the file will be handled. The common modes
are:
r (Read): Opens the file for reading. If the file does not
exist, it raises an error.
w (Write): Opens the file for writing. If the file already
exists, it truncates it (removes all content). If the file
does not exist, it creates a new file.
a (Append): Opens the file for appending. If the file
exists, new data is added at the end of the file without
truncating it. If the file does not exist, it creates a new
file.
x (Create): Creates a new file. If the file already exists, it
raises an error.
b (Binary): Used with other modes to open files in
binary mode (e.g., rb, wb).
t (Text): Used with other modes to open files in text
mode (default).
Besant Technologies
File Handling Operations
1. Creating a File
You can create a new file using the open() function
with the w or x mode.
# Creating a file using write mode
file = open("example.txt", "w")
file.write("Hello, world!")
file.close()
# Creating a file using create mode
try:
file = open("example2.txt", "x")
file.write("This is a new file.")
file.close()
except FileExistsError:
print("File already exists.")
2. Reading from a File
You can read the content of a file using the read(),
readline(), or readlines() functions.
# Reading the entire file
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
# Reading line by line
file = open("example.txt", "r")
for line in file:
print(line.strip())
Besant Technologies
file.close()
# Reading a single line
file = open("example.txt", "r")
line = file.readline()
print(line)
file.close()
3. Writing to a File
You can write data to a file using the write() or
writelines() functions.
# Writing to a file
file = open("example.txt", "w")
file.write("This is new content.")
file.close()
# Writing multiple lines
lines = ["Line 1\n", "Line 2\n", "Line
3\n"]
file = open("example.txt", "w")
file.writelines(lines)
file.close()
4. Appending to a File
You can add content to the end of a file without deleting
the existing content using the a mode.
# Appending to a file
file = open("example.txt", "a")
file.write("Appending this line.\n")
file.close()
5. Deleting a File
Besant Technologies
You can delete a file using the os.remove() function
from the os module.
import os
# Deleting a file
if os.path.exists("example.txt"):
os.remove("example.txt")
else:
print("The file does not exist.")
6. Updating a File
Updating a file involves reading its content, making
modifications, and writing the modified content back to
the file.
# Updating a file
file = open("example.txt", "r")
content = file.readlines()
file.close()
content[1] = "This is the updated
second line.\n"
file = open("example.txt", "w")
file.writelines(content)
file.close()
Handle Exceptions: Use try-except blocks to handle
potential errors, such as trying to read a non-existent file
or writing to a file with insufficient permissions.
Work with Binary Files: When working with non-text
files like images or executables, open them in binary
mode using rb, wb, etc.
Besant Technologies
Object-Oriented Programming (OOP) in
Object-Oriented Programming (OOP) is a programming
paradigm that uses objects and classes to organize and
structure code. It allows you to model real-world entities
using objects, making your code more modular, reusable, and
easier to maintain.
Key Concepts of OOP
1. Class: A blueprint for creating objects. It defines a set of
attributes and methods that the created objects will
have.
2. Object: An instance of a class. It contains data
(attributes) and behaviors (methods).
3. Constructor: A special method in a class that is
automatically called when an object is created. It is used
to initialize the object's attributes.
4. Polymorphism: The ability to present the same interface
for different data types. In , polymorphism allows you to
define methods in the child class with the same name as
in the parent class.
5. Encapsulation: The bundling of data and methods that
operate on that data within one unit, such as a class. It
restricts access to some of the object's components.
6. Abstraction: The process of hiding the complex
implementation details and showing only the essential
features of an object.
Besant Technologies
7. Inheritance: The ability of a class to inherit attributes
and methods from another class, allowing for code
reuse.
Understanding Pre-OOP Concepts
Before diving into OOP concepts, it's essential to understand
the following:
1. Constructor
A constructor is a special method used to initialize the
attributes of an object when the object is created. In , the
__init__ method is the constructor.
Example:
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
my_car = Car("Toyota", "Corolla")
print(my_car.brand) # Output: Toyota
print(my_car.model) # Output: Corolla
2. Self
In , self is a reference to the current instance of the class. It is
used to access variables that belong to the class. It is the first
parameter of any method in the class and is used to access the
attributes and methods of the class within that method.
Besant Technologies
Key Points About self:
1. Self is not a keyword: self is just a convention. You can
name it anything, but using self is a widely accepted
standard.
2. Self is the first argument of instance methods: It must
be the first parameter of any method in the class.
3. Access instance variables: You can use self to access
variables and methods associated with the object.
4. Self differentiates between instance and local variables:
Inside a method, self.zvariable_name refers to instance
variables, while variable_name refers to local variables.
Example 1: Using self to Access Instance Variables
class Person:
def __init__(self, name, age):
self.name = name # self.name is
an instance variable
self.age = age # self.age is
an instance variable
def display(self):
print(f"Name: {self.name}, Age:
{self.age}")
# Creating an instance of Person
person1 = Person("Alice", 30)
person1.display()
3. Private Class
In , you can define private attributes or methods by prefixing
their names with an underscore (_). Private attributes or
Besant Technologies
methods are not meant to be accessed directly from outside
the class.
Example:
class MyClass:
def __init__(self):
self._private_variable = 42 #
This is a private attribute
def _private_method(self):
print("This is a private method")
obj = MyClass()
print(obj._private_variable) # Accessing
private variable (not recommended)
obj._private_method() # Accessing
private method (not recommended)
4. Public Class
Public attributes and methods are accessible from outside the
class. By default, all attributes and methods in are public
unless explicitly defined as private.
Example:
class MyClass:
def __init__(self):
self.public_variable = 42 # This
is a public attribute
def public_method(self):
print("This is a public method")
Besant Technologies
obj = MyClass()
print(obj.public_variable) # Accessing
public variable
obj.public_method() # Accessing
public method
5. Superclass
A superclass is the class from which other classes (subclasses)
inherit attributes and methods. The subclass can override or
extend the functionality of the superclass.
Example:
class Animal:
def sound(self):
print("Some generic animal
sound")
class Dog(Animal):
def sound(self):
super().sound()
print("Bark")
dog = Dog()
dog.sound() # Output: Bark (overrides
the superclass method)
6. Method Overriding
Method overriding occurs when a subclass provides a specific
implementation for a method that is already defined in its
superclass. The subclass's method is called instead of the
superclass's method.
Example:
Besant Technologies
class Animal:
def sound(self):
print("Some generic animal
sound")
class Cat(Animal):
def sound(self):
print("Meow")
cat = Cat()
cat.sound() # Output: Meow (overrides
the superclass method)
Diving into OOP Concepts
1. Class and Object
A class is a blueprint for creating objects. An object is an
instance of a class.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is
{self.name} and I am {self.age} years
old.")
# Creating an object of the Person class
person1 = Person("Alice", 30)
Besant Technologies
person1.greet() # Output: Hello, my name
is Alice and I am 30 years old.
2. Constructor
As discussed earlier, a constructor initializes an object's
attributes when it is created.
Example:
class Book:
def __init__(self, title, author):
self.title = title
self.author = author
book1 = Book("1984", "George Orwell")
print(book1.title) # Output: 1984
print(book1.author) # Output: George
Orwell
3. Polymorphism
Polymorphism allows objects of different classes to be treated
as objects of a common superclass. It enables the same
method to behave differently based on the object it is called
on.
Types of Polymorphism:
same function name has in subclass and also has in super class
Method Overriding: As shown earlier, a subclass can
provide a specific implementation for a method already
defined in its superclass.
Method Overloading: does not support method
overloading by default. However, you can achieve
same function name with multiple function time but different parameter is methodoverloading
Besant Technologies
similar functionality using default arguments or variable-
length arguments.
Example of Polymorphism:
class Bird:
def sound(self):
print("Some bird sound")
class Parrot(Bird):
def sound(self):
print("Squawk")
class Sparrow(Bird):
def sound(self):
print("Chirp")
# Polymorphism in action
def make_sound(bird):
bird.sound()
parrot = Parrot()
sparrow = Sparrow()
make_sound(parrot) # Output: Squawk
make_sound(sparrow) # Output: Chirp
4. Encapsulation
Encapsulation is the practice of bundling data (attributes) and
methods that operate on that data into a single unit (class). It
also involves restricting access to certain components, which
is done by making attributes or methods private.
Besant Technologies
Example:
class BankAccount:
def __init__(self, balance):
self._balance = balance #
Private attribute
def deposit(self, amount):
self._balance += amount
def withdraw(self, amount):
if amount <= self._balance:
self._balance -= amount
else:
print("Insufficient funds")
def get_balance(self):
return self._balance
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance()) # Output:
1300
5. Abstraction
Abstraction is the concept of hiding the complex
implementation details and exposing only the essential
features to the user. It can be achieved using abstract classes
or interfaces, but does not have built-in support for abstract
classes as in other languages. However, the abc module can
be used to create abstract classes.
Besant Technologies
Example:
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass
class Dog(Animal):
def sound(self):
print("Bark")
class Cat(Animal):
def sound(self):
print("Meow")
dog = Dog()
cat = Cat()
dog.sound() # Output: Bark
cat.sound() # Output: Meow
6. Inheritance
Inheritance allows a class (subclass) to inherit attributes and
methods from another class (superclass). It promotes code
reuse and establishes a relationship between classes.
Types of Inheritance:
Single Inheritance: A subclass inherits from a single
superclass.
Besant Technologies
Multiple Inheritance: A subclass inherits from more
than one superclass.
Multilevel Inheritance: A subclass inherits from another
subclass, forming a chain of inheritance.
Hierarchical Inheritance: Multiple subclasses inherit
from a single superclass.
Hybrid Inheritance: A combination of two or more types
of inheritance.
1. Single Inheritance
Single inheritance involves one class inheriting from a single
superclass. This is the simplest form of inheritance.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
dog = Dog()
dog.speak() # Inherited method from
Animal class
dog.bark() # Method of Dog class
2. Multiple Inheritance
Multiple inheritance allows a class to inherit from more than
one superclass. This means that the subclass has access to the
attributes and methods of all its superclasses.
Besant Technologies
Example:
class Engine:
def start(self):
print("Engine starts")
class Wheels:
def rotate(self):
print("Wheels rotate")
class Car(Engine, Wheels):
def drive(self):
print("Car is driving")
my_car = Car()
my_car.start() # Method from Engine
class
my_car.rotate() # Method from Wheels
class
my_car.drive() # Method from Car class
3. Multilevel Inheritance
Multilevel inheritance occurs when a subclass inherits from
another subclass, forming a chain of inheritance.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Mammal(Animal):
def walk(self):
print("Mammal walks")
Besant Technologies
class Dog(Mammal):
def bark(self):
print("Dog barks")
dog = Dog()
dog.speak() # Inherited from Animal
class
dog.walk() # Inherited from Mammal
class
dog.bark() # Method of Dog class
4. Hierarchical Inheritance
Hierarchical inheritance involves multiple subclasses
inheriting from a single superclass. Each subclass will have
access to the methods of the superclass.
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def bark(self):
print("Dog barks")
class Cat(Animal):
def meow(self):
print("Cat meows")
dog = Dog()
cat = Cat()
Besant Technologies
dog.speak() # Inherited from Animal
class
dog.bark() # Method of Dog class
cat.speak() # Inherited from Animal
class
cat.meow() # Method of Cat class
5. Hybrid Inheritance
Hybrid inheritance is a combination of two or more types of
inheritance. supports hybrid inheritance but does not support
hybrid inheritance directly due to the diamond problem.
However, it can be managed using the Method Resolution
Order (MRO).
Example:
class Animal:
def speak(self):
print("Animal speaks")
class Mammal(Animal):
def walk(self):
print("Mammal walks")
class Bird(Animal):
def fly(self):
print("Bird flies")
class Bat(Mammal, Bird):
def hang(self):
print("Bat hangs upside down")
Besant Technologies
bat = Bat()
bat.speak() # Inherited from Animal
class
bat.walk() # Inherited from Mammal
class
bat.fly() # Inherited from Bird class
bat.hang() # Method of Bat class
Iterators, Generators, and Decorators in
This module covers three important concepts in : Iterators,
Generators, and Decorators. Understanding these will enhance your
ability to write efficient, readable, and reusable code.
Iterators allow you to traverse through all elements of a collection one
by one.
Generators allow you to create iterators in a more concise and memory-
efficient way using yield.
Decorators enable you to extend the behavior of functions or methods
without modifying their code directly.
1. Iterators in
What is an Iterator?
An iterator is an object that allows you to traverse through all the
elements of a collection (like lists, tuples, or dictionaries) without
needing to maintain the index position. In , an iterator implements two
methods: __iter__() and __next__().
How Iterators Work:
__iter__(): This method initializes the iterator. It returns the iterator
object itself and is implicitly called at the start of loops.
__next__(): This method returns the next item from the sequence. It
raises a StopIteration exception when no more items are available.
Example of an Iterator:
Besant Technologies
class MyIterator:
def __init__(self, numbers):
self.numbers = numbers
self.index = 0
def __iter__(self):
return self
def __next__(self):
if self.index < len(self.numbers):
result = self.numbers[self.index]
self.index += 1
return result
else:
raise StopIteration
# Creating an instance of MyIterator
my_iter = MyIterator([1, 2, 3, 4])
# Using the iterator
for num in my_iter:
print(num)
Output:
1
2
3
4
Built-in Iterator Functions:
iter(): Returns an iterator object.
next(): Returns the next item from the iterator.
Why Use iter()?
Efficiency: Iterators don’t load the entire iterable object into
memory, so they're efficient for handling large data sets.
Customization: You can create customized iteration behavior
for your objects.
Lazy Evaluation: Iterators support lazy evaluation, where
values are computed on the fly as you iterate over them, rather
than storing the entire sequence in memory.
Besant Technologies
Example:
numbers = [10, 20, 30]
iterator = iter(numbers)
print(next(iterator)) # Output: 10
print(next(iterator)) # Output: 20
print(next(iterator)) # Output: 30
# print(next(iterator)) # Raises StopIteration
Exception
Practical Use Case: Reading Large Files
# Reading a large file using iter()
with open('large_file.txt', 'r') as file:
for line in iter(file.readline, ''):
print(line.strip())
2. Generators in
What is a Generator?
A generator is a special type of iterator that can be iterated over only
once. It generates values on the fly and doesn't store them in memory.
Generators are defined using functions and the yield statement.
Key Points:
yield: Used to produce a value and pause the generator. The state of
the generator is saved, so it can resume where it left off when next() is
called again.
Memory Efficient: Generators are more memory efficient than lists
because they do not store all values in memory.
Example of a Generator:
def my_generator():
yield 1
yield 2 You're sitting in a restaurant and order a full meal.
But instead of bringing everything at once,
yield 3 the servant brings one item at a time: 1st time rice
,2nd time samabr, 3 time curd, 4 time desert (like lazy)
# Using the generator
gen = my_generator()
print(next(gen)) # Output: 1
Besant Technologies
print(next(gen)) # Output: 2
print(next(gen)) # Output: 3
# print(next(gen)) # Raises StopIteration Exception
Example 2:
def fibanocci(n):
a,b =0,1
for _ in range(n):
yield a
a,b = b,a+b
for i in fibanocci(90):
print(i)
3. Decorators in
What is a Decorator?
A decorator is a function that takes another function and extends its
behavior without explicitly modifying it. Decorators allow you to add
functionality to existing code in a clean and maintainable way.
How Decorators Work:
Function as an argument: Decorators take a function as input and return
a new function with added functionality.
Wrapper function: This inner function is where the additional behavior
is implemented.
Example of a Simple Decorator:
def my_decorator(func):
def wrapper():
print("Something is happening before the function is
called.")
func()
print("Something is happening after the function is
called.")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
# Calling the decorated function
say_hello()
Besant Technologies
Output:
Something is happening before the function is called.
Hello!
Something is happening after the function is called.
def authentication_decorater(func):
def wrapper():
username=input("Enter Username: ")
password =input("Enter Password: ")
if username=='admin' and password=='Password':
return func()
else:
print("invalid credentials")
return wrapper
@authentication_decorater
def user_authentication():
print("Welcome, authenticated User!")
Understanding the datetime Module
The datetime module provides classes for manipulating dates and
times. It consists of several classes, but we'll focus on the following:
datetime: Combines date and time.
date: Handles date (year, month, day).
time: Handles time (hour, minute, second).
timedelta: Represents the difference between two dates or times.
datetime.now() retrieves the current date and time.
strftime(format) and strptime(date_string, format) help in formatting and
parsing dates and times.
timedelta is used for date and time arithmetic.
time.sleep(seconds) pauses execution, which can be useful in tasks that require delays
or timed operations.
Key Functions and Methods
1. Getting the Current Date and Time
datetime.now(): Returns the current local date and time.
from datetime import datetime
# Get the current date and time
now = datetime.now()
print("Current date and time:", now)
Besant Technologies
2. Formatting Dates and Times
strftime(format): Formats datetime into a readable string.
from datetime import datetime
now = datetime.now()
formatted_now = now.strftime("%Y-%m-%d %H:%M:%S")
print("Formatted date and time:", formatted_now)4
# %Y - Year - YYYY
# %y - year - YY
# %m - Month
# %B - Month Name - Full Month Name - December
# %h - Shorth Month Name - Dec
# %d - day
# %D - mm-dd-yy -> 08/12/24
# %H - Hour
# %M - Minutes
# %S - Seconds
3. Parsing Strings into Dates
strptime(date_string, format): Parses a string into a datetime object.
from datetime import datetime
date_string = "2024-08-25 14:30:00"
date_format = "%Y-%m-%d %H:%M:%S"
parsed_date = datetime.strptime(date_string, date_format)
print("Parsed date and time:", parsed_date)
4. Manipulating Dates and Times
timedelta(days=number): Represents a duration. Used to add or subtract time.
from datetime import datetime, timedelta
now = datetime.now()
future_date = now + timedelta(days=5)
past_date = now - timedelta(days=5)
print("Date 5 days from now:", future_date)
print("Date 5 days ago:", past_date)
Combining datetime with time.sleep
time.sleep(seconds): Pauses the execution of the program for the specified number of
seconds.
Example: Using time.sleep with datetime
Besant Technologies
from datetime import datetime
import time
print("Start time:", datetime.now())
# Wait for 5 seconds
time.sleep(5)
print("End time:", datetime.now())
In this example:
We print the current time, wait for 5 seconds, and then print the time again to show the
elapsed duration.
Complete Examples
Example 1: Countdown Timer
from datetime import datetime, timedelta
import time
def countdown_timer(seconds):
w
while datetime.now() < end_time:
remaining = end_time - datetime.now()
print(f"Time remaining: {remaining}", end="\r")
time.sleep(1) # Sleep for 1 second
print("Time's up!")
# Run the countdown timer for 10 seconds
countdown_timer(10)
In this example:
We calculate the end time based on the current time plus a duration.
We update the remaining time every second using a loop and time.sleep.
Example 2: Logging Execution Time
from datetime import datetime
import time
def task():
print("Task started at:", datetime.now())
time.sleep(3) # Simulate a task taking 3 seconds
print("Task ended at:", datetime.now())
task()
Besant Technologies
Advanced Data Structures/Collections in
What are Advanced Data Structures?
Advanced data structures are specialized collections that provide
efficient solutions for common problems related to data management.
These structures are built on top of basic collections (like lists, tuples,
sets, and dictionaries) but offer more features, optimizations, and
convenience. They are designed to handle specific use cases that are
not efficiently managed by basic data structures.
Why Use Advanced Data Structures?
Efficiency: They offer optimized performance for specific tasks,
reducing time complexity.
Convenience: Provide built-in methods and attributes that
simplify complex tasks.
Functionality: Enable solutions to problems that are difficult or
cumbersome with basic structures.
Scalability: Handle large datasets more effectively, making
them suitable for real-world applications.
Real Use Cases:
Deque: Managing a queue of tasks where you need to add or
remove elements from both ends.
namedtuple: Storing and accessing data with named fields like
a database record or a row from a CSV file.
ChainMap: Managing multiple dictionaries in a way that
allows you to search through them as a single mapping.
Counter: Counting occurrences of elements in a collection,
useful in scenarios like text analysis.
OrderedDict: Maintaining the order of items as they are
inserted, important in cases where order matters, like JSON
parsing.
DefaultDict: Automatically handling missing keys with a
default value, useful in data aggregation tasks.
Besant Technologies
Detailed Explanations and Examples:
1. Deque (Double-Ended Queue)
Explanation:
o A deque is a generalization of stacks and queues. It
supports adding and removing elements from either end
with O (1) time complexity.
o Unlike a list, deque is optimized for operations at both
ends, making it suitable for tasks like implementing
queues and managing a sequence of undo operations.
Example:
from collections import deque
# Create a deque with initial elements
dq = deque(['a', 'b', 'c'])
# Add elements to the right end
dq.append('d')
print(dq) # Output: deque(['a', 'b', 'c', 'd'])
# Add elements to the left end
dq.appendleft('z')
print(dq) # Output: deque(['z', 'a', 'b', 'c', 'd'])
# Remove elements from the right end
dq.pop()
print(dq) # Output: deque(['z', 'a', 'b', 'c'])
# Remove elements from the left end
dq.popleft()
print(dq) # Output: deque(['a', 'b', 'c'])
2. namedtuple
Explanation:
o A namedtuple is a lightweight, immutable object that
allows you to access its elements by name rather than by
index. It's useful when you need to create objects with
fields but don’t need the full functionality of a class.
Example:
from collections import namedtuple
# Create a namedtuple for a point in 2D space
Point = namedtuple('Point', ['x', 'y'])
# Instantiate a Point object
Besant Technologies
p = Point(2, 3)
# Access fields by name
print(p.x) # Output: 2
print(p.y) # Output: 3
# Namedtuples are immutable
# p.x = 5 # This would raise an AttributeError
3. ChainMap
Explanation:
o ChainMap is a dictionary-like class that groups multiple
dictionaries into a single view. It's useful when you want to treat
multiple mappings as a single unit, for example, combining local,
global, and built-in variable scopes.
Example:
from collections import ChainMap
# Create two dictionaries
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
# Combine them using ChainMap
combined = ChainMap(dict1, dict2)
# Access elements
print(combined['a']) # Output: 1
print(combined['b']) # Output: 2 (from the first dict in the chain)
print(combined['c']) # Output: 4
4. Counter
Explanation:
o Counter is a subclass of dict that is specifically designed for counting
hashable objects. It’s ideal for tasks like counting occurrences in a collection
or frequency analysis.
Example:
from collections import Counter
# Create a counter from a list of elements
cnt = Counter(['a', 'b', 'c', 'a', 'b', 'b'])
# Get the count of an element
print(cnt['b']) # Output: 3
# Get the most common elements
print(cnt.most_common(2)) # Output: [('b', 3), ('a', 2)]
Besant Technologies
5. OrderedDict
Explanation:
o An OrderedDict is a dictionary subclass that remembers
the order in which entries were added. This is useful when
the order of items is important, such as maintaining the
order of configurations or JSON fields.
Example:
from collections import OrderedDict
# Create an ordered dictionary
od = OrderedDict()
od['apple'] = 1
od['banana'] = 5
od['cherry'] = 3
# Print the dictionary
for key, value in od.items():
print(key, value)
# Output:
# apple 1
# banana 2
# cherry 3
6. DefaultDict
Explanation:
o A DefaultDict is a subclass of dict that returns a default value if the
requested key is not found. It’s particularly useful in cases like
counting or grouping where you want to avoid key errors.
Example:
from collections import defaultdict
# Create a defaultdict with default value as list
dd = defaultdict(list)
# Add some values
dd['fruits'].append('apple')
dd['fruits'].append('banana')
dd['vegetables'].append('carrot')
# Accessing a missing key returns the default value (an empty list)
print(dd['fruits']) # Output: ['apple', 'banana']
print(dd['vegetables']) # Output: ['carrot']
print(dd['meats']) # Output: []
Besant Technologies
Conclusion:
Advanced data structures in , such as Deque, namedtuple, ChainMap,
Counter, OrderedDict, and DefaultDict, provide specialized functionalities
that make them powerful tools for efficiently managing data in various
scenarios. Understanding when and how to use these structures will greatly
enhance your ability to write efficient, clean, and maintainable code.
MySQL with : A Comprehensive Guide
Objective:
In this module, you will learn how to interact with MySQL databases using . You'll
understand how to execute SQL statements, perform CRUD (Create, Read, Update, Delete)
operations, and manage database connections using .
1. SQL Statements & Operations
SQL (Structured Query Language) is the standard language used to communicate with
relational databases like MySQL. The basic SQL operations you'll need to perform in
include:
Create: Inserting new records into the database.
Read: Querying the database to retrieve existing records.
Update: Modifying existing records in the database.
Delete: Removing records from the database.
2. CRUD Operations in
CRUD stands for Create, Read, Update, and Delete—the four basic functions that can be
performed on a database.
2.1. Create (Insert)
The CREATE operation is used to add new records to a database table.
Example:
import mysql.connector
# Establishing the connection to the database
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
Besant Technologies
password="yourpassword",
database="yourdatabase"
)
# Creating a cursor object
cursor = connection.cursor()
# SQL statement to insert a record
sql_insert = "INSERT INTO employees (name, position, salary) VALUES (%s,
%s, %s)"
values = ("John Doe", "Software Engineer", 75000)
# Executing the SQL statement
cursor.execute(sql_insert, values)
# Commit the changes to the database
connection.commit()
print(cursor.rowcount, "record inserted.")
# Closing the connection
connection.close()
2.2. Read (Select)
The READ operation involves querying the database to retrieve data.
Example:
# Establishing the connection
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Creating a cursor object
cursor = connection.cursor()
# SQL statement to select records
sql_select = "SELECT * FROM employees"
# Executing the SQL statement
cursor.execute(sql_select)
# Fetching all records
results = cursor.fetchall()
# Displaying the records
for row in results:
print(row)
# Closing the connection
connection.close()
2.3. Update
Besant Technologies
The UPDATE operation modifies existing records in the database.
Example:
# Establishing the connection
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Creating a cursor object
cursor = connection.cursor()
# SQL statement to update a record
sql_update = "UPDATE employees SET salary = %s WHERE name = %s"
values = (80000, "John Doe")
# Executing the SQL statement
cursor.execute(sql_update, values)
# Commit the changes to the database
connection.commit()
print(cursor.rowcount, "record(s) updated.")
# Closing the connection
connection.close()
2.4. Delete
The DELETE operation removes records from the database.
Example:
# Establishing the connection
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Creating a cursor object
cursor = connection.cursor()
# SQL statement to delete a record
sql_delete = "DELETE FROM employees WHERE name = %s"
value = ("John Doe",)
# Executing the SQL statement
cursor.execute(sql_delete, value)
# Commit the changes to the database
Besant Technologies
connection.commit()
print(cursor.rowcount, "record(s) deleted.")
# Closing the connection
connection.close()
3. -MySQL Connector Installation
To interact with MySQL databases in , you need to install the mysql-connector-python
package.
Installation Command:
pip install mysql-connector-python
This package provides a API for connecting to MySQL, executing SQL queries, and
managing database transactions.
4. with CRUD Operations
makes it straightforward to perform CRUD operations on MySQL databases. By using the
mysql-connector- package, you can connect to the database, execute SQL queries, and
commit changes.
4.1. Establishing a Connection
Before you can perform any CRUD operations, you must establish a connection to the
MySQL database.
Example:
import mysql.connector
# Establishing the connection
connection = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Check if the connection was successful
if connection.is_connected():
print("Connected to MySQL database")
# Closing the connection
connection.close()
4.2. Creating a Cursor
A cursor is an object that allows you to execute SQL queries and retrieve data.
Besant Technologies
Example:
cursor = connection.cursor()
4.3. Committing Transactions
After executing any operation that modifies the database (like INSERT, UPDATE,
DELETE), you need to commit the transaction to save the changes.
Example:
connection.commit()
4.4. Handling Errors in MySQL with
When interacting with a MySQL database using , errors can occur due to various reasons like
connection issues, SQL syntax errors, or attempting to perform operations on non-existent
tables or records. 's try-except block can be used to handle these errors gracefully.
Example: Handling Errors During Database Operations
import mysql.connector
from mysql.connector import Error
try:
# Establish a database +connection
connection = mysql.connector.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
# Check if the connection is successful
if connection.is_connected():
cursor = connection.cursor()
# SQL query to insert data into a table
sql_insert = """INSERT INTO employees (id, name, salary) VALUES
(%s, %s, %s)"""
values = (1, 'John Doe', 75000)
# Execute the query
cursor.execute(sql_insert, values)
# Commit the transaction
connection.commit()
print("Record inserted successfully into employees table")
except mysql.connector.Error as error:
print(f"Failed to insert record into MySQL table: {error}")
finally:
Besant Technologies
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
Explanation:
1. try: The code block under try is executed. If any error occurs, the control is passed to the
except block.
2. except: Catches the mysql.connector.Error and prints an error message. This prevents
the program from crashing and allows for more graceful error handling.
3. finally: This block is executed no matter what, whether an error occurred or not. It is often
used to close the database connection to ensure there are no open connections.
5. with CRUD Operations
Now, let's explore how to perform the CRUD operations using .
5.1. Create (Insert Operation)
import mysql.connector
# Establish a database connection
connection = mysql.connector.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
# Create a cursor object
cursor = connection.cursor()
# SQL query to insert data
sql_insert = "INSERT INTO employees (id, name, salary) VALUES (%s, %s, %s)"
values = (1, 'Alice', 50000)
# Execute the query and commit the transaction
cursor.execute(sql_insert, values)
connection.commit()
print("Record inserted successfully.")
# Close the connection
cursor.close()
connection.close()
5.2. Read (Select Operation)
import mysql.connector
# Establish a database connection
connection = mysql.connector.connect(
host='localhost',
Besant Technologies
database='your_database',
user='your_username',
password='your_password'
)
# Create a cursor object
cursor = connection.cursor()
# SQL query to read data
sql_select = "SELECT * FROM employees"
# Execute the query
cursor.execute(sql_select)
# Fetch all the records
records = cursor.fetchall()
for row in records:
print(f"ID: {row[0]}, Name: {row[1]}, Salary: {row[2]}")
# Close the connection
cursor.close()
connection.close()
5.3. Update Operation
import mysql.connector
# Establish a database connection
connection = mysql.connector.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
# Create a cursor object
cursor = connection.cursor()
# SQL query to update data
sql_update = "UPDATE employees SET salary = %s WHERE id = %s"
values = (60000, 1)
# Execute the query and commit the transaction
cursor.execute(sql_update, values)
connection.commit()
print(f"{cursor.rowcount} record(s) affected.")
# Close the connection
cursor.close()
connection.close()
5.4. Delete Operation
import mysql.connector
# Establish a database connection
Besant Technologies
connection = mysql.connector.connect(
host='localhost',
database='your_database',
user='your_username',
password='your_password'
)
# Create a cursor object
cursor = connection.cursor()
# SQL query to delete data
sql_delete = "DELETE FROM employees WHERE id = %s"
values = (1,)
# Execute the query and commit the transaction
cursor.execute(sql_delete, values)
connection.commit()
print(f"{cursor.rowcount} record(s) deleted.")
# Close the connection
cursor.close()
connection.close()
6. Commit
The commit() function is used to save all the changes made to the database during a
transaction. Without calling commit(), the changes will not be saved in the database, which
could lead to data inconsistencies.
Key Points:
Always call commit() after INSERT, UPDATE, or DELETE operations.
If commit() is not called, the changes are not persisted to the database.
Network Programming with Python: A Detailed Guide
Objective:
1. Terms and Basics of Network Programming
Network programming involves writing code that allows your software to communicate with
other software over a network. It includes sending and receiving data across networks like the
internet or a local area network (LAN).
IP Address: A unique string of numbers separated by periods that identifies each computer
using the Internet Protocol to communicate over a network.
Port: A virtual point where network connections start and end. Ports are used to distinguish
between different services on a single device.
Socket: An endpoint for sending and receiving data. Sockets are the building blocks for
communication between two machines on a network.
Protocol: A set of rules that define how data is transmitted over a network. Common
protocols include HTTP, FTP, TCP/IP, and UDP.
Besant Technologies
2. The Architecture of Data Transmission Between Sender and Receiver
Using
In network programming, data transmission between a sender and a receiver is typically done
using sockets.
Socket: The socket library in provides low-level access to network interfaces, allowing you
to send and receive data over a network.
The architecture generally involves:
1. Client: The client initiates a connection to the server and requests services or resources.
2. Server: The server listens for incoming connections on a specific port, processes requests
from the client, and sends the appropriate responses.
Example Architecture:
Client: Connects to the server's IP address and port.
Server: Accepts the connection, processes the request, and sends back a response.
3. Getting Data from the Remote Server
You can retrieve data from a remote server using network sockets or higher-level libraries
like requests for HTTP communication.
Example: Retrieving Data Using Sockets
import socket
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Define the server address and port
server_address = ('www.example.com', 80)
# Connect to the server
client_socket.connect(server_address)
# Send a GET request to the server
request = "GET / HTTP/1.1\r\nHost: www.example.com\r\n\r\n"
client_socket.sendall(request.encode())
# Receive the response from the server
response = client_socket.recv(4096)
# Print the server response
print(response.decode())
# Close the socket
client_socket.close()
Besant Technologies
Example: Retrieving Data Using requests Library
import requests
# Send a GET request to the server
response = requests.get('http://www.example.com')
# Print the response content
print(response.text)
4. Client & Server-Side Programming
Network communication typically involves a client-server model, where the client sends a
request to the server, and the server processes the request and returns a response.
4.1. Client-Side Programming
The client-side program connects to the server, sends requests, and handles responses.
Example: Simple Client Program
import socket
# Create a socket object
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Define the server address and port
server_address = ('localhost', 65432)
# Connect to the server
client_socket.connect(server_address)
try:
# Send data to the server
message = 'Hello, Server!'
client_socket.sendall(message.encode())
# Receive the server's response
data = client_socket.recv(1024)
print(f"Received: {data.decode()}")
finally:
# Close the connection
client_socket.close()
4.2. Server-Side Programming
The server-side program listens for incoming connections, processes client requests, and
sends responses.
Example: Simple Server Program
Besant Technologies
import socket
# Create a socket object
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Bind the socket to an address and port
server_address = ('localhost', 65432)
server_socket.bind(server_address)
# Listen for incoming connections
server_socket.listen()
print("Server is listening...")
while True:
# Accept a connection
client_socket, client_address = server_socket.accept()
try:
print(f"Connection from {client_address}")
# Receive the data
data = client_socket.recv(1024)
print(f"Received: {data.decode()}")
# Send a response
response = 'Hello, Client!'
client_socket.sendall(response.encode())
finally:
# Close the connection
client_socket.close()
5. Hands-on: Using Networking Module in
In , networking is commonly handled using the socket module, which provides access to the
BSD socket interface. This module allows you to work with both TCP and UDP protocols to
create clients and servers.
5.1. Data Transmission Between Client and Server
Using the socket module, you can easily transmit data between a client and a server.
TCP (Transmission Control Protocol): A connection-oriented protocol that ensures data is
reliably delivered in the correct order.
UDP (User Datagram Protocol): A connectionless protocol that is faster but does not
guarantee data delivery or order.
Example: TCP Client-Server Communication
Refer to the client and server examples provided above.
Key Concepts Recap:
Sockets: Fundamental for network programming, used to establish a connection between a
client and server.
Besant Technologies
IP Address and Ports: Essential for identifying machines and services on a network.
Client-Server Model: A common network architecture where clients request services, and
servers provide them.
Regex with Python
Objective: Learn how to use and write Regular Expressions (Regex) in Python.
Regex Syntax:
o Regex (Regular Expressions) are patterns used to match character combinations in
strings.
o Basic syntax:
.: Matches any character except a newline.
^: Matches the start of the string.
$: Matches the end of the string.
\: Escapes special characters.
Quantifiers:
o *: Matches 0 or more repetitions.
o +: Matches 1 or more repetitions.
o ?: Matches 0 or 1 occurrence.
o {n}: Matches exactly n occurrences. {5}
o {n,}: Matches n or more occurrences. {5,}
Metacharacters:
o []: Defines a set of characters to match.
o |: Acts like a logical OR.
o (): Groups expressions and captures matched text.
o \b: Word boundary.
o \d: Matches any digit (equivalent to [0-9]).
o \w: matches any word character, which includes letters,
numbers, and underscores
Special Sequences:
o \s: Matches any whitespace character.
o \S: Matches any non-whitespace character.
Sets:
o [a-z]: Matches any lowercase letter.
o [A-Z]: Matches any uppercase letter.
o [0-9]: Matches any digit.
Python re module:
o import re: To use regex in Python.
Common Methods:
o re.match(): Determines if the regex matches at the beginning of a string.
o re.search(): Searches for the regex pattern in the string.
o re.findall(): Returns all matches of the pattern.
o re.sub(): Replaces matches with a string.
Hands-on Example:
1. re.match()
re.match() checks if the regex pattern matches at the beginning of the string.
Besant Technologies
import re
# Match the word "Python" at the beginning of the string
pattern = r'Python'
text = "Python is a powerful language."
match = re.match(pattern, text)
if match:
print("Match found:", match.group()) # Output: Python
else:
print("No match")
Explanation:
re.match() returns a match only if the pattern is found at the start of the string. If the
pattern is elsewhere, it will return None.
2. re.search()
re.search() looks for the regex pattern anywhere in the string.
import re
# Search for the word "powerful" anywhere in the string
pattern = r'powerful'
text = "Python is a powerful language."
search = re.search(pattern, text)
if search:
print("Search found:", search.group()) # Output: powerful
else:
print("No match")
Explanation:
re.search() will return the first match it finds anywhere in the string, unlike
re.match().
3. re.findall()
re.findall() returns all matches of the pattern in the string as a list.
import re
# Find all occurrences of 3-letter words in the string
pattern = r'\b[a-zA-Z]{3}\b' # Matches any 3-letter word
text = "The cat sat on the mat."
matches = re.findall(pattern, text)
print(matches) # Output: ['The', 'cat', 'sat', 'the', 'mat']
Explanation:
Besant Technologies
re.findall() returns all the matches it finds in the string as a list. It doesn’t stop after the
first match.
4. re.sub()
re.sub() is used to replace all occurrences of the regex pattern in the string with a
replacement string.
import re
# Replace all occurrences of "cat" or "dog" with "pet"
pattern = r'cat|dog'
text = "I have a cat and a dog."
replaced_text = re.sub(pattern, "pet", text)
print(replaced_text) # Output: I have a pet and a pet.
Explanation:
re.sub() replaces all matches of the pattern with the given replacement string. Here, both
"cat" and "dog" are replaced by "pet".
5. Using re.match(), re.search(), re.findall(), and re.sub() together
import re
text = "My email is [email protected]. Another email is
[email protected]."
# re.match(): Look for "My" at the beginning of the string
pattern_match = r'My'
match = re.match(pattern_match, text)
print("Match result:", match.group() if match else "No match") # Output:
Match result: My
# re.search(): Search for the first email in the text
pattern_search = r'\w+@\w+\.\w+'
search = re.search(pattern_search, text)
print("Search result:", search.group() if search else "No match") #
Output: Search result:
[email protected]# re.findall(): Find all email addresses in the text
pattern_findall = r'\w+@\w+\.\w+'
findall = re.findall(pattern_findall, text)
print("Findall result:", findall) # Output: Findall result:
['
[email protected]', '
[email protected]']
# re.sub(): Replace all email addresses with "[email]"
pattern_sub = r'\w+@\w+\.\w+'
replaced_text = re.sub(pattern_sub, "[email]", text)
print("Replaced text:", replaced_text) # Output: My email is [email].
Another email is [email].
Besant Technologies
API Access with Python
Objective: Learn how to access open APIs using Python.
Topics:
Google Text to Speech:
o Convert text to speech using gTTS (Google Text-to-Speech).
o Example:
from gtts import gTTS
import os
text = "Hello, how are you?"
tts = gTTS(text)
tts.save("output.mp3")
os.system("start output.mp3")
Google Speech to Text:
o Convert speech to text using the SpeechRecognition library.
o Example:
import speech_recognition as sr
recognizer = sr.Recognizer()
with sr.Microphone() as source:
print("Speak now:")
audio = recognizer.listen(source)
try:
print("You said: " + recognizer.recognize_google(audio))
except sr.UnknownValueError:
print("Google Speech Recognition could not understand the
audio")
OpenWeatherMap:
o Access weather data from OpenWeatherMap API.
o Example:
import requests
api_key = "your_api_key"
city = "London"
url =
f"http://api.openweathermap.org/data/2.5/weather?q={city}&appid
={api_key}"
response = requests.get(url)
data = response.json()
print(f"Weather in {city}:
{data['weather'][0]['description']}")
Besant Technologies
GUI Programming with PyQt5 in Python
Objective:
PyQt5 is a powerful Python library for creating Graphical User Interface (GUI) applications.
It provides bindings for the Qt application framework and is widely used for creating cross-
platform desktop applications.
Introduction to PyQt5
PyQt5 is a set of Python bindings for Qt libraries which can be used to create professional-
looking desktop applications.
With PyQt5, you can build modern and efficient graphical interfaces and manage events like
button clicks, text input, etc.
Components and Events in PyQt5
Components are UI elements like buttons, text boxes, labels, etc.
Events are actions triggered by the user, such as clicking a button, entering text, etc. These
actions can be handled using signals and slots.
Example: Basic PyQt5 Application
import sys
from PyQt5.QtWidgets import QApplication, QLabel, QWidget
# Create an application object
app = QApplication(sys.argv)
# Create a window (QWidget)
window = QWidget()
window.setWindowTitle('Hello PyQt5')
window.setGeometry(100, 100, 280, 80)
# Add a label to the window
label = QLabel('<h1>Hello, World!</h1>', parent=window)
label.move(60, 15)
# Show the window
window.show()
# Start the application loop
sys.exit(app.exec_())
Explanation:
QApplication: Initializes the application.
QWidget: Represents the window.
QLabel: Displays static text inside the window.
app.exec_(): Enters the application's main loop and waits for events.
Besant Technologies
Widgets in PyQt5
QPushButton: Button widget to trigger actions.
QLineEdit: Text input widget to accept user input.
QLabel: Displays static text or images.
QCheckBox: A checkbox widget to select/deselect options.
Example with Multiple Widgets
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QLabel,
QLineEdit, QVBoxLayout
# Define the main application
def on_click():
label.setText("Button clicked!")
app = QApplication(sys.argv)
# Create a window
window = QWidget()
window.setWindowTitle('Simple PyQt5 App')
# Create widgets
button = QPushButton('Click Me', window)
label = QLabel('Hello, PyQt5', window)
text_input = QLineEdit(window)
# Connect button click event to the on_click function
button.clicked.connect(on_click)
# Set layout
layout = QVBoxLayout()
layout.addWidget(label)
layout.addWidget(text_input)
layout.addWidget(button)
# Apply the layout to the window
window.setLayout(layout)
window.show()
# Run the application
sys.exit(app.exec_())
Layout Management
Layouts help you organize the widgets inside a window. PyQt5 provides various layouts such
as:
QVBoxLayout: Arranges widgets vertically.
QHBoxLayout: Arranges widgets horizontally.
Example with Layouts
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QVBoxLayout
Besant Technologies
app = QApplication(sys.argv)
# Create a window
window = QWidget()
window.setWindowTitle('Layout Example')
# Create buttons
button1 = QPushButton('Button 1', window)
button2 = QPushButton('Button 2', window)
button3 = QPushButton('Button 3', window)
# Use QVBoxLayout
layout = QVBoxLayout()
layout.addWidget(button1)
layout.addWidget(button2)
layout.addWidget(button3)
# Set layout to the window
window.setLayout(layout)
# Show window
window.show()
sys.exit(app.exec_())
Signals and Slots
Signal: Event or action (e.g., button clicked).
Slot: Function that gets called when the signal is emitted.
Example with Signals and Slots
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton
def on_click():
print("Button clicked!")
app = QApplication([])
window = QWidget()
# Create a button and connect it to the on_click slot
button = QPushButton('Click Me', window)
button.clicked.connect(on_click)
window.show()
app.exec_()
QMessageBox and QDialog
QMessageBox: Displays dialog boxes like alerts, information, or confirmation.
QDialog: Modal dialog used to gather user input.
Example with QMessageBox
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QMessageBox, QPushButton
Besant Technologies
def show_message():
msg_box = QMessageBox()
msg_box.setText("This is a message box")
msg_box.exec_()
app = QApplication(sys.argv)
# Create window
window = QWidget()
window.setWindowTitle('Message Box Example')
# Add button
button = QPushButton('Show Message', window)
button.clicked.connect(show_message)
window.show()
sys.exit(app.exec_())
Database Handling with PyQt5 (MySQL Integration)
PyQt5 allows for the integration of databases, enabling you to build desktop applications that
can interact with databases. The QSqlDatabase class from PyQt5's QtSql module provides a
flexible way to interact with databases like MySQL. Below is an explanation of how to
integrate MySQL databases with PyQt5 and perform basic operations such as displaying data
in a PyQt5 application.
Steps to Handle MySQL Databases with PyQt5:
1. Install MySQL Connector: You will need to install the mysql-connector-python
library for connecting your Python application to a MySQL database.
pip install mysql-connector-python
2. Create MySQL Database & Table: Ensure that your MySQL database is set up and
that you have a table from which you want to fetch data. For this example, let’s
assume you have a database named sample_db and a table named employees.
CREATE DATABASE sample_db;
USE sample_db;
CREATE TABLE employees (
id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
position VARCHAR(100),
salary FLOAT
);
INSERT INTO employees (name, position, salary)
VALUES
('John Doe', 'Manager', 70000),
('Jane Smith', 'Engineer', 55000),
('Sam Brown', 'HR', 45000);
Besant Technologies
PyQt5 GUI to Show MySQL Table Data
This example demonstrates how to fetch data from the MySQL database and display it in a
PyQt5 application.
Full Example: PyQt5 GUI to Display Data from MySQL Table
import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout,
QPushButton, QLabel, QLineEdit, QTableWidget, QTableWidgetItem
import mysql.connector
class MySQLTableDisplay(QWidget):
def __init__(self):
super().__init__()
# Setup the PyQt5 window
self.setWindowTitle('Employee Table Display')
self.setGeometry(100, 100, 600, 400)
# Create a vertical layout
layout = QVBoxLayout()
# Create a table widget
self.table_widget = QTableWidget()
layout.addWidget(self.table_widget)
# Button to load data
load_button = QPushButton('Load Data')
load_button.clicked.connect(self.load_data)
layout.addWidget(load_button)
# Set the layout for the window
self.setLayout(layout)
def load_data(self):
# Establish MySQL connection
connection = mysql.connector.connect(
host='localhost',
user='root', # Your MySQL username
password='your_password', # Your MySQL password
database='sample_db'
)
cursor = connection.cursor()
# Query to fetch all data from the employees table
cursor.execute("SELECT * FROM employees")
records = cursor.fetchall()
# Set the number of rows and columns for the table widget
self.table_widget.setRowCount(len(records))
self.table_widget.setColumnCount(3)
self.table_widget.setHorizontalHeaderLabels(['ID', 'Name',
'Position', 'Salary'])
# Populate the table with data
for row_index, row_data in enumerate(records):
for column_index, data in enumerate(row_data):
self.table_widget.setItem(row_index, column_index,
QTableWidgetItem(str(data)))
Besant Technologies
# Close the cursor and connection
cursor.close()
connection.close()
# Main execution of the PyQt5 application
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MySQLTableDisplay()
window.show()
sys.exit(app.exec_())
Explanation:
1. MySQL Connection:
o The mysql.connector.connect() function is used to establish a connection to
the MySQL database.
o Replace 'localhost', 'root', and 'your_password' with your MySQL host,
username, and password, respectively.
2. Fetching Data:
o The cursor.execute("SELECT * FROM employees") command fetches all
records from the employees table.
o The records = cursor.fetchall() function retrieves all rows from the result
set as a list of tuples.
3. Displaying Data in PyQt5 Table:
o The QTableWidget is used to create a table in the PyQt5 GUI.
o setRowCount() and setColumnCount() methods define the number of rows
and columns in the table.
o setHorizontalHeaderLabels() defines the column names.
o A nested loop iterates through the fetched records and populates the
QTableWidget.
4. Triggering the Display:
o A button labeled Load Data is connected to the load_data() function, which
loads the data from the database and displays it when clicked.