Readable_Python_Notes
Readable_Python_Notes
I. Introduction
**********************************************************************
***
**************************
I. Introduction:
----------------
Python is a high
-
level, inte
rpreted, dynamic programming language
known for its simplicity and readability.
Page 1
Python Notes
Created by Guido van Rossum and first released in 1991.
**********************************************************************
***
**************************
---------------------------
-----------------------------
Python's syn
tax is designed to be clear and readable, making it an
Page 2
Python Notes
ideal language
2. Interpreted Language:
------------------
------
--
Page 3
Python Notes
-----------------------------
------------------------------
This eliminates the need to write code from scratch for common
Page 4
Python Notes
functionalities.
5. Dynamic Typing:
------------------
---------------------------------
Page 5
Python Notes
7. Object
-
Oriented Programming:
-----------
--------------------
8. Open Source:
---------------
Page 6
Python Notes
Python is an open
-
source language, encouraging collaboration and
allowing developers to modify and
***********************************
**************************************
**************************
------------------------------
1. Performance:
---------------
Page 7
Python Notes
Python is an interpreted language, and while this provides
flexibility and ea
se of development,
---------------------------------
Page 8
Python Notes
3. Mobile Development:
---------------------
-
4. Memory Consumption:
----------------------
===============================
Page 9
Python Notes
a. Procedural programming
-------------------------
def greet(name):
return a + b
# Main program
Page 10
Python Notes
greet(user_name)
print("Sum:", result)
-------------------------------------------
# Function to calcula
te the square of a number
def square(x):
Page 11
Python Notes
return x ** 2
# Example usage
squared_numbers = square(8)
c. Object
-
oriented programming example in Python
-------------------------------------------------
class Dog:
Page 12
Python Notes
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
print("Woof!")
my_dog = Dog("Buddy", 3)
my_dog.bark()
Page 13
Python Notes
============
==============
1. Web Development:
-------------------
Frameworks like Django and Flask are widely used for building web
applications.
Selenium
Page 14
Python Notes
-------------------------------------
Scikit
-
learn is a powerful library for machine learning tasks.
Page 15
Python Notes
3. Artificial Intelligence:
---------------------------
4. Scientific Computing:
------------------------
Page 16
Python Notes
----------------------------
Libraries like Tkinter, PyQt, and Kivy are used for developing
6. Network Programming:
-----------------------
Python's socket library and frameworks like Twisted are used for
Page 17
Python Notes
---
-------------------------
8. Cybersecurity:
-----------------
9. Cloud Computing:
Page 18
Python Notes
-------------------
10. DevOps:
-----------
Page 19
Python Notes
2.0 Tokens:
===========
I. Introduction
**********************************************************************
***
**************************
I. Introduction:
----------------
Page 20
Python Notes
source code.
**********************************************************************
***
**************************
------------------------------
a. Keywords:
------------
Page 21
Python Notes
b. Identifiers:
---------------
Page 22
Python Notes
variable_name = 42
_name = "python"
c. Literals:
------------
Page 23
Python Notes
integer_literal = 42
boolean_literal = True
d. Operators:
-------------
Page 24
Python Notes
`, `<`, `>`)
e. Delimiters:
--------------
my_list = [1, 2, 3]
Page 25
Python Notes
f. Comments:
------------
They start with the `#` symbol and are used for documentation and
cl
arification.
# This is a comment
g. Strings:
-----------
Page 26
Python Notes
h. Whitespace:
--------------
Page 27
Python Notes
def my_function():
print("Hello")
2.1.
Variables:
===============
I. Introduction
III. Keywords
**********************************************************************
***
Page 28
Python Notes
**************************
I. Introduction:
----------------
Page 29
Python Notes
x = 10
name = "Python"
name = "Python"
print(name)
Page 30
Python Notes
x = 10
x = 20
x = "Python"
x = [4, 7, 9]
Page 31
Python Notes
**********************************************************************
***
**************************
--------------------------------
A variable na
me must begin with a letter of the alphabet(a
-
z, A
-
Z) or an underscore(_)
Page 32
Python Notes
-
|
----------------------
|
---------------
|
-------------------------------
---------------------------------------
---------------------------
|
Page 33
Python Notes
| Pascal Case | UserName | Class names (e.g., class
UserProfile:)
for single
-
word names. |
**************************
***********************************************
**************************
III. Keywords:
Page 34
Python Notes
--------------
keywords are reserved words that have special meanings and cannot be
used as identifiers
Page 35
Python Notes
Keywords cannot be used as variable names, as they are already
reserved.
True def
as elif if or yield
Page 36
Python Notes
**********************************************************************
***
**************************
--------------
The LEGB rule defines the order in which Python looks for variable
names in different scopes.
The acronym L
EGB stands for Local, Enclosing, Global, and Built
-
in.
Page 37
Python Notes
-
-------------------
Local variables are accessible only within the function where they
are defined.
Example:
python
Page 38
Python Notes
def my_function():
local_variable = 10
print(local_v
ariable)
-----------------------
Page 39
Python Notes
-
Example:
python
def outer_function():
outer_variable = 20
def inner_function():
Page 40
Python Notes
e from the
enclosing scope
inner_function()
outer_function()
--------------------
Global variabl
es are accessible throughout the module or script.
Page 41
Python Notes
Example:
python
global_variable = 30
def another_function():
another_func
tion()
4. Built
-
in Scope (B):
Page 42
Python Notes
----------------------
Example:
python
Page 43
Python Notes
-
in function len()
================================
I. Introduction
III. Garba
ge Collection in Python
**********************************************************************
***
**************************
I. Introduction:
----------------
Page 44
Python Notes
memory
Python uses a private heap space to manage memory, and the Python
memory manager
**************************************************************
***********
**************************
-----------------
Page 45
Python Notes
a. Memory Allocation:
---------------------
The si
ze of the memory block allocated depends on the type and
structure of the object.
b. Reference Counting:
----------------------
Each object has a reference count associated with it, and when
the count drops to zero,
Page 46
Python Notes
c. Garbage Collection:
----------------------
****
*********************************************************************
**************************
Page 47
Python Notes
----------------------------------
-----------------------------
Page 48
Python Notes
collect cyclic references,
-----------------------------------
Python's garbage
collector uses a generational approach,
Page 49
Python Notes
-------------------------------------------
Refer
ence counting handles short
-
term memory management, while
garbage collection handles
long
-
term memory management and cyclic references.
Page 50
Python Notes
d. `gc` Module:
---------------
3. Operators:
=============
Page 51
Python Notes
I. Introduction
**********************************************************************
***
**************************
I. Introduction
----------------
Page 52
Python Notes
calculations, compare values, logical operations,
Arithmetic Operators
Comparison Operators
Logical Operators
Page 53
Python Notes
Membership operators
Assig
nment operators
Identity operators
Bitwise Operators
**********************************************************************
***
**************************
-----------------------------------
a. Arithmetic
Page 54
Python Notes
Operators:
------------------------
1. Addition
-----------
a = 10
Page 55
Python Notes
b = 5
sum_result = a + b
print("Sum:", sum_result)
2. Subtraction
-
-------------
a = 10
Page 56
Python Notes
b = 5
diff_result = a
-
print("Difference:", diff_result)
3. Multiplication
----------------
Page 57
Python Notes
a = 10
b = 5
prod_result = a * b
print("Product:", prod_result)
4. Division
-
----------
Page 58
Python Notes
a = 10
b = 5
div_result = a / b
print("Quotient:", div_result)
5. Modulus (remainder)
----------------------
Page 59
Python Notes
a = 10
b = 5
mod_result = a % b
print("Remainder:", mod_result)
6. Exponentiation
Page 60
Python Notes
-----------------
a = 10
b = 5
exp_result = a ** b
print("Exponentiation:", exp_result)
7. Floor Division
Page 61
Python Notes
-----------------
a = 10
b = 5
result = a // b
b. Compari
son Operators:
------------------------
Page 62
Python Notes
-
1. Equal to ( == )
------------------
x = 10
y = 5
Page 63
Python Notes
print(x == y)
2. Not equal to ( != )
----
------------------
x = 10
y = 5
Page 64
Python Notes
print(x != y)
---------------------
x = 10
y = 5
Page 65
Python Notes
print(x > y)
------------------
x = 10
y = 5
print(x < y)
Page 66
Python Notes
----------------------------------
x = 10
y = 5
Page 67
Python Notes
-------------------------------
x = 10
y = 5
print(x <= y)
Page 68
Python Notes
c
. Logical Operators:
---------------------
----------------------
p = True
q = False
Page 69
Python Notes
print(p and q)
2. Logical OR ( or )
--------------------
p = True
q = False
Page 70
Python Notes
print(p or q)
----------------------
p = True
q = False
print(not p)
Page 71
Python Notes
Table:
------
| p | q | p AND q | p OR q |
|
-------
|
-------
|
---------
|
--------
|
Page 72
Python Notes
d. Membership Operators:
-------------
-----------
Page 73
Python Notes
1. In ( in )
------------
my_list = [1, 2, 3, 4, 5]
Page 74
Python Notes
2. Not in ( not in )
--------------------
my_list = [1, 2, 3, 4,
5]
e. Assignment Operators:
------------------------
Page 75
Python Notes
-----------------
x = 10
x += 5 # Equivalent to x =
x + 5
Page 76
Python Notes
----------------------
x = 5
x
-
= 3 # Equivalent to x = x
-
Page 77
Python Notes
----------------------
x = 4
x *= 2 # Equivalent to x = x * 2
-------
-------------
x = 5
Page 78
Python Notes
x /= 4 # Equivalent to x = x / 4
print(x)
f. Identity Operators:
----------------------
Page 79
Python Notes
a = [1, 2, 3]
b = a
Page 80
Python Notes
1. is
-----
print(a is b)
2. is not
---------
print(a is not b)
Page 81
Python Notes
g. Bitwise Operators:
---------------------
--------------
Page 82
Python Notes
p = 5 binary: 0101
q = 3 binary: 0011
0001
print(p & q)
Page 83
Python Notes
----
2. Bitwise OR ( | )
-------------------
p = 5 binary: 0101
q = 3 binary: 0011
print(p | q) 0111
Page 84
Python Notes
----
-
3. Bitwise XOR ( ^ )
--------------------
p = 5 binary: 0101
Page 85
Python Notes
q = 3 binary: 0011
print(p ^ q)
-----
4.
Bitwise NOT ( ~ )
Page 86
Python Notes
--------------------
print(~p)
Note:
'=='' is for value equality. It's used to know if two objects have
the same value.
Page 87
Python Notes
Examples:
---------
mutable objec
ts:
----------------
a = []
b = []
print(a is b)
Page 88
Python Notes
print(id(a))
print(id(b))
print(a==b)
immutable objects:
----------------
a = ''
b = ''
print(a is b)
Page 89
Python Notes
print(id(a))
print(id(b))
print(a==b)
****************
*********************************************************
**************************
-------------------------
Page 90
Python Notes
It defines th
e hierarchy of operators, ensuring that some
operators are evaluated before others.
Parentheses : ()
Exponentiation : **
Multiplicatio
n, division, and remainder : *, /, //, %
Page 91
Python Notes
Bitwise XOR : ^
Bitwise OR
: |
Page 92
Python Notes
Logical OR : or
Example:
--------
result = 6 + 7 * 4 ** 2
-
Page 93
Python Notes
(8 % 3)
Remainder : 8 % 3 evaluates to 2.
Parentheses : (8 % 3) is now 2.
Subtraction : 118
-
2 evaluates to 116.
Page 94
Python Notes
4.Datatypes/Structures Introduction:
====================================
I. Req
uirement
V. Type Conversions
VI. Range
**********************************************************************
***
**************************
I. Requirement:
---------------
Page 95
Python Notes
Entity :
Noun Form
State : Datatype/Structures
Validations : Client/Server
# CRUD
# x = 10
# print(x)
Page 96
Python Notes
# x += 5
# del x
# print()
# type()
# id()
# input()
**********************************************************************
***
**************************
------------------
Page 97
Python Notes
Basic input
example
-------------------
print(user_input)
--------------------------
print(type(user_age))
Page 98
Python Notes
Handling multiple inputs
------------------------
print("Hello, " + name + "! You are " + str(age) + " years old.")
*******************
******************************************************
**************************
----------------
1. Numeric Types:
----------------
Page 99
Python Notes
float : Floating
-
p
oint type, representing decimal numbers.
Example:
x = 5 int
y = 3.14 float
Page 100
Python Notes
z = 2 + 3j complex
2. Text Type:
--
------------
Example:
text = "Hello"
3. Sequence Types:
Page 101
Python Notes
------------------
Example:
my_list = [1, 2, 3]
Page 102
Python Notes
my_tuple = (4, 5, 6)
my_range = range(0, 5)
4. Set Types:
-------------
set : Unordered,
Example:
my_set = {1, 2, 3}
Page 103
Python Notes
5. Mapping Type:
-------------
---
Example:
Page 104
Python Notes
6. Boolean Type:
----------------
Example:
is_true = True
is_false = False
7. None Type:
Page 105
Python Notes
-------------
Example:
no_value = None
*****************
********************************************************
**************************
--------------------
1. Lists:
Page 106
Python Notes
---------
Example:
my_list = [1, 2, 3, 4, 5]
2. Tuples:
----------
Page 107
Python Notes
Example:
my_tuple = (1, 2, 3, 4, 5)
3. Sets:
--------
Page 108
Python Notes
Example:
my_set = {1, 2, 3, 4, 5}
4. Dictionaries:
----------------
Page 109
Python Notes
Allows efficient lookup based on keys.
Example:
print(my_dict['name'])
print(my_dict.get('name
'))
5. Strings:
-----------
Page 110
Python Notes
Sequences of characters. Immutable.
Example:
------------------------------
Homogeneous,
fixed
-
size sequences. Elements must be of the same
type.
Page 111
Python Notes
Example:
***************************************************************
**********
**************************
V. Type Conversions:
--------------------
1. Integer to Float:
--------------------
Page 112
Python Notes
integer_value = 5
float_va
lue = float(integer_value)
-------------------------------
string_number = "10"
integer_number = int(s
tring_number)
float_number = float(string_number)
Page 113
Python Notes
3. Number to String:
---------------------
number = 42
string_representation = str(number)
Page 114
Python Notes
4. String to Boolean:
---------------------
tr_string = "True"
Page 115
Python Notes
boolean_value = bool(tr_string)
5. Boolean to String:
----------
-----------
boolean_value = True
string_representation = str(boolean_value)
6. Float to Integer:
--------------------
Page 116
Python Notes
nteger using int(). Note that this
will truncate the decimal part:
float_number = 3.14
integer_number = int(float_number)
**********************************************************************
***
**************************
V
I. range:
----------
Page 117
Python Notes
# # stop(manda
tory) : if n is the stop
provided then upto n
-
1
# print(each)
**********************************************************************
***
**************************
5. Decision Making:
===================
I. Introduction
Page 118
Python Notes
III. Examples
**********************************************************************
***
**************************
I. Introduction:
----------------
De
cision Making is the process of executing different blocks of
code based on certain conditions.
The constructs for decision making are 'if', 'elif' (else if),
and 'else' statements.
Page 119
Python Notes
These statements allow you to control the flow of
execution
based on the evaluation of specified conditions.
***************************
**********************************************
**************************
-----------------------
1. if Statement:
----------------
Page 120
Python Notes
specified cond
ition is true.
if condition:
2. elif Statement:
------------------
Page 121
Python Notes
code if the preceding conditions
if condition1:
elif condition2:
Page 122
Python Notes
3. else Statement:
-----
-------------
if condition1:
Page 123
Python Notes
elif condition2:
else:
**********************************************************************
***
**************************
III. Examples:
--------------
Page 124
Python Notes
if num > 0:
print("Number is positive.")
print("Number is negative.")
else:
print("Number is zero.")
Page 125
Python Notes
6. LOOPS, Co
ntrol Statements:
=============================
I. Introduction
Page 126
Python Notes
**********************************************************************
***
**************************
I. Introduction:
------
----------
Page 127
Python Notes
Automation
Page 128
Python Notes
processing elements in a
collection one by one.
Loops can
Page 129
Python Notes
Ranges : Genera
ting a sequence of numbers
using the range function
Page 130
Python Notes
-
Custom Objects
: If an object supports iteration (by
implementing __iter__ and __next__ methods)
Page 131
Python Notes
-
for loops
while loops
**********************************************************************
***
**********
****************
------------
Page 132
Python Notes
Page 133
Python Notes
Example:
--------
Page 134
Python Notes
a", "cherry"]
print(fruit)
**********************************************************************
***
**************************
----------------
Page 135
Python Notes
while
loop might be more appropriate on below scenarios
Page 136
Python Notes
advance how many iterations are needed
Example:
Page 137
Python Notes
--------
while condition:
# Factorial Calculation
Page 138
Python Notes
#
---------
--------------
given_num = num
result = 1
Page 139
Python Notes
result *= num
num
-
= 1
Page 140
Python Notes
# Guessing
Game with Break
#
-------------------------
secret_number = 3
Page 141
Python Notes
while True:
if guess == secret_number:
Page 142
Python Notes
break
else:
print("Try again.")
# Fibonacci
#
-----------
Page 143
Python Notes
a, b = 0, 1
count = 0
Page 144
Python Notes
print(a)
nth = a + b
a = b
Page 145
Python Notes
b = nth
count += 1
**********************************************************************
***
**************************
-----------------------
Page 146
Python Notes
break Statement:
----------------
Page 147
Python Notes
Examp
le:
--------
Page 148
Python Notes
for i in range(5):
if i == 3:
break
print(i)
Page 149
Python Notes
continue Statement:
-------------------
It
Page 150
Python Notes
Skipping certain iterations based on a condition
without terminating the entire loop.
Example:
--------
for i in range(5):
if i == 2
:
Page 151
Python Notes
continue
print(i)
pass Statement:
---------------
Page 152
Python Notes
op statement, meaning
it does nothing.
Page 153
Python Notes
Example:
--------
for i in range(3):
if i == 1:
Page 154
Python Notes
pass
else:
print(i
)
String:
Page 155
Python Notes
========================================
String:
------
****************************************************
*********************
**************************
-----------------------------
Page 156
Python Notes
-
# https://python
-
reference.readthedocs.io/en/latest/docs/str/ASCII.html
# https://home.unicode.org/
# https://en.wikipedia.org/wiki/List_of_Unicode_characters
Page 157
Python Notes
ASCII(128):
Unicode():
Page 158
Python Notes
Req
uires more memory compared to ASCII.
**********************************************************************
***
**************************
Operations on Sequences:
------------------------
String
-
List
-
Page 159
Python Notes
Tuple
Indexing:
---------
first_char =
my_string[0] # Access the first character
print(first_char) # Output: H
Slicing:
Page 160
Python Notes
--------
substrin
g = my_string[7:12] # Extract a portion of the string
Adding:
-------
Page 161
Python Notes
Concatenating two or more sequences together.
second_part = "World
!"
Multiplying:
------------
orig
Page 162
Python Notes
inal_string = "abc"
-----------------------
Ver
ifying if a specific character/word is present in a
sequence.
Page 163
Python Notes
e
len():
------
print(length_of_string)
# Output: 13
max():
Page 164
Python Notes
------
my_string = "python"
print(max_of_string) # Output: y
min()
:
------
Page 165
Python Notes
my_string = "python"
print(min_of_string) # Output: h
----------------------------
last_char = my_string[
-
1] # Access the last character using
Page 166
Python Notes
negative indexing
print(last_char) # Output: d
----------------------------
-----------------------
name = "John"
age = 30
Page 167
Python Notes
print("Hello, my name is %s
------------------------------------
name = "John"
age = 15
f
-
st
rings:
Page 168
Python Notes
------------
name = "John"
age = 15
**********************************************************************
***
**************************
String Functions
(47):
---------------------
+
---------------
+
--------------
Page 169
Python Notes
+
--------------
+
-------------
+
--------
------
+
--------------
+
--------------
+
--------------
+
| endswith
| expandtabs | join |
| istitle |
isupper | splitlines |
Page 170
Python Notes
| rstrip | sp
lit | splitlines |
| removesuffix | | | |
| |
| |
+
---------------
+
--------------
+
--------------
+
-------------
Page 171
Python Notes
+
--------
------
+
--------------
+
--------------
+
--------------
+
Page 172
Python Notes
Page 173
Python Notes
---------------------------------------------------------
---
str()
---
Note:
-----
\
t for a tab
\
n for a newline
\
\
for a backslash
\
" for a double quote
\
' for a single quote
Page 174
Python Notes
****
*********************************************************************
**************************
List:
=====
I. Introduction
II. Built
-
in methods for lists(11)
************************************************************
*************
**************************
I. Introduction:
----------------
Page 175
Python Notes
-
[].
Indexing
-
Page 176
Python Notes
(positve and negative)
Slicing
Concatenating (adding)
len()
min()
Page 177
Python Notes
max()
**********************************************************************
***
**************************
II. Built
-
in methods for lists(11):
-----------------------------------
# Sample list
Page 178
Python Notes
sample_list = [1, 2, 3, 4, 3, 5]
sample_list.append(6)
print(f"append: {sampl
e_list}")
sample_list.clear()
print(f"clear: {sample_list}")
original_list = [1, 2, 3]
copied_list = original_lis
Page 179
Python Notes
t.copy()
print(f"copy: {copied_list}")
count_occurrences = sample_list.count(3)
print(f"count: {count_occurrences}")
sample_list.extend([4, 5, 6])
print(f"extend: {sample_list}")
Page 180
Python Notes
index_result = sample_list.index(4)
print(f"index:
{index_result}")
sample_list.insert(1, 10)
print(f"insert: {sample_list}")
# pop: Remove and return the last element from the list
popped_eleme
nt = sample_list.pop()
Page 181
Python Notes
sample_list.remove(4)
print(f"remove: {sample_list}")
sample_list.reverse()
print(f"reverse: {sample_list}")
sample_list.sort()
print(f"s
ort: {sample_list}")
Page 182
Python Notes
numbers = [3, 1, 4, 1, 5, 9, 2]
sorted_numbers = sorted(numbers)
print(sorted_numbers) # O
utput: [1, 1, 2, 3, 4, 5, 9]
**********************************************************************
***
**************************
-------------------------
Page 183
Python Notes
-
syntax
-
Page 184
Python Notes
iterable : The iterable you are iterating over (e.g., a list,
tuple, or s
tring).
Example:
--------
print(squares) # Ou
tput: [0, 1, 4, 9, 16]
Tuple:
======
Page 185
Python Notes
I. Introduction
II. Built
-
in methods for Tuples(02)
**********************************************************************
***
**************************
I. Introduction:
----------------
Page 186
Python Notes
().
Indexing
-
Slicing
Concatenating (adding)
Page 187
Python Notes
len()
min()
max()
Note:
----
Empty tuple
Page 188
Python Notes
-
()
(element,)
**
**********************************************************************
*
**************************
II. Built
-
in methods for Tuples(02)
------------------------------------
# count
-
Page 189
Python Notes
the
tuple.
my_tuple = (1, 2, 2, 3, 2, 4)
occurrences_of_2 = my_tuple.count(2)
print(occurrences_of_2) # Output: 3
# index
-
my_tuple = (1, 2
, 3, 4, 5)
index_of_3 = my_tuple.index(3)
print(index_of_3) # Output: 2
Page 190
Python Notes
--------------------------------------------------------
---
tuple()
----
**************
***********************************************************
**************************
Set:
====
I. Introduction
II. Built
-
in methods for Sets(17)
Page 191
Python Notes
**********************************************************************
***
*
*************************
I. Introduction:
----------------
Page 192
Python Notes
Sets holds only immutable datatypes.
S
ets can contain both homogeneous and heterogeneous immutable
datatypes.
{}.
len()
Page 193
Python Notes
min()
max()
Note:
-----
Empty
set
-
set() or set({})
**********************************************************************
***
**************************
II. Built
-
Page 194
Python Notes
in methods for Sets(17):
----------------------------------
----------------------------------------------
my_set = {1, 2, 3}
my_set.add(4)
--------------------------------------------
my_set.clear(
)
Page 195
Python Notes
-------------------------------------------
original_set = {1, 2, 3}
copied_set = original_set.copy()
# 4. difference: Get the set of elements in the first set but not in
the second set
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
Page 196
Python Notes
result_set = set1.difference(set2)
# 5. difference_update: Remove el
ements from the set that are in
another set
---------------------------------------------------------------------
-------
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.difference_update(set2)
# 6.
Page 197
Python Notes
-------------------------------------------------------------
my_set = {1, 2, 3}
my_set.discard(2)
------------------------------------------------------------------
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
Page 198
Python Notes
result_set = set1.intersection(set2)
# 8. intersection
_update: Update the set with the intersection of
itself and another set
---------------------------------------------------------------------
-------------------
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
set1.intersection_update(set2)
Page 199
Python Notes
-------------------------------------------------------------
set1 = {1, 2, 3}
set2 = {4, 5, 6}
is_disjoint = set1.isdisjoint(set2)
--------------------------------------------------------------------
set1 = {1, 2}
set2 = {1, 2, 3, 4}
is_subset = set1.issub
set(set2)
Page 200
Python Notes
---------------------------------------------------------------------
set1 = {1, 2, 3, 4}
set2 = {1, 2}
is_supe
rset = set1.issuperset(set2)
# 12. pop: Remove and return an arbitrary element from the set
--------------------------------------------------------------
Page 201
Python Notes
my_set = {1, 2, 3}
popped_element = my_
set.pop()
-----------------------------------------------------
my_set = {1, 2, 3}
my_set.remove(2)
print(my_set) # Out
put: {1, 3}
Page 202
Python Notes
---------------------------------------------------------------------
----------
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
result_set = set1
.symmetric_difference(set2)
---------------------------------------------------------------
------
-------------------------------------
set1 = {1, 2, 3, 4}
Page 203
Python Notes
set2 = {3, 4, 5, 6}
set1.symmetric_difference_update(set2)
----------
--------------------------------------------
set1 = {1, 2, 3}
set2 = {3, 4, 5}
result_set = set1.union(set2)
# 17. update: Update the set with elements from another set or
iterable
Page 204
Python Notes
---------------------------------------------------------------------
--
set1 = {1, 2, 3}
set2 = {3, 4, 5}
set1.update(set2)
-------
------------------------------------------------
---
set()
---
Page 205
Python Notes
**********************************************************************
***
**************************
------------------------
syntax
-
Page 206
Python Notes
Example:
Page 207
Python Notes
--------
print(
squares_set)
Dictionary:
===========
I. Introduction
II. Built
-
in methods for Dictionary(11)
Page 208
Python Notes
**********************************************************************
***
**************************
I. Introduction:
----------------
Page 209
Python Notes
{}.
len()
min()
max()
Page 210
Python Notes
Note:
-----
Empty Dictionary
-
dct = {}
****************************************
*********************************
**************************
II. Built
-
in methods for Dictionary(11):
-----------------------------------
dict functions(11):
-------------------
Page 211
Python Notes
# 1. clear: Re
move all items from the dictionary
------------------------------------------------
my_dict.clear()
# Re
-
create the sample dictionary
Page 212
Python Notes
--------------------------------------------------
copied_dict = my_dict.copy()
-------------------------------------------------------------------
-----------
print("Fro
mkeys result:", new_dict) # Output: {'x': 0, 'y': 0,
'z': 0}
Page 213
Python Notes
-------------------------------------------------------------------
--------------------
----
# 5.
------------------------------------------------------------------
Page 214
Python Notes
all_items = my_dict.items()
-------------------------------------------------------
all_keys = my_dict.keys()
# 7. pop: Remove the item with the specified key and return its
value
-------------------------------------------------------------------
--
Page 215
Python Notes
print("Removed value
-----------------------------------------------------------
removed_item = my_dict.popitem()
Page 216
Python Notes
print("Updated dictionary:", my_dict) # Output: {'a': 1}
-------------------------------------------------------------------
--------------------------------
print("New key
-
value for 'b':", new_key_value) # Output: 20
Page 217
Python Notes
-------------------------------------------------------------------
-------------------------
my_dict.update(update_dict)
-----------------------------------------------------------
Page 218
Python Notes
all_values = my_di
ct.values()
--------------------------------------------------------------
---
dict()
---
Examples:
---------
Page 219
Python Notes
------------------------------
dict_from_list = dict(list_of_tuples)
print(dict_from_list)
-----------------------------
dict_from_list = dict(list_of_lists)
print(dict_from_list)
Page 220
Python Notes
# Two separate lists to dictionary
----------------------------------
values = [1, 2, 3]
print(dict_from_lists)
# Tuple of key
-
value pairs to dictionary
-----------------
-----------------------
Page 221
Python Notes
dict_from_tuple = dict(tuple_of_pairs)
print(dict_from_tuple)
---------------------------
import jso
n
dict_from_json = json.loads(json_string)
print(dict_from_json)
**********************************************************************
***
Page 222
Python Notes
**************************
III.
Dictionary Comprehensions:
------------------------------
syntax
-
key_expres
sion : The expression for the dictionary keys.
Page 223
Python Notes
Example:
--------
Page 224
Python Notes
squares_dict = {x: x**2 for x in
range(5)}
values = [1, 2, 3]
pr
int(dict_from_comprehension)
**********************************************************************
***
**************************
Page 225
Python Notes
1. sum():
---------
Usage: sum(iter
able, start=0)
------------------------------
Example:
--------
Page 226
Python Notes
m
y_dict = {'a': 1, 'b': 2, 'c': 3}
total = sum(my_dict.values())
print(total) # Output: 6 (1 + 2 + 3)
2. any():
---------
Usage: any(iterable)
---------------
-----
Page 227
Python Notes
Example:
-------
result = any(my_strings)
3. all():
---------
Usage: all(iterable)
Page 228
Python Notes
---------------------
Example:
--------
result = all(my_list)
p
rint(result) # Output: False
4. collections module
---------------------
Page 229
Python Notes
8. Functions
============
I. Introduction
III. Nested/Recursive/Decorator
**********************************************************************
***
**************************
I. Introduction:
----------------
Page 230
Python Notes
3. Readability : Well
-
named functions enhance code
readability and comprehension.
Page 231
Python Notes
Functions vs Methods:
---------------------
Functions:
----------
Page 232
Python Notes
Can be standalone and called independen
tly.
Methods:
--------
Params vs Args:
------
Page 233
Python Notes
---------
Print vs Return:
----------------
Prin
t : Outputs information to the console but doesn't
return a value.
Page 234
Python Notes
Return : Sends a value back to the caller and terminates
the function's execution.
**********************************************************************
***
**************
************
---------------------------------------------------------
User
-
defined Functions:
----------------------
Page 235
Python Notes
return x + y
Built
-
in Functions:
-------------------
**********************************************************************
***
**************************
III. Nested/Recursive/Decorator:
---------------------------
-----
Nested Function:
Page 236
Python Notes
----------------
def outer_function(x):
def inner_function(y):
return x + y
return inner_function
result = outer_function(5)(3)
Recursive Function:
--------------
-----
def factorial(n):
Page 237
Python Notes
if n == 0:
return 1
else:
return n * factorial(n
-
1)
Decorator Function:
-------------------
def decorator(func):
def wrapper():
print("B
efore function execution")
Page 238
Python Notes
func()
return wrapper
@decorator
def my_function():
print("Executing my_function")
my_function()
********************************
*****************************************
**************************
Page 239
Python Notes
----------------------------------------
Positional Arguments:
---------------------
return x + y
result = add(3, 5)
Keyword Arguments:
------------------
Page 240
Python Notes
greet(message="Welcome", name="Python")
Default arguments:
----------
--------
Page 241
Python Notes
# logic implementation
*args
**kwargs:
---------------
Page 242
Python Notes
-
Example:
--------
def va
riable_args(*args, kwargs):
Page 243
Python Notes
**********
***************************************************************
**************************
----------------------------------------
Page 244
Python Notes
disposable function for simple operations.
Syntax
:
-------
'arguments' : Comma
-
separated list of input parameters.
Page 245
Python Notes
**********************************************************************
***
**************************
Note:
-----
Typing Module
https://myp
y.readthedocs.io/en/stable/getting_started.html#installing
-
and
-
running
Page 246
Python Notes
-
mypy
https://docs.python.org/3/library/typing.html#
isinstance
--
Page 247
Python Notes
=====================
I. Introduction
**********************************************************************
***
**************************
I. Introduction:
----------------
Package:
--
------
Page 248
Python Notes
A package is a way of organizing related modules into a single
directory hierarchy.
my_project/
|
--
main_script.py
|
--
my_package/
|
--
__init__.py
Page 249
Python Notes
|
--
module1.py
|
--
module2.py
|
--
subpackage/
|
--
__init__.py
|
--
module3.py
Page 250
Python Notes
Directory:
-------
---
project/
|
--
Page 251
Python Notes
script.py
|
--
module1.py
|
--
module2.py
Module:
-------
Page 252
Python Notes
It serves as a way to organize code and make it reu
sable.
A module contains:
------------------
Page 253
Python Notes
**********************************************************************
***
**************************
----------------------
-----------------------------------
Built
Page 254
Python Notes
-
in modules and packages that come with Python installation.
2. User
-
Defined Packag
es (Custom Packages):
-------------------------------------------
Page 255
Python Notes
3. External
Packages (Third
-
Party Packages):
--------------------------------------------
**********************************************************************
***
**************************
Page 256
Python Notes
-----------------------
fro
m module_name import function_name
import module_name
Page 257
Python Notes
Importing with an alias:
**********************************************************************
**
*
**************************
====================
I. Introduction
**********************************************************************
***
**************************
I. Introduc
Page 258
Python Notes
tion:
----------------
Object
-
oriented programming (OOP) is a programming paradigm that
uses objects,
The key idea behind OOP is to organize code around objects, which
are
instances of classes.
Page 259
Python Notes
world entities.
**********************************************************************
***
**************************
-----------------
-----------------------
Page 260
Python Notes
It defines the attributes (properties) and methods
(functions) that the objects will have.
2. Encapsulation:
-----------------
It allows you to co
ntrol access to the data and protects it from
unauthorized manipulation.
Page 261
Python Notes
3. Inheritance:
---------------
4. Polymorphism:
----------------
Page 262
Python Notes
5. Abstraction:
---------------
Page 263
Python Notes
based on the essential properties and behaviors they share.
*******************************************************
******************
**************************
----------------------
------------------------------
Page 264
Python Notes
Classes and ob
jects provide a way to structure code into smaller,
2. Code Organization:
---------------------
Page 265
Python Notes
------------------------------
Encapsulation helps
------------------------------
Page 266
Python Notes
--------
------------------------
Page 267
Python Notes
=============
===========
I. Class
II. Object
**********************************************************************
***
**************************
I. Class:
-------------------------
It defines a
Page 268
Python Notes
class ClassName:
Page 269
Python Notes
self.parameter1 = p
arameter1
self.parameter2 = parameter2
# Other methods
def method1(self):
Page 270
Python Notes
# Method body
# Method body
Page 271
Python Notes
Constructor method
It is called automatically
when an object is created from the class.
Page 272
Python Notes
Page 273
Python Notes
tance variables (attributes) and other methods within the class.
**********************************************************************
***
**************************
II. Object:
-----------
Page 274
Python Notes
-
class Car:
def
__init__(self, make, model):
Page 275
Python Notes
self.model = model # Instance variable
def my_method(self):
# Method body
print("Executing my_method")
car
1_object = Car("Toyota", "Camry")
print(car1_object.make, car1_object.model)
my_object.my_method()
===========================================
Introduction:
Page 276
Python Notes
-------------
cl
ass attributes and instance variables are both ways to store data
within classes,
1. Class Attributes:
--------------------
Class attributes are variables that are shared among all instances
of
a class.
They are defined outside of any method in the class and are
associated with the class itself rather than any particular instance.
Page 277
Python Notes
They are accessed using the class name rather than instance
references.
They are declared within the class definition but outside of any
methods, typically at the top of the class.
Example:
--------
class Car:
Page 278
Python Notes
um_wheels = 4 # Class attribute
car1 = Car()
car2 = Car()
print(car1.num_wheels) # Output: 4
print(car2.num_wheels) # Output: 4
print(Car.num_wheels) # Output: 4
2. Instance Variables:
-----------
-----------
Page 279
Python Notes
They are defined within methods of the class, typically within the
'__init__ method', using the 'self' keyword.
variables,
and they are not shared among instances.
Example:
--------
class Car:
Page 280
Python Notes
s
elf.make = make # Instance variable
print(car1.make, car1.model)
print(car2.make, car2.model)
Note:
-----
class MyClass:
Page 281
Python Notes
self.instance_variable = instance_variable
def instance_method(self):
print("In
stance variable : ", self.instance_variable)
Page 282
Python Notes
# Calling in
stance methods
obj1.instance_method()
obj2.instance_method()
======================
Python does not have explicit access modifiers like some other
programming languages.
Page 283
Python Notes
1. Private Variables:
---------------------
class PrivateClass:
def __init__(self):
Page 284
Python Notes
def priv_fun(self):
method"
print(self.__private_variable)
priv_obj = PrivateClass()
# print(priv_obj.__private_variable)
# print(PrivateClass().__private_var
iable)
# priv_obj.priv_fun()
2. Protected Variables:
Page 285
Python Notes
-----------------------
outside the
class,
class ProtectedClass:
def __init__(self):
Page 286
Python Notes
def pro_fun(sel
f):
print(self._protected_variable)
pro_obj = ProtectedClass()
print(pro_obj._protected_variable)
print(ProtectedClass()._
protected_variable)
pro_obj.pro_fun()
Page 287
Python Notes
3. Private Method:
------------------
class MyClass:
def __private_method(self):
obj = MyClass()
Page 288
Python Notes
# print(obj.__private_meth
od())
4. Protected Method:
--------------------
of a convention.
Page 289
Python Notes
class MyClass:
def _protected_method(self):
obj = MyClass()
print(obj._protected_method())
5. Class Method:
----------------
Page 290
Python Notes
-
They are often used for operations that involve the class itself
rather than instances.
class MyClass:
@classmethod
def class_method(cls):
print(MyClass.class_metho
d())
Page 291
Python Notes
6. Static Method:
-----------------
They don't have access to the class or instance and are used for
utility functions.
class MyClass:
@staticmethod
def static_method():
Page 292
Python Notes
print(MyClass.static_method())
7. property decorator:
----------------------
Page 293
Python Notes
class Circle:
self.radius = radius
@property
def diameter(self):
return 2 * self.radius
@property
def area(self):
Page 294
Python Notes
my_circle = Circle(5)
print("Diameter:", my_circle.diameter)
print("Area:", my_circle.area)
NOTE:
----
encapsulate
internal implementation details and
Page 295
Python Notes
they are intended for internal use but still allow limited acce
ss.
==========================================
I. Intoduction
II. getattr
III. setattr
IV. delattr
Page 296
Python Notes
V. hasattr
I. Intoduction:
---------------
------------------------------------------------
Purpose
Page 297
Python Notes
-
Arguments :
default (optional) : A v
alue to return if the attribute is not
found.
Example:
--------
class Person:
Page 298
Python Notes
self.name = name
self.age = age
# Accessing non
-
existent attribute with default
Page 299
Python Notes
print(name
) # Output: Alice
print(age) # Output: 30
--------------------------------------------
Arguments :
Page 300
Python Notes
object : The object on which to set the attribute.
Example:
--------
class Person:
self.name = name
Page 301
Python Notes
self.age = age
setattr(person, "age
", 31)
Page 302
Python Notes
------
------------------------------
Arguments :
Example:
--------
Page 303
Python Notes
V. hasattr(object, attribute_name):
-----------------------------------
Arguments :
Page 304
Python Notes
-
Return Value :
Example:
--------
Page 305
Python Notes
13.3 Inheritance:
=================
I. Introduction
II. Us
e of Inheritance
V. super()
**********************************************************************
***
**************************
I. Introduction:
----------------
Page 306
Python Notes
Inheritance is
This allows the derived class to reuse code from the base class and
extend its f
unctionality.
**********************************************************************
***
**************************
-----------------------
Page 307
Python Notes
Code reusability : Inheritance allows you to reuse code by
inheriting attributes
and methods from existing classes.
*******************************************
******************************
**************************
--------------------------
base
classes.
Page 308
Python Notes
3. Multilevel Inheritance : A derived class is created from another
derived class.
**********************************************************************
***
**************************
----------------------------------
in the hierarchy of
classes.
Page 309
Python Notes
Use of MRO:
-----------
**********************************************************************
***
**************************
V. super():
Page 310
Python Notes
-----------
Uses of super():
---------------
It allows
you to invoke methods of the superclass without
explicitly naming them.
Page 311
Python Notes
10.4 Polymorphism
=================
I. Introduction
I
V. Constructor overloading
**********************************************************************
***
**************************
I. Introduction:
----------------
Page 312
Python Notes
-
to t
he same method call in different ways.
**********************************************************************
***
**************************
---------------------
Page 313
Python Notes
**********************************************************************
***
**************************
------------------------
Page 314
Python Notes
Page 315
Python Notes
and types of arguments accepted.
Example:
--------
def calculate
_area(length, width=1): # Default width
argument
area_rectangle = calculate_area(5, 3)
Page 316
Python Notes
print(area_rectangle) # Output: 15
area_s
quare = calculate_area(4)
print(area_square) # Output: 4
**********************************************************************
***
**************************
----------------------------
Page 317
Python Notes
parameter lists within a class.
1. Default Arguments:
---------------------
T
his allows the constructor to be called with varying
Page 318
Python Notes
argument counts.
Example:
--------
class Person:
Page 319
Python Notes
self.name = name
self.age = age
# Creati
ng objects with different argument
patterns
Page 320
Python Notes
person2 = Person("Bob", 35) # Specifies age
--------------------------------------------
Use *arg
s to collect extra positional arguments in a
tuple.
Page 321
Python Notes
Example:
-------
class Product:
self.name = name
Page 322
Python Notes
self.args = args
self.kwargs = kwargs
product1 = Product("Book")
Page 323
Python Notes
brand="Dell")
10.5 Abstarction:
=================
I. Introduction
**********************************************************************
***
**************************
I. Introduction:
----------------
Page 324
Python Notes
-
1. Classes as Blueprints:
Page 325
Python Notes
2. Encapsulation:
Abst
raction allows us to encapsulate complex functionality
within methods,
Page 326
Python Notes
polymorphism, which are key features of OOP.
that must be
implemented by concrete subclasses.
Page 327
Python Notes
===========
============
I. Introduction
V. raise
Page 328
Python Notes
**********************************************************************
***
**************************
I. Intr
oduction:
----------------
Page 329
Python Notes
Page 330
Python Notes
Page 331
Python Notes
because
they do not result in any
error messages or exceptions.
Page 332
Python Notes
behavior of the program.
exceptio
nal situations that occur during the execution of a
Python program.
**********************************************************************
Page 333
Python Notes
***
**************************
----------------------------------
Error Detection:
---------
---------
Page 334
Python Notes
-
Graceful Failure:
------
-------------
program.
Page 335
Python Notes
-
Error Reporting:
------------------
-----------------------
Page 336
Python Notes
Resource Management:
----------------------
Page 337
Python Notes
------------------------
cause of errors
Page 338
Python Notes
and helping to trace the execution flow.
**********************************************************************
***
**************************
-----------------------------------
try block : This block is used to enclose the code that might
raise an exception.
Page 339
Python Notes
Page 340
Python Notes
It is ge
nerally used to perform cleanup actions,
such as closing files or releasing resources.
Example:
-------
try:
Page 341
Python Notes
result = 10 / x
except Val
ueError:
Page 342
Python Notes
except ZeroDivisionError:
print("Cannot divide by
zero.")
Page 343
Python Notes
else:
finally:
Page 344
Python Notes
****************
*********************************************************
**************************
------------------------
BaseException
ChildProcessError
nnectionResetError
ror
ResourceWarning
**********************************************************************
***
************
**************
V. raise:
Page 345
Python Notes
---------
Page 346
Python Notes
-
syntax :
--------
raise [ExceptionClassName(args)]
=======================
I. Introduction
Page 347
Python Notes
****************************************************************
*********
**************************
I. Introduction:
----------------
Page 348
Python Notes
syntax
-
filename : The name (or path) of the file you want to open.
-----------------
Page 349
Python Notes
'w'
'a' : Open the file for appending. New data will be written to
the end of the file.
'r+': Open the file for both reading and writing (from the
beginning).
'w+':
Open the file for both reading and writing. Existing
content will be overwritten!
Page 350
Python Notes
'x' : Opens the file for exclusive creation, failing if the file
already exists.
Binary Modes (
'b'):
--------------------
'wb': Open the file for writing in binary mode. Existing content
will be overwritten.
'ab': Open the file for appending in binary mode. New data will
Page 351
Python Notes
'r+b' or 'rb+': Open the file for both reading and writing in
binary mode (from the beginning).
'w+b' or 'wb+': Open the file for both reading and writing in
binary mode. Existing content will be overwr
itten.
'a+b' or 'ab+': Open the file for both reading and appending in
binary mode.
Other Modes:
------------
Page 352
Python Notes
1. Opening a F
ile:
------------------
-----------------------
Page 353
Python Notes
content = file.read()
# Read a
single line
line = file.readline()
lines = file.readlines()
3. Writing to a File:
---------------------
Page 354
Python Notes
n")
-----------------------------------
Remember: Always
**********************************************************************
***
**************************
-----------------
---------------------
Page 355
Python Notes
syntax:
---------
with context_manag
er_expression as variable_name:
Page 356
Python Notes
Built
-
in functions like open() for
file handling.
Page 357
Python Notes
content = file.read()
********
*****************************************************************
**************************
--------------------
File operations can fail due to various reasons (e.g., file not
found, permission issues).
It's essenti
al to handle these exceptions using try...except
blocks:
try:
Page 358
Python Notes
content = file.read()
except FileNotFoundError:
Note:
-----
os module
shutil module
Page 359
Python Notes
csv files
pdf files
image files
excel files
Page 360