0% found this document useful (0 votes)
4 views

Readable_Python_Notes

Python is a high-level, interpreted programming language known for its simplicity and versatility, supporting multiple paradigms such as procedural, object-oriented, and functional programming. Key features include clear syntax, extensive libraries, dynamic typing, and a large community, while disadvantages include performance issues and higher memory consumption. Python is widely used in various domains including web development, data science, artificial intelligence, and automation.

Uploaded by

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

Readable_Python_Notes

Python is a high-level, interpreted programming language known for its simplicity and versatility, supporting multiple paradigms such as procedural, object-oriented, and functional programming. Key features include clear syntax, extensive libraries, dynamic typing, and a large community, while disadvantages include performance issues and higher memory consumption. Python is widely used in various domains including web development, data science, artificial intelligence, and automation.

Uploaded by

ashish bujarge
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 360

Python Notes

I. Introduction

II. Key Features of Python

III. Disadvantages of python

**********************************************************************
***
**************************

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.

It supports multiple programming paradigms, including procedural,


object
-
oriented, and functional programmi
ng.

**********************************************************************
***
**************************

II. Key Features of Python:

---------------------------

1. Clear and Readable Syntax:

-----------------------------

Python's syn
tax is designed to be clear and readable, making it an

Page 2
Python Notes
ideal language

for beginners and experienced developers alike.

The use of indentation rather than braces enhances code


readability.

2. Interpreted Language:

------------------
------

Python is an interpreted language, which means that the Python code


is executed line by line,

facilitating rapid development and debugging. There is no need for


a separate compilation step.

3. Versatility and Portability:

--

Page 3
Python Notes
-----------------------------

Python is a versatile language used in various domains, including


web development, data science,

artificial intelligence, machine learning, automation, and more.

It is supported on different platforms, i


ncluding Windows, macOS,
and Linux.

4. Extensive Standard Library:

------------------------------

Python comes with a comprehensive standard library that includes


modules and packages for various tasks,

such as file handling, netwo


rking, web development, and more.

This eliminates the need to write code from scratch for common

Page 4
Python Notes
functionalities.

5. Dynamic Typing:

------------------

Python is dynamically typed, meaning that variable types are


determined at runt
ime.

This flexibility allows for easier code maintenance and faster


development.

6. Large Community and Ecosystem:

---------------------------------

Python has a vibrant and active community that contributes to its


growth.

The availability of numerous third


-
party libraries and frameworks,
such as Django, Flask,

Page 5
Python Notes

NumPy, and TensorFlow, enhances the Python ecosystem and supports


various application development needs.

7. Object
-
Oriented Programming:

-----------
--------------------

Python supports object


-
oriented programming principles, allowing
developers to structure their code

using classes and objects, promoting code reusability and


maintainability.

8. Open Source:

---------------

Page 6
Python Notes

Python is an open
-
source language, encouraging collaboration and
allowing developers to modify and

distribute their own versions. This open nature contributes to the


continuous improvement of the language.

***********************************
**************************************
**************************

III. Disadvantages of python:

------------------------------

1. Performance:

---------------

Page 7
Python Notes
Python is an interpreted language, and while this provides
flexibility and ea
se of development,

it can lead to slower performance compared to compiled languages


like C or C++.

2. Global Interpreter Lock (GIL):

---------------------------------

The Global Interpreter Lock (GIL) in CPython (the default P


ython
interpreter)

allows only one thread to execute Python bytecode at a time.

This can limit the parallelism in multithreaded programs,


impacting performance in certain scenarios.

Page 8
Python Notes
3. Mobile Development:

---------------------
-

Python is not as commonly used for mobile app development as


languages like Java (for Android) or Swift (for iOS).

4. Memory Consumption:

----------------------

Python's memory consumption can be higher compared to some other


languages.

This may be a concern in environments with strict memory


constraints.

2. Different Programming Types:

===============================

Page 9
Python Notes

a. Procedural programming

-------------------------

def greet(name):

print("Hello, " + name + "!")

def calculate_sum(a, b):

return a + b

# Main program

user_name = input("Enter your name: ")

Page 10
Python Notes
greet(user_name)

num1 = int(input("Enter a number: "))

num2 = int(input("Enter another number: "))

result = calculate_sum(num1, num2)

print("Sum:", result)

b. Functional programming example in Python

-------------------------------------------

# 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)

print("Squared Numbers:", squared_numbers)

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!")

# Creating an instance of the Dog class

my_dog = Dog("Buddy", 3)

# Accessing object properties and methods

print(f"{my_dog.name} is {my_dog.age} years old.")

my_dog.bark()

Page 13
Python Notes

1.2 Areas of Applications:

============
==============

1. Web Development:

-------------------

Frameworks like Django and Flask are widely used for building web
applications.

Libraries such as BeautifulSoup and requests are employed for web


scraping.

Selenium

is utilized for browser automation.

Page 14
Python Notes

2. Data Science and Machine Learning:

-------------------------------------

Popular libraries like NumPy, Pandas, Matplotlib, and Seaborn

are used for data manipulation, analysis, and visual


ization.

Scikit
-
learn is a powerful library for machine learning tasks.

TensorFlow and PyTorch are widely used for deep learning.

Page 15
Python Notes
3. Artificial Intelligence:

---------------------------

Python is extensively used in AI


applications for natural
language processing (NLTK, SpaCy),

computer vision (OpenCV), and reinforcement learning.

4. Scientific Computing:

------------------------

Python is utilized in scientific research for numerical and

scientific computing with libraries like SciPy and SymPy.

Page 16
Python Notes

5. Desktop GUI Applications:

----------------------------

Libraries like Tkinter, PyQt, and Kivy are used for developing

desktop graphical user interface (GUI) ap


plications.

6. Network Programming:

-----------------------

Python's socket library and frameworks like Twisted are used for

network programming and developing networking applications.

Page 17
Python Notes

7. Automation and Scripting:

---
-------------------------

Python is widely used for automating repetitive tasks and


scripting, thanks to its simplicity and readability.

8. Cybersecurity:

-----------------

Python is employed for tasks such as penetration testi


ng,
vulnerability scanning, and building security tools.

9. Cloud Computing:

Page 18
Python Notes
-------------------

Python is commonly used in cloud environments, and there are


libraries and SDKs for

interacting with services provided by major


cloud providers like
AWS, Azure, and Google Cloud.

10. DevOps:

-----------

Python is widely used for automation and scripting in the DevOps


domain, for tasks such as

configuration management, deployment automation, and monito


ring.

Page 19
Python Notes

2.0 Tokens:

===========

I. Introduction

II. Different types of tokens

**********************************************************************
***
**************************

I. Introduction:

----------------

Token is the smalle


st unit in a program.

The Python interpreter uses tokens to recognize and parse the

Page 20
Python Notes
source code.

The interpreter uses these tokens to understand and execute the


code provided.

There are several types of tokens in Python, each s


erving a
different purpose.

**********************************************************************
***
**************************

II. Different types of tokens:

------------------------------

a. Keywords:

------------

Page 21
Python Notes

Keywords are res


erved words that have a special meaning in
Python.

They cannot be used as variable names.

Examples `if`, `else`, `while`, `for`, `def`, `class`, etc.

b. Identifiers:

---------------

Identifiers are used as names f


or variables, functions, classes,
etc.

Page 22
Python Notes

An identifier must start with a letter or an underscore, followed


by letters, digits, or underscores.

variable_name = 42

_name = "python"

c. Literals:

------------

Literals are constant values used in Python.

There are different types of literals, such as numeric literals,


string literals, and boolean literals.

Page 23
Python Notes

integer_literal = 42

string_literal = "Hello, World!"

boolean_literal = True

d. Operators:

-------------

Operators perform operations on variables and values.

Examples: arithmetic operators (`+`, `


-
`, ``, `/`)

comparison operators (`==`, `!=

Page 24
Python Notes
`, `<`, `>`)

logical operators (`and`, `or`, `not`).

e. Delimiters:

--------------

Delimiters are characters used to define the structure of the


code,

such as parentheses `()`, brackets `[]`, and


curly braces `{}`.

my_list = [1, 2, 3]

Page 25
Python Notes

f. Comments:

------------

Comments are annotations in the code that are ignored by the


interpreter.

They start with the `#` symbol and are used for documentation and
cl
arification.

# This is a comment

g. Strings:

-----------

Page 26
Python Notes

Strings are sequences of characters enclosed in single (`'`) or


double (`"`) quotes or triple qoutes (`'''` or `"""`).

message = "Hello, Pytho


n!"

h. Whitespace:

--------------

Whitespace includes spaces, tabs, and line breaks.

It is used to separate tokens and make the code readable.

Page 27
Python Notes

def my_function():

print("Hello")

2.1.

Variables:

===============

I. Introduction

II. Rules for naming a variable

III. Keywords

IV. LEGB Rule

**********************************************************************
***

Page 28
Python Notes
**************************

I. Introduction:

----------------

It is a reserved memory location that stores and manipulates


data.

Variables are entities of a program that holds a value.

Variable is essentially a name assigned to a value or an object,

allowing you to reference and work with that va


lue or object
throughout your program.

Page 29
Python Notes

Variables should be meaniningful for readability.

Assign a value to a variable using the assignment operator (=)

x = 10

name = "Python"

To display the value of a variable use th


e print function

name = "Python"

print(name)

Page 30
Python Notes

We can change the value of a variable by assigning a new value to


it

x = 10

x = 20

x = "Python"

x = [4, 7, 9]

We can assign multiple variables in


a single line:

x, y, z = 10, "Python", [2, 'hello', 5.6]

Page 31
Python Notes

**********************************************************************
***
**************************

II. Rules for naming a variable:

--------------------------------

A variable na
me must begin with a letter of the alphabet(a
-
z, A
-
Z) or an underscore(_)

The first character can be followed by letters, numbers or


underscores.

Python variable names are case sensitive.

Page 32
Python Notes
-

Reserved words cannot be used as variable names.

| Case Name | Example | Use Case

|
----------------------
|
---------------
|
-------------------------------
---------------------------------------
---------------------------
|

| Snake Case | user_name | Variables, Function names


(e.g., def calculate_total():)
|

Page 33
Python Notes
| Pascal Case | UserName | Class names (e.g., class
UserProfile:)

| Screaming Snake Case | USER_NAME | Constants (e.g.,


MAX_CONNECTIONS = 100)

| Upper Case | USERNAME | Similar to Sc


reaming Snake
Case, used for constants but less common in multi
-
word constants. |

| Flat Case | username | Used for variables, typically

for single
-
word names. |

**************************
***********************************************
**************************

III. Keywords:

Page 34
Python Notes

--------------

keywords are reserved words that have special meanings and cannot be
used as identifiers

(such as variable names, function names, or clas


s names).

These keywords are an integral part of the language's syntax and


play specific roles

in defining the structure and logic of Python code.

Python has a set of standard keywords, and their usage is predefined


by the language.

Page 35
Python Notes
Keywords cannot be used as variable names, as they are already
reserved.

There are 35 keywords in Python.

False class finally is return

None continue for lambda try

True def

from nonlocal while

and del global not with

as elif if or yield

assert else import pass break

except in raise async await

Page 36
Python Notes

**********************************************************************
***
**************************

IV. LEGB Rule:

--------------

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.

Python searches for variable names in LEGB order

Page 37
Python Notes
-

To avoid naming conflicts and ensuring that variables are accessed in


the intended scope.

1. Local Scope (L):

-------------------

Variables defined within a function are in the local scope.

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)

my_function() # Accessing local_variable is valid here

2. Enclosing Scope (E):

-----------------------

Refers to the scope of the enclosing function (for nested


functions).

Page 39
Python Notes
-

If a variable is not found in the


local scope, Python looks in the
enclosing scope.

Example:

python

def outer_function():

outer_variable = 20

def inner_function():

print(outer_variable) # Accessing outer_variabl

Page 40
Python Notes
e from the
enclosing scope

inner_function()

outer_function()

3. Global Scope (G):

--------------------

Variables defined at the top level of a module or script are in


the global scope.

Global variabl
es are accessible throughout the module or script.

Page 41
Python Notes

Example:

python

global_variable = 30

def another_function():

print(global_variable) # Accessing global_variable from the


global scope

another_func
tion()

4. Built
-
in Scope (B):

Page 42
Python Notes

----------------------

This is the broadest scope and includes built


-
in names and
functions provided by Python (e.g., print, len, sum).

Variables in the built


-
in scope are accessible from any p
art of
the program.

Example:

python

print(len([1, 2, 3])) # Accessing the built

Page 43
Python Notes
-
in function len()

2.2 Memory Management in Python:

================================

I. Introduction

II. Key Features

III. Garba
ge Collection in Python

**********************************************************************
***
**************************

I. Introduction:

----------------

Page 44
Python Notes

Memory management in Python involves the allocation and deallocation


of

memory

space for objects during program execution.

Python uses a private heap space to manage memory, and the Python
memory manager

handles the dynamic storage needed by the program.

**************************************************************
***********
**************************

II. Key Features:

-----------------

Page 45
Python Notes

a. Memory Allocation:

---------------------

When an object is created in Python, the memory manager allocates


space for that object on the heap.

The si
ze of the memory block allocated depends on the type and
structure of the object.

b. Reference Counting:

----------------------

Python uses a reference counting mechanism to keep track of the


number of references to each object.

Each object has a reference count associated with it, and when
the count drops to zero,

Page 46
Python Notes

the memory occupied by the object can be reclaimed.

c. Garbage Collection:

----------------------

While reference counting is a fundament


al part of memory
management in Python,

it may not handle cyclic references (when objects reference each


other in a cycle).

To address this, Python employs a garbage collector to identify


and collect unreachable objects.

****
*********************************************************************
**************************

Page 47
Python Notes

III. Garbage Collection in Python:

----------------------------------

Python's garbage collector is responsible for reclaiming memory


occupied by obje
cts that are no longer in use.

The garbage collection process is automatic and transparent to the


programmer.

a. Cyclic Garbage Collection:

-----------------------------

Python uses a cyclic garbage collector that can ide


ntify and

Page 48
Python Notes
collect cyclic references,

preventing memory leaks that might occur if cyclic references


were not properly handled.

b. Generational Garbage Collection:

-----------------------------------

Python's garbage
collector uses a generational approach,

dividing objects into three generations: young, middle


-
aged,
and old.

New objects are initially allocated in the young generation,


and if they survive a

Page 49
Python Notes

garbage collection cycle


, they are promoted to older
generations.

c. Reference Counting + Garbage Collection:

-------------------------------------------

Python's memory management combines reference counting with


garbage collection.

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:

---------------

Python provides the `gc` module, which allows f


or manual
control and fine
-
tuning of the garbage collection process.

While automatic garbage collection is generally effective, the


`gc` module can be used to trigger collections,

disable collections, or obtain information about th


e garbage
collector's behavior.

3. Operators:

=============

Page 51
Python Notes

I. Introduction

II. Different Operators Explanation

III. Operators precedence

**********************************************************************
***
**************************

I. Introduction

----------------

Operators in Python are special symbols or keywords that


facilitate operations on variables and values.

They allow you to manipulate data, perform mathematical

Page 52
Python Notes
calculations, compare values, logical operations,

bitwise operations and control the flow of your program.

Python operators are divided into several types, each serves a


distinct purpose.

Arithmetic Operators

Comparison Operators

Logical Operators

Page 53
Python Notes
Membership operators

Assig
nment operators

Identity operators

Bitwise Operators

**********************************************************************
***
**************************

II. Different Operators Explanation

-----------------------------------

a. Arithmetic

Page 54
Python Notes
Operators:

------------------------

Arithmetic operators are used for mathematical


calculations.

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

print("Floor Division:", result)

b. Compari
son Operators:

------------------------

Page 62
Python Notes
-

Comparison operators are used to compare values and returns


boolean values

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)

3. Greater than ( > )

---------------------

x = 10

y = 5

Page 65
Python Notes
print(x > y)

4. Less than ( < )

------------------

x = 10

y = 5

print(x < y)

Page 66
Python Notes

5. Greater than or equal to ( >= )

----------------------------------

x = 10

y = 5

print(x >= y) True

Page 67
Python Notes

6. Less than or equal to ( <= )

-------------------------------

x = 10

y = 5

print(x <= y)

Page 68
Python Notes
c
. Logical Operators:

---------------------

Logical operators perform logical operations on boolean


values.

1. Logical AND ( and )

----------------------

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)

3. Logical NOT ( not )

----------------------

p = True

q = False

print(not p)

Page 71
Python Notes

Table:

------

| p | q | p AND q | p OR q |

|
-------
|
-------
|
---------
|
--------
|

Page 72
Python Notes

| True | True | True | True |

| True | False | False | True |

| False | True | False | True |

| False | False | False | False |

d. Membership Operators:

-------------
-----------

Page 73
Python Notes

Membership operators test for membership in a sequence.

1. In ( in )

------------

my_list = [1, 2, 3, 4, 5]

print(3 in my_list) True

Page 74
Python Notes

2. Not in ( not in )

--------------------

my_list = [1, 2, 3, 4,

5]

print(6 not in my_list) True

e. Assignment Operators:

------------------------

Page 75
Python Notes

Assignment operators are used to assign values to


variables.

1. Add and assign

-----------------

x = 10

x += 5 # Equivalent to x =
x + 5

2. Subtract and assign

Page 76
Python Notes

----------------------

x = 5

x
-
= 3 # Equivalent to x = x
-

3. Multiply and assign

Page 77
Python Notes
----------------------

x = 4

x *= 2 # Equivalent to x = x * 2

4. Divide and assign

-------
-------------

x = 5

Page 78
Python Notes

x /= 4 # Equivalent to x = x / 4

print(x)

f. Identity Operators:

----------------------

Identity operators are used to compare the objects, not if


they are equal,

but if they are actually the same


object.

Page 79
Python Notes

Checks if two variables are referring to the exact same


object in the computer's memory,

not just objects that happen to look the same.

The 'is' operator checks for the identity of the objects,


not just their content or appearance.

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:

---------------------

Bitwise operators perform operations on binary


representations of integers
.

1. Bitwise AND ( & )

--------------

Page 82
Python Notes

p = 5 binary: 0101

q = 3 binary: 0011

0001

print(p & q)

Expl: For each corresponding pair of bits, if both are


1, the result i
s 1; otherwise, it's 0.

Page 83
Python Notes

----

2. Bitwise OR ( | )

-------------------

p = 5 binary: 0101

q = 3 binary: 0011

print(p | q) 0111

Page 84
Python Notes

Expl: For each corresponding pair of bits, if at least


one is 1, the result is 1.

----
-

3. Bitwise XOR ( ^ )

--------------------

p = 5 binary: 0101

Page 85
Python Notes

q = 3 binary: 0011

print(p ^ q)

Expl: For each corresponding pair of bits, the result is


1 if the bits are different; otherwise, it's 0.

-----

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.

'is' is for reference equality. It's used to know if two


references refer (or point) to the s
ame object,

i.e if they're identical.

Two objects are identical if they have the same memory


address.

Page 87
Python Notes

is statement is like checking id(a) == id(b)

Consider mutable and immutable

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)

****************
*********************************************************
**************************

III. Operators precedence

-------------------------

Operator precedence determines the order in which operators are


evaluated in an expression.

Page 90
Python Notes

It defines th
e hierarchy of operators, ensuring that some
operators are evaluated before others.

Parentheses : ()

Exponentiation : **

Unary plus and minus : +x,


-
x

Multiplicatio
n, division, and remainder : *, /, //, %

Page 91
Python Notes

Addition and subtraction : +,


-

Bitwise shifts : <<, >>

Bitwise AND : &

Bitwise XOR : ^

Bitwise OR

: |

Comparison operators : <, <=, >, >=,


==, !=

Membership operators : in, not in

Page 92
Python Notes

Identity operators : is, is not

Logical NOT : not

Logical AND : and

Logical OR : or

Example:

--------

result = 6 + 7 * 4 ** 2
-

Page 93
Python Notes

(8 % 3)

Exponentiation : 4 ** 2 evaluates to 16.

Multiplication : 7 * 16 evaluates to 112.

Addition : 6 + 112 evaluates to 118.

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

II. Input function

III. Data Types

IV. Data Structures

V. Type Conversions

VI. Range

**********************************************************************
***
**************************

I. Requirement:

---------------

Page 95
Python Notes

Entity :

Noun Form

State : Datatype/Structures

Behaviour : Operation : CRUD

Validations : Client/Server

Business logic : operators, DM, Loops

x = 10 # perform CRUD operations

# CRUD

# x = 10

# print(x)

Page 96
Python Notes

# x += 5

# del x

# print()

# type()

# id()

# input()

**********************************************************************
***
**************************

II. Input function:

------------------

Page 97
Python Notes

Basic input

example

-------------------

user_input = input("Enter your name: ")

print(user_input)

Input for numerical values

--------------------------

user_age = int(input("Enter age: "))

print("You are " + str(age) + " years old.")

print(type(user_age))

Page 98
Python Notes
Handling multiple inputs

------------------------

name = input("Enter your name: ")

age = int(input("Enter your age: "))

print("Hello, " + name + "! You are " + str(age) + " years old.")

*******************
******************************************************
**************************

III. Data Types:

----------------

1. Numeric Types:

----------------

Page 99
Python Notes

int : Integer type, representing integer numbers.

float : Floating
-
p
oint type, representing decimal numbers.

complex : Complex number type, with real and imaginary parts.

Example:

x = 5 int

y = 3.14 float

Page 100
Python Notes
z = 2 + 3j complex

2. Text Type:

--
------------

str: String type, representing sequences of characters.

Example:

text = "Hello"

3. Sequence Types:

Page 101
Python Notes

------------------

list : Ordered, mutable sequence.

tuple : Ordered, immu


table sequence.

range : Represents a range of numbers.

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,

mutable collection of unique elements.

frozenset : Unordered, immutable collection of unique elements.

Example:

my_set = {1, 2, 3}

Page 103
Python Notes

my_frozenset = frozenset({4, 5, 6})

5. Mapping Type:

-------------
---

dict: A collection of key


-
value pairs.

Example:

my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}

Page 104
Python Notes

6. Boolean Type:

----------------

bool: Represents Boolean values (True or False).

Example:

is_true = True

is_false = False

7. None Type:

Page 105
Python Notes
-------------

None: Represents the absence of a value or a null value.

Example:

no_value = None

*****************
********************************************************
**************************

IV. Data Structures:

--------------------

1. Lists:

Page 106
Python Notes

---------

Ordered, mutable sequences.

Elements can be added, removed, or modified.

Example:

my_list = [1, 2, 3, 4, 5]

2. Tuples:

----------

Ordered, immutable sequences.

Page 107
Python Notes

Elements cannot be modified once defined.

Example:

my_tuple = (1, 2, 3, 4, 5)

3. Sets:

--------

Unordered, mutable collections of unique elements.

Page 108
Python Notes

Useful for performing set operations.

Example:

my_set = {1, 2, 3, 4, 5}

4. Dictionaries:

----------------

Orderd(from 3.7 version) collections of key


-
value pairs.

Page 109
Python Notes
Allows efficient lookup based on keys.

Example:

my_dict = {'name': 'Alice', 'age': 30, 'city': 'London'}

print(my_dict['name'])

print(my_dict.get('name
'))

5. Strings:

-----------

Page 110
Python Notes
Sequences of characters. Immutable.

Example:

my_string = "Hello, World!"

6. Arrays (from array module):

------------------------------

Homogeneous,
fixed
-
size sequences. Elements must be of the same
type.

Page 111
Python Notes
Example:

from array import array

my_array = array('i', [1, 2, 3, 4, 5]) 'i' denotes integer type

***************************************************************
**********
**************************

V. Type Conversions:

--------------------

1. Integer to Float:

--------------------

You can convert an integer to a float using the float() function:

Page 112
Python Notes
integer_value = 5

float_va
lue = float(integer_value)

2. String to Integer or Float:

-------------------------------

To convert a string to an integer or float, you can use int() or


float():

string_number = "10"

integer_number = int(s
tring_number)

float_number = float(string_number)

Page 113
Python Notes

Note that if the string contains non


-
numeric characters, a
ValueError will be raised.

3. Number to String:

---------------------

You can convert a number to a stri


ng using the str() function:

number = 42

string_representation = str(number)

Page 114
Python Notes

4. String to Boolean:

---------------------

You can convert a string to a boolean using conditions.

For example, an empty


string or "False" (case
-
insensitive) will be
converted to False,

and any other non


-
empty string will be converted to True:

tr_string = "True"

Page 115
Python Notes

boolean_value = bool(tr_string)

5. Boolean to String:

----------
-----------

You can convert a boolean to a string using str():

boolean_value = True

string_representation = str(boolean_value)

6. Float to Integer:

--------------------

You can convert a float to an i

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:

----------

# for each in range(1, 10): # range(start, stop, step)

# # start(optional) : if start is not


provided then starts from zero

Page 117
Python Notes

# # stop(manda
tory) : if n is the stop
provided then upto n
-
1

# # step(optional) : how many places to


skip

# print(each)

**********************************************************************
***
**************************

5. Decision Making:

===================

I. Introduction

Page 118
Python Notes

II. 'if' 'elif' 'else'

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.

The basic structure of a conditional statement involves


checking a condition and

executing a specific block of code if the condition is true.

***************************
**********************************************
**************************

II. 'if' 'elif' 'else':

-----------------------

1. if Statement:

----------------

The if statement is used to execute a block of code only if a

Page 120
Python Notes
specified cond
ition is true.

if condition:

Execute this block of code if condition is true

2. elif Statement:

------------------

The elif statement allows you to check multiple conditions


after the initial if statem
ent.

It is short for "else if" and is used to execute a block of

Page 121
Python Notes
code if the preceding conditions

are false and the current condition is true.

Can have multiple elif statements to check for additional


conditions.

if condition1:

Execute this block of code if condition1 is true

elif condition2:

Execute this block of code if condition1 is false and


condition2 is true

Page 122
Python Notes

3. else Statement:

-----
-------------

The else statement is used to execute a block of code if none


of the preceding conditions

in the 'if' and 'elif' statements are true.

It is optional and is typically used as a fallback when no


other conditio
n is met.

if condition1:

Execute this block of code if condition1 is true

Page 123
Python Notes

elif condition2:

Execute this block of code if condition1 is false and


condition2 is true

else:

Execute this block of code if neither condition1 nor


condition2 is true

**********************************************************************
***
**************************

III. Examples:

--------------

Req: Check if a number is positi


ve, negative, or zero

num = int(input("Enter number : "))

Page 124
Python Notes

if num > 0:

print("Number is positive.")

elif num < 0:

print("Number is negative.")

else:

print("Number is zero.")

Req: weekday weekend

if weekday goto office if weekend party, trip, movie

if party house party outdoor party

Page 125
Python Notes

if trip outstation trip or local trip

if movie theatre or ott

6. LOOPS, Co
ntrol Statements:

=============================

I. Introduction

II. for loop

Page 126
Python Notes

III. while loop

IV. Control Statements

**********************************************************************
***
**************************

I. Introduction:

------
----------

Loops are used to repeatedly execute a block of code until


a specified condition is met.

Loops are essential for automating repetitive tasks and


iterating over collections of data.

Page 127
Python Notes

Loops are required for

Automation

: Loops help automate repetitive


tasks by executing a block of code

multiple times without the need to


write the same code over and over.

Iteration : Loops are crucial for iterating


over elements in a sequence or

Page 128
Python Notes

processing elements in a
collection one by one.

Dynamic Execution : Loops allow for dynamic execution


based on changing conditions,

providing flexibility in program


control flow.

Loops can

be applied to various data types and data


structures:

Page 129
Python Notes

Lists : Iterating over elements of a list

Strings : Processing characters of a string

Tuples : Iterating over elements of a tuple

Ranges : Genera
ting a sequence of numbers
using the range function

Page 130
Python Notes
-

Dictionaries : Iterating over keys, values, or items


in a dictionary

Sets : Looping through elements in a set

Files : Reading lines from a file

Custom Objects
: If an object supports iteration (by
implementing __iter__ and __next__ methods)

Page 131
Python Notes
-

There are two main types of loops in Python

for loops

while loops

**********************************************************************
***
**********
****************

II. for loop

------------

Page 132
Python Notes

'for' loop is used to iterate over a sequence (such as a


list, tuple, string, range)

or set or dictionary and execute a block of code for each


item in the sequence.

for iterating over element


s in sequences or set or
dictionary keys,

'for' loops are often more concise and expressive

Page 133
Python Notes
Example:

--------

for each in sequence/set:

# code to be executed for each item in the


sequence

fruits = ["apple", "banan

Page 134
Python Notes
a", "cherry"]

for fruit in fruits:

print(fruit)

**********************************************************************
***
**************************

III. while loop

----------------

while loop is used to repeatedly execute a b


lock of code as
long as a specified condition is true.

Page 135
Python Notes

while loops are better suited for situations where

you don't know the exact number of iterations beforehand,

and the loop continues as long as a specified condition is


true

while
loop might be more appropriate on below scenarios

Unknown Iteration Count : When you don't know in

Page 136
Python Notes
advance how many iterations are needed

Conditional Iteration : If you need to iterate based


on a condition other than

the natural order of


elements in a sequence

Example:

Page 137
Python Notes

--------

while condition:

# code to be executed while the condition is true

# Factorial Calculation

Page 138
Python Notes

#
---------
--------------

num = int(input("Enter a number: "))

given_num = num

result = 1

Page 139
Python Notes

while num > 1:

result *= num

num
-
= 1

print(f"Factorial of given number


{given_num} is:", result)

Page 140
Python Notes

# Guessing
Game with Break

#
-------------------------

secret_number = 3

Page 141
Python Notes

while True:

guess = int(input("Guess the number b/w


0 to 9: "))

if guess == secret_number:

print("Congratulations! You guessed


the correct
number.")

Page 142
Python Notes

break

else:

print("Try again.")

# Fibonacci

#
-----------

Page 143
Python Notes

n = int(input("Enter the number of terms:


"))

a, b = 0, 1

count = 0

while count < n:

Page 144
Python Notes

print(a)

nth = a + b

a = b

Page 145
Python Notes
b = nth

count += 1

**********************************************************************
***
**************************

IV. Control Statements:

-----------------------

break, continue, and pass


are special control statements
that are used within loops to modify their behavior.

Page 146
Python Notes

They provide additional flexibility and control over the


flow of execution in loops.

break Statement:

----------------

The break statement is use


d to exit a loop
prematurely based on when a specific condition is met.

Breaking out of a loop when a target value is


found or when further iterations are unnecessary.

Page 147
Python Notes

Avoiding the execution of certain code for


particular cases

Examp
le:

--------

Page 148
Python Notes

for i in range(5):

if i == 3:

break

print(i)

Page 149
Python Notes
continue Statement:

-------------------

The continue statement is used to skip specific


iterations based on a condition.

It

allows to skip certain iterations based on


when a specific condition is met.

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:

---------------

The pass statement is a no


-

Page 152
Python Notes
op statement, meaning
it does nothing.

When a syntactically required statement is


needed but no action is necessary.

Placeholder for future code implementation.

Ensuring that an empty block of code is


syntactically valid.

Page 153
Python Notes

Example:

--------

for i in range(3):

if i == 1:

Page 154
Python Notes

pass

else:

print(i
)

7.0.1 Datastructures in Detail


-

String:

Page 155
Python Notes

========================================

String:

------

A string is a sequence of characters.

Strings are treated as immutable.

****************************************************
*********************
**************************

Memory Allocation in Strings:

-----------------------------

Page 156
Python Notes
-

Each character typically requires a certain number of bytes

(e.g., ASCII characters usually take 1 byte per character, while


U
nicode characters might take more).

# https://python
-
reference.readthedocs.io/en/latest/docs/str/ASCII.html

# https://home.unicode.org/

# https://en.wikipedia.org/wiki/List_of_Unicode_characters

Memory allocation for stri


ngs depends on the character encoding
used (e.g., ASCII, Unicode).

Page 157
Python Notes

ASCII(128):

ASCII (American Standard Code for Information Interchange):

Uses 7 or 8 bits to represent each character.

Commonly used in English and support


s a limited character set.

Requires less memory compared to Unicode.

Unicode():

Uses 16 or 32 bits to represent each character.

Page 158
Python Notes

Supports a broader range of characters, including international and


special characters.

Req
uires more memory compared to ASCII.

**********************************************************************
***
**************************

Operations on Sequences:

------------------------

String
-

List
-

Page 159
Python Notes

Tuple

Indexing:

---------

Accessing an individual element in a sequence using its


position.

my_string = "Hello, World!"

first_char =
my_string[0] # Access the first character

print(first_char) # Output: H

Slicing:

Page 160
Python Notes

--------

Extracting a portion of a sequence by specifying a range.

my_string = "Hello, World!"

substrin
g = my_string[7:12] # Extract a portion of the string

print(substring) # Output: World

Adding:

-------

Page 161
Python Notes
Concatenating two or more sequences together.

first_part = "Hello, "

second_part = "World
!"

full_string = first_part + second_part # Concatenate two


strings

print(full_string) # Output: Hello, World!

Multiplying:

------------

Replicating a sequence by a specified number of times.

orig

Page 162
Python Notes
inal_string = "abc"

replicated_string = original_string * 3 # Replicate the string


three times

print(replicated_string) # Output: abcabcabc

Checking for Membership:

-----------------------

Ver
ifying if a specific character/word is present in a
sequence.

my_string = "Hello, World!"

check_result = "World" in my_string # Check if "World" is


present in the string

print(check_result) # Output: Tru

Page 163
Python Notes
e

len():

------

Returns the length (number of elements) of a sequence.

my_string = "python string"

length_of_string = len(my_string) # Get the length of the list

print(length_of_string)

# Output: 13

max():

Page 164
Python Notes
------

Returns the maximum element in a sequence.

my_string = "python"

max_of_string = min(my_string) # Get the max

print(max_of_string) # Output: y

min()
:

------

Returns the minimum element in a sequence.

Page 165
Python Notes

my_string = "python"

min_of_string = min(my_string) # Get the min

print(min_of_string) # Output: h

Negative Indexing Mechanisms:

----------------------------

Allows accessing elements from the end of the sequence using


negative indices.

my_string = "Hello, World"

last_char = my_string[
-
1] # Access the last character using

Page 166
Python Notes
negative indexing

print(last_char) # Output: d

Types of Formatting Strings:

----------------------------

Old Style Formatting:

-----------------------

name = "John"

age = 30

Page 167
Python Notes
print("Hello, my name is %s

and my age is %s!" % (name, age))

New Style Formatting (str.format):

------------------------------------

name = "John"

age = 15

print("Hello, my name is {} and my age is {}".format (name, age))

f
-
st
rings:

Page 168
Python Notes
------------

name = "John"

age = 15

print(f"Hello, my name is {name} and my age is {age}")

**********************************************************************
***
**************************

String Functions
(47):

---------------------

+
---------------
+
--------------

Page 169
Python Notes
+
--------------
+
-------------
+
--------
------
+
--------------
+
--------------
+
--------------
+

| capitalize | casefold | center | count | encode

| endswith
| expandtabs | join |

| format | format_map | index | isalnum | isalpha

| isascii | isdecimal | replace |

| isidentifier | islower | isnumeric | isprintable | isspace

| istitle |
isupper | splitlines |

Page 170
Python Notes

| ljust | lower | lstrip | maketrans |


partition | removeprefix | removesuffix | isdigit |

| rfind | rindex | rjust | rpartition | rsplit

| rstrip | sp
lit | splitlines |

| startswith | strip | swapcase | title |


translate | upper | find | zfill |

| removesuffix | | | |

| |

| |

+
---------------
+
--------------
+
--------------
+
-------------

Page 171
Python Notes
+
--------
------
+
--------------
+
--------------
+
--------------
+

upper() and lower(): Convert string to uppercase or lowercase.

strip(), lstrip(), rstrip():

Remove leading and trailing whitespaces.

find(), index(): Locate a substring within a string.

Page 172
Python Notes

replace(): Replace occurrences of a substring with another.

count(): Count occurrences of a substring.

startswith() and endswith(): Check if


a string starts or ends with a
specific substring.

split(): Split a string into a list of substrings based on a


delimiter.

join(): Concatenate a list of strings into one string using a


specified delimiter.

Convert various data types or data st


ructures into string

Page 173
Python Notes
---------------------------------------------------------

---

str()
---

Note:

-----

r for to avoid error in path

\
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)

III. List Comprehensions

************************************************************
*************
**************************

I. Introduction:

----------------

Page 175
Python Notes
-

Lists are mutable data structures.

Lists are ordered/sequential collections.

Lists can contain both homogeneous and heterogeneous data.

Lists are repres


ented using square brackets
-

[].

Indexing
-

Page 176
Python Notes
(positve and negative)

Slicing

Concatenating (adding)

Multiplying (with integer)

Checking Membership (in)

len()

min()

Page 177
Python Notes

max()

**********************************************************************
***
**************************

II. Built
-
in methods for lists(11):

-----------------------------------

"append()", "clear()", "copy()", "count()", "extend()", "index(


)",
"insert()",

"pop()", "remove()", "reverse()", "sort()"

# Sample list

Page 178
Python Notes

sample_list = [1, 2, 3, 4, 3, 5]

# append: Add an element to the end of the list

sample_list.append(6)

print(f"append: {sampl
e_list}")

# clear: Remove all elements from the list

sample_list.clear()

print(f"clear: {sample_list}")

# copy: Create a shallow copy of the list

original_list = [1, 2, 3]

copied_list = original_lis

Page 179
Python Notes
t.copy()

print(f"copy: {copied_list}")

# count: Count the occurrences of an element in the list

count_occurrences = sample_list.count(3)

print(f"count: {count_occurrences}")

# extend: Extend the list by appe


nding elements from an iterable

sample_list.extend([4, 5, 6])

print(f"extend: {sample_list}")

# index: Return the index of the first occurrence of an element

Page 180
Python Notes
index_result = sample_list.index(4)

print(f"index:
{index_result}")

# insert: Insert an element at a specified position in the list

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()

print(f"pop: {popped_element}, {sample_list}")

# remove: Remove the first occurrence of a specified element

Page 181
Python Notes

sample_list.remove(4)

print(f"remove: {sample_list}")

# reverse: Reverse the

elements of the list in place

sample_list.reverse()

print(f"reverse: {sample_list}")

# sort: Sort the elements of the list in ascending order,


Modifies Original List, Returns None

sample_list.sort()

print(f"s
ort: {sample_list}")

Page 182
Python Notes

# sorted: Creates a New Sorted List, Does Not Modify Original


list, Returns a Sorted List

numbers = [3, 1, 4, 1, 5, 9, 2]

sorted_numbers = sorted(numbers)

print(sorted_numbers) # O
utput: [1, 1, 2, 3, 4, 5, 9]

print(numbers) # Output: [3, 1, 4, 1, 5, 9, 2]


(original list is not modified)

**********************************************************************
***
**************************

III. List Comprehe


nsions:

-------------------------

Page 183
Python Notes
-

List comprehensions provide a concise way to create lists.

They consist of an expression followed by at least one 'for' clause


and zero or more 'if' clauses.

syntax
-

[expression for item in


iterable if condition]

expression : The operation to perform on each item.

item : The variable representing each element in the


iterable.

Page 184
Python Notes
iterable : The iterable you are iterating over (e.g., a list,
tuple, or s
tring).

condition : An optional condition to filter the elements.

Example:

--------

# Squares of numbers from 0 to 4 using list comprehension

squares = [x**2 for x in range(5)]

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:

----------------

Tuples are immu


table data structures.

Tuples are ordered/sequential collections.

Tuples can contain both homogeneous and heterogeneous data.

Page 186
Python Notes

Tuples are represented using paranthesis


-

().

Indexing
-

(positve and negative)

Slicing

Concatenating (adding)

Page 187
Python Notes

Multiplying (with integer)

Checking Membership (in)

len()

min()

max()

Note:

----

Empty tuple

Page 188
Python Notes
-

()

Single element tuple


-

(element,)

**
**********************************************************************
*
**************************

II. Built
-
in methods for Tuples(02)

------------------------------------

# count
-

Returns the number of occurrences of a specified value in

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
-

Returns the index of the first occurrence of a specified


value in the tuple.

my_tuple = (1, 2
, 3, 4, 5)

index_of_3 = my_tuple.index(3)

print(index_of_3) # Output: 2

Page 190
Python Notes

Convert various data types or data structures into tuple

--------------------------------------------------------

---

tuple()
----

**************
***********************************************************
**************************

Set:

====

I. Introduction

II. Built
-
in methods for Sets(17)

Page 191
Python Notes

III. Set Comprehensions

**********************************************************************
***
*
*************************

I. Introduction:

----------------

Sets are mutable data structures.

Sets store unique elements

Sets are unordered collections.(No indexing and No Slicing)

Page 192
Python Notes
Sets holds only immutable datatypes.

S
ets can contain both homogeneous and heterogeneous immutable
datatypes.

Sets are represented using curly brackets


-

{}.

Checking Membership (in)

len()

Page 193
Python Notes

min()

max()

Note:

-----

Empty
set
-

set() or set({})

**********************************************************************
***
**************************

II. Built
-

Page 194
Python Notes
in methods for Sets(17):

----------------------------------

# 1. add: Add an element to the end of the set

----------------------------------------------

my_set = {1, 2, 3}

my_set.add(4)

print(my_set) # Output: {1, 2, 3, 4}

# 2. clear: Remove all elements from the set

--------------------------------------------

my_set.clear(
)

Page 195
Python Notes

print(my_set) # Output: set()

# 3. copy: Create a shallow copy of the set

-------------------------------------------

original_set = {1, 2, 3}

copied_set = original_set.copy()

print(copied_set) # Output: {1, 2, 3}

# 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)

print(result_set) # Output: {1, 2}

# 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)

print(set1) # Output: {1, 2}

# 6.

Page 197
Python Notes

discard: Remove an element from the set if it is present

-------------------------------------------------------------

my_set = {1, 2, 3}

my_set.discard(2)

print(my_set) # Output: {1, 3}

# 7. intersection: Get the set of common

elements between two sets

------------------------------------------------------------------

set1 = {1, 2, 3, 4}

set2 = {3, 4, 5, 6}

Page 198
Python Notes
result_set = set1.intersection(set2)

print(result_set) # Output: {3, 4}

# 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)

print(set1) # Output: {3, 4}

# 9. isdisjoint: Check if two sets have no elements in common

Page 199
Python Notes
-------------------------------------------------------------

set1 = {1, 2, 3}

set2 = {4, 5, 6}

is_disjoint = set1.isdisjoint(set2)

print(is_disjoint) # Output: True

# 10. issubset: Check if every element in the set is in another set

--------------------------------------------------------------------

set1 = {1, 2}

set2 = {1, 2, 3, 4}

is_subset = set1.issub
set(set2)

Page 200
Python Notes

print(is_subset) # Output: True

# 11. issuperset: Check if every element in another set is in the set

---------------------------------------------------------------------

set1 = {1, 2, 3, 4}

set2 = {1, 2}

is_supe
rset = set1.issuperset(set2)

print(is_superset) # Output: True

# 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()

print(popped_element, my_set) # Output: 1 {2, 3}

# 13. remove: Remove a specified element from the set

-----------------------------------------------------

my_set = {1, 2, 3}

my_set.remove(2)

print(my_set) # Out
put: {1, 3}

# 14. symmetric_difference: Get the set of elements in either set,


but not both

Page 202
Python Notes

---------------------------------------------------------------------
----------

set1 = {1, 2, 3, 4}

set2 = {3, 4, 5, 6}

result_set = set1
.symmetric_difference(set2)

print(result_set) # Output: {1, 2, 5, 6}

# 15. symmetric_difference_update: Update the set with the symmetric


difference of itself and another set

---------------------------------------------------------------
------
-------------------------------------

set1 = {1, 2, 3, 4}

Page 203
Python Notes

set2 = {3, 4, 5, 6}

set1.symmetric_difference_update(set2)

print(set1) # Output: {1, 2, 5, 6}

# 16. union: Get the set of all elements in either set

----------
--------------------------------------------

set1 = {1, 2, 3}

set2 = {3, 4, 5}

result_set = set1.union(set2)

print(result_set) # Output: {1, 2, 3, 4, 5}

# 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)

print(set1) # Output: {1, 2, 3, 4, 5}

Convert various data types or data structures into set:

-------
------------------------------------------------

---

set()
---

Page 205
Python Notes

**********************************************************************
***
**************************

III. Set Comprehensions:

------------------------

Set comprehensions cre


ate sets using a similar syntax.

syntax
-

{expression for item in iterable if condition}

Page 206
Python Notes

expression : The operation to perform on each item.

item : The variable representing each element in the


iterable.

iterable : The iterab


le you are iterating over (e.g., a
list, tuple, or string).

condition : An optional condition to filter the elements.

Example:

Page 207
Python Notes
--------

# Creating a set of squares using set comprehension

squares_set = {x**2 for x in range(5)}

print(
squares_set)

Dictionary:

===========

I. Introduction

II. Built
-
in methods for Dictionary(11)

III. Dictionary Comprehensions

Page 208
Python Notes

**********************************************************************
***
**************************

I. Introduction:

----------------

Dictionarys are mutable data structures.

Dictionarys are mapping type.

Dictionarys contain key, value pairs

Dictionary keys should be unique immutable datatypes.

Page 209
Python Notes

Dictionary values are of any datatype.

Dictionarys are represented using curly brackets


-

{}.

Checking Membership (in)

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

my_dict = {'a': 1, 'b': 2, 'c': 3}

# 1. clear: Re
move all items from the dictionary

------------------------------------------------

my_dict.clear()

print("After clear:", my_dict) # Output: {}

# Re
-
create the sample dictionary

my_dict = {'a': 1, 'b':


2, 'c': 3}

# 2. copy: Create a shallow copy of the dictionary

Page 212
Python Notes

--------------------------------------------------

copied_dict = my_dict.copy()

print("Copied dictionary:", copied_dict) # Output: {'a': 1,


'b': 2, 'c':
3}

# 3. fromkeys: Create a new dictionary with specified keys and a


default value

-------------------------------------------------------------------
-----------

new_dict = dict.fromkeys(['x', 'y', 'z'], 0)

print("Fro
mkeys result:", new_dict) # Output: {'x': 0, 'y': 0,
'z': 0}

Page 213
Python Notes

# 4. get: Retrieve the value for a given key, or a default value if


the key is not present

-------------------------------------------------------------------
--------------------
----

value_a = my_dict.get('a', 'Key not found')

value_d = my_dict.get('d', 'Key not found')

print("Value for 'a':", value_a) # Output: 1

print("Value for 'd':", value_d) # Output: Key not found

# 5.

items: Return a view of all key


-
value pairs in the dictionary

------------------------------------------------------------------

Page 214
Python Notes

all_items = my_dict.items()

print("All items:", all_items) # Output: dict_items([('a', 1),


('b
', 2), ('c', 3)])

# 6. keys: Return a view of all keys in the dictionary

-------------------------------------------------------

all_keys = my_dict.keys()

print("All keys:", all_keys) # Output: dict_keys(['a', 'b',


'c'])

# 7. pop: Remove the item with the specified key and return its
value

-------------------------------------------------------------------
--

Page 215
Python Notes

removed_value = my_dict.pop('b', 'Key not found')

print("Removed value

for 'b':", removed_value) # Output: 2

print("Updated dictionary:", my_dict) # Output: {'a': 1, 'c':


3}

# 8. popitem: Remove and return an arbitrary key


-
value pair

-----------------------------------------------------------

removed_item = my_dict.popitem()

print("Removed item:", removed_item) # Output: ('c', 3)

Page 216
Python Notes
print("Updated dictionary:", my_dict) # Output: {'a': 1}

# 9. setdefault: Return the value for a given key, or set a default


v
alue if the key is not present

-------------------------------------------------------------------
--------------------------------

default_value = my_dict.setdefault('a', 10)

new_key_value = my_dict.setdefault('b', 20)

print("Default value for 'a':", default_value) # Output: 1

print("New key
-
value for 'b':", new_key_value) # Output: 20

print("Updated dictionary:", my_dict) # Output: {'a': 1, 'b':


20}

Page 217
Python Notes

# 10. update: Update the diction


ary with key
-
value pairs from
another dictionary or iterable

-------------------------------------------------------------------
-------------------------

update_dict = {'b': 2, 'c': 3, 'd': 4}

my_dict.update(update_dict)

print("Updated dictionary:", my_dict) # Output: {'a': 1, 'b':


2, 'c': 3, 'd': 4}

# 11. values: Return a view of all values in the dictionary

-----------------------------------------------------------

Page 218
Python Notes
all_values = my_di
ct.values()

print("All values:", all_values) # Output: dict_values([1, 2,


3, 4])

Convert various data types or data structures into dictionary:

--------------------------------------------------------------

---

dict()
---

Examples:

---------

# List of tuples to dictionary

Page 219
Python Notes
------------------------------

list_of_tuples = [("a", 1), ("b", 2), ("c", 3)]

dict_from_list = dict(list_of_tuples)

print(dict_from_list)

List of lists to dictionary

-----------------------------

list_of_lists = [["a", 1], ["b", 2], ["c", 3]]

dict_from_list = dict(list_of_lists)

print(dict_from_list)

Page 220
Python Notes
# Two separate lists to dictionary

----------------------------------

keys = ["a", "b", "c"]

values = [1, 2, 3]

dict_from_lists = dict(zip(keys, values))

print(dict_from_lists)

# Tuple of key
-
value pairs to dictionary

-----------------
-----------------------

tuple_of_pairs = (("a", 1), ("b", 2), ("c", 3))

Page 221
Python Notes
dict_from_tuple = dict(tuple_of_pairs)

print(dict_from_tuple)

# JSON string to dictionary

---------------------------

import jso
n

json_string = '{"a": 1, "b": 2, "c": 3}'

dict_from_json = json.loads(json_string)

print(dict_from_json)

**********************************************************************
***

Page 222
Python Notes
**************************

III.
Dictionary Comprehensions:

------------------------------

Dictionary comprehensions are similar to list comprehensions but


create dictionaries.

syntax
-

{key_expression: value_expression for item in iterable if


condition}

key_expres
sion : The expression for the dictionary keys.

value_expression : The expression for the dictionary values.

Page 223
Python Notes

item : The variable representing each element in the


iterable.

iterable : The iterable you are iterating


over (e.g., a
list, tuple, or string).

condition : An optional condition to filter the elements.

Example:

--------

# Creating a dictionary of squares using dictionary comprehension

Page 224
Python Notes
squares_dict = {x: x**2 for x in
range(5)}

print(squares_dict) # Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

# using two lists

keys = ["a", "b", "c"]

values = [1, 2, 3]

dict_from_comprehension = {key: value for key, value in zip(keys,


values)}

pr
int(dict_from_comprehension)

**********************************************************************
***
**************************

Page 225
Python Notes

1. sum():

---------

Calculates the sum of all elements in a Dictionary, set, tuple, List

Usage: sum(iter
able, start=0)

------------------------------

iterable : The iterable containing the elements to sum.

start : (Optional) The value added to the sum of items in the


iterable (defaults to 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():

---------

any() returns True if at least one element is present.

Usage: any(iterable)

---------------
-----

iterable : The iterable to check.

Page 227
Python Notes

Example:

-------

my_strings = ["", "Hello", "World", ""]

result = any(my_strings)

print(result) # Output: True (At least one non


-
empty string is
present)

3. all():

---------

all() returns True if all elements are present.

Usage: all(iterable)

Page 228
Python Notes

---------------------

iterable: The iterable to check.

Example:

--------

my_list = ["", "", ""]

result = all(my_list)

p
rint(result) # Output: False

4. collections module

---------------------

Page 229
Python Notes
8. Functions

============

I. Introduction

II. Different Types of Functions (User


-
defined/Built
-
in)

III. Nested/Recursive/Decorator

IV. Different types of Arguments

V. Anonymous Function (Lambda Function)

**********************************************************************
***
**************************

I. Introduction:

----------------

Page 230
Python Notes

Function is a block of organized, reusable code that performs a


specific task.

Functions help in modularizing code and make it more readable and


maintainable.

1. Code Organization : Functions help break down a program into


smaller, manageable parts.

2. Reusability : Functions can be


reused across the
codebase, reducing redundancy.

3. Readability : Well
-
named functions enhance code
readability and comprehension.

Page 231
Python Notes

4. Debugging : Isolating functionality into functions


aids in pinpointing and fixing issues.

Functions vs Methods:

---------------------

Functions:

----------

Defined using the def keyword.

Not associated with any object.

Page 232
Python Notes
Can be standalone and called independen
tly.

Methods:

--------

Associated with objects and classes.

Invoked on an object using the dot notation.

Dependent on the object they are called on.

Params vs Args:

------

Page 233
Python Notes
---------

Parameters (params) : Variables listed in the function


definition.

Arguments (args) : Values passed to the function during


a function call.

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.

**********************************************************************
***
**************
************

II. Different Types of Functions (User


-
defined/Built
-
in):

---------------------------------------------------------

User
-
defined Functions:

----------------------

def add_numbers(x, y):

Page 235
Python Notes

return x + y

Built
-
in Functions:

-------------------

result = len("Hello, World!")

**********************************************************************
***
**************************

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()

print("After function execution")

return wrapper

@decorator

def my_function():

print("Executing my_function")

my_function()

********************************
*****************************************
**************************

IV. Different types of Arguments:

Page 239
Python Notes
----------------------------------------

Positional Arguments:

---------------------

def add(x, y):

return x + y

result = add(3, 5)

Keyword Arguments:

------------------

def greet(name, message):

Page 240
Python Notes

print(f"Hello, {name}! {message}")

greet(message="Welcome", name="Python")

Default arguments:

----------
--------

Feature that allows you to provide default values for


parameters in a function.

When a function is called, if a value for a parameter is not


provided by the caller,

the default value specified in the functi


on definition is used.

Page 241
Python Notes

def function_name(param1, param2=default_value):

# logic implementation

param1: Required parameter without a default value.

param2: Optional parameter with a default value.

*args

**kwargs:

---------------

*args : allows a function to accept any number of positional


arguments.

Page 242
Python Notes
-

**kwargs : allows a function to accept any number of keyword


arguments.

Example:

--------

def va
riable_args(*args, kwargs):

"""Prints positional and keyword arguments."""

print("Positional arguments : ", args)

print("Keyword arguments : ", kwargs)

variable_args(1, 2, 3, name='John', age=25)

Page 243
Python Notes
**********
***************************************************************
**************************

V. Anonymous Function (Lambda Function):

----------------------------------------

A lambda function is an anonymous function created using the


'lambda' k
eyword.

It is a way to define a small, one


-
time
-
use function without the
need for a formal function definition using 'def'.

Lambda functions are a powerful tool when you need a quick,

Page 244
Python Notes
disposable function for simple operations.

Syntax
:

-------

lambda arguments: expression

'lambda' : Keyword indicating the creation of a lambda


function.

'arguments' : Comma
-
separated list of input parameters.

'expression' : Single expression to be evalu


ated and returned.

Page 245
Python Notes

**********************************************************************
***
**************************

Note:

-----

Typing Module

adding type hints to function parameters, return values, and


variables.

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
--

what are identifiers in python

map, filter, reduce


--
> with lambda

9. Packages & Modu


les

Page 247
Python Notes
=====================

I. Introduction

II. Types of Packages

III. Import Statements

**********************************************************************
***
**************************

I. Introduction:

----------------

Package:

--
------

Page 248
Python Notes
A package is a way of organizing related modules into a single
directory hierarchy.

It usually includes an __init__.py file, and it can contain


subpackages as well.

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:

-------
---

A directory is a folder on the filesystem containing Python


source files, modules,

or other directories (subdirectories).

A directory becomes a package when it includes an __init__.py


file.

project/

|
--

Page 251
Python Notes
script.py

|
--

module1.py

|
--

module2.py

Module:

-------

A module is a single Python file that contains functions,


classes, and variables.

Page 252
Python Notes
It serves as a way to organize code and make it reu
sable.

Modules can be standalone or part of a package.

A module contains:

------------------

Functions : Blocks of reusable code.

Classes : Blueprints for creating objects.

Variables : Data containers.

Page 253
Python Notes

Statements : Executable instructions.

Comments : Explanatory notes.

**********************************************************************
***
**************************

II. Types of Package


s:

----------------------

1. Standard Library Packages (Lib):

-----------------------------------

Built

Page 254
Python Notes
-
in modules and packages that come with Python installation.

Examples: os, math, datetime, json

2. User
-
Defined Packag
es (Custom Packages):

-------------------------------------------

Packages created by users for their specific needs

Example: If you have a package named my_package, it could have


modules like module1, module2, etc.

Page 255
Python Notes
3. External
Packages (Third
-
Party Packages):

--------------------------------------------

External modules and packages installed using package managers


like pip

Packages developed by third


-
party developers and not part of the
standard library.

Examples: requests, numpy, pandas.

**********************************************************************
***
**************************

Page 256
Python Notes

III. Import Statements:

-----------------------

Importing a specific module or function:

fro
m module_name import function_name

Importing an entire module:

import module_name

Page 257
Python Notes
Importing with an alias:

import module_name as alias

**********************************************************************
**
*
**************************

10. OOP Introduction:

====================

I. Introduction

II. Key Features

III. Advantages of OOP

**********************************************************************
***
**************************

I. Introduc

Page 258
Python Notes
tion:

----------------

Object
-
oriented programming (OOP) is a programming paradigm that
uses objects,

which are instances of classes, to structure and organize code.

The key idea behind OOP is to organize code around objects, which
are
instances of classes.

These objects encapsulate data (attributes) and behavior (methods)


related to a specific concept,

making it easier to model and manipulate real


-

Page 259
Python Notes
world entities.

Holds both the information about something (data) and


the actions it
can perform (behavior) in a neat package.

**********************************************************************
***
**************************

II. Key Features:

-----------------

1. Classes and Objects:

-----------------------

Class : A class is a blueprint or template for creating objects.

Page 260
Python Notes
It defines the attributes (properties) and methods
(functions) that the objects will have.

Object : An object is an instance of a class.

It is a concrete entity created based on the class


definition.

2. Encapsulation:

-----------------

Encapsulation is the bundling of data and the methods that


operate on that data into a single unit (class).

It allows you to co
ntrol access to the data and protects it from
unauthorized manipulation.

Page 261
Python Notes

3. Inheritance:

---------------

Inheritance is a mechanism that allows a class (subclass/derived


class) to inherit the

properties and methods of another c


lass (base class/parent
class).

It promotes code reusability and helps create a hierarchy of


classes.

4. Polymorphism:

----------------

Page 262
Python Notes

Polymorphism allows objects of different classes to be treated as


objects of a common base
class.

It enables a single interface to represent different types of


objects and allows methods to be called on

objects without knowing their specific types.

5. Abstraction:

---------------

Abstraction is the process


of simplifying complex systems by
modeling classes

Page 263
Python Notes
based on the essential properties and behaviors they share.

It hides the unnecessary details and focuses on what is


essential.

*******************************************************
******************
**************************

II. Advantages of OOP:

----------------------

1. Modularity and Reusability:

------------------------------

OOP encourages the creation of modular and reusable code.

Page 264
Python Notes

Classes and ob
jects provide a way to structure code into smaller,

manageable units, making it easier to maintain and update.

2. Code Organization:

---------------------

OOP helps in organizing code in a more structured and logical


way.

Classes and objects allow developers to model real


-
world entities
and their interactions,

leading to a more intuitive and readable codebase.

Page 265
Python Notes

3. Encapsulation and Security:

------------------------------

Encapsulation helps

protect data by restricting access to it and


providing methods to manipulate it.

This enhances security and reduces the chances of unintended


interference with data.

4. Inheritance for Code Reuse:

------------------------------

Inheritance allows the creation of new classes based on existing


ones, promoting code reuse and reducing redundancy.

Page 266
Python Notes

This is particularly useful when building on top of existing


functionality.

5. Polymorphism for Flexibility:

--------
------------------------

Polymorphism enables the use of a common interface for different


types of objects.

This flexibility allows for the development of more adaptable and


extensible systems.

10.1.1 Class and Object:

Page 267
Python Notes
=============
===========

I. Class

II. Object

**********************************************************************
***
**************************

I. Class:

-------------------------

A class in Python is a blueprint for creating objects.

It defines a

data structure that contains both data (attributes)


and code (methods) to operate on that data.

Page 268
Python Notes

Creating a class involves using the 'class' keyword, followed by


the class name (always written in pascal case) and a colon.

The class body contains


attributes and methods.

class ClassName:

# Class attributes (optional)

class_attribute = "I am a class attribute"

Page 269
Python Notes

# Constructor method (optional)

def __init__(self, parameter1, parameter2):

self.parameter1 = p
arameter1

self.parameter2 = parameter2

# Other methods

def method1(self):

Page 270
Python Notes

# Method body

def method2(self, parameter):

# Method body

class keyword : Indicates the beginning of


a
class definition.

ClassName : The name of the class,


followed by a colon.

Class attributes : Variables that belong to the


class and are shared by all instances of the class. These are
optional.

Page 271
Python Notes

Constructor method

(__init__) : A special method used for


initializing instances of the class.

It is called automatically
when an object is created from the class.

The self parameter refers to


the insta
nce of the class.

The constructor is used to


initialize the attributes of the object.

Other methods : Functions defined within the


class, which can be called on instances of the class.

Page 272
Python Notes

The self parameter is


required in all methods to refer to the instance.

self : self is a reference to the


instance of the class.

It is the first parameter in


the definition
of every method, including the constructor.

When calling a method on an


object, Python automatically passes the instance (self) as the first
argument.

self is required to access


the ins

Page 273
Python Notes
tance variables (attributes) and other methods within the class.

It allows the methods to


operate on the specific instance to which they belong.

When self is there as


parameter in the m
ethod, that method is called 'instance method'

**********************************************************************
***
**************************

II. Object:

-----------

An object is an instance of a class.

Page 274
Python Notes
-

Instance refers to a specific occ


urrence of a class.

When you create an object from a class, you are creating an


instance of that class.

Each instance has its own set of attributes and methods,


independent of other instances of the same class.

class Car:

def
__init__(self, make, model):

self.make = make # Instance variable

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()

10.1.2 Class Variable vs Instance Variable:

===========================================

Introduction:

Page 276
Python Notes

-------------

cl
ass attributes and instance variables are both ways to store data
within classes,

but they have different scopes and purposes

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.

Class attributes are typica


lly used to store data that is common to
all instances of the class.

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:

-----------
-----------

Instance variables are unique to each instance of a class.

Page 279
Python Notes

They are defined within methods of the class, typically within the
'__init__ method', using the 'self' keyword.

Each instance of the class has its own copy of instance

variables,
and they are not shared among instances.

Instance variables store data specific to each instance of the


class.

Example:

--------

class Car:

Page 280
Python Notes

def __init__(self, make, model):

s
elf.make = make # Instance variable

self.model = model # Instance variable

car1 = Car("Toyota", "Camry")

car2 = Car("Honda", "Accord")

print(car1.make, car1.model)

print(car2.make, car2.model)

Note:

-----

class MyClass:

Page 281
Python Notes

class_variable = "I am a class variable"

def __init__(self, instance_variable):

self.instance_variable = instance_variable

def instance_method(self):

print("In
stance variable : ", self.instance_variable)

print("Class variable : ", MyClass.class_variable)

# Creating instances of MyClass

obj1 = MyClass("Instance Variable 1")

obj2 = MyClass("Instance Variable 2")

Page 282
Python Notes

# Calling in
stance methods

obj1.instance_method()

obj2.instance_method()

10.2 Access Modifiers:

======================

Python does not have explicit access modifiers like some other
programming languages.

However, there are conven


tions(_, __) that are widely followed.

Page 283
Python Notes

1. Private Variables:

---------------------

Private variables are conventionally denoted with a double


underscore `__` as a prefix.

They are not accessible directly from outside the cla


ss.

class PrivateClass:

def __init__(self):

self.__private_variable = "I am private variable"

Page 284
Python Notes
def priv_fun(self):

# self.__private_variable = "I am private variable in


instance

method"

print(self.__private_variable)

priv_obj = PrivateClass()

# Accessing private variable will result in an AttributeError

# print(priv_obj.__private_variable)

# print(PrivateClass().__private_var
iable)

# priv_obj.priv_fun()

2. Protected Variables:

Page 285
Python Notes

-----------------------

Protected variables are conventionally denoted with a single


underscore `_` as a prefix.

They are not meant to be accessed directly from

outside the
class,

but it's more of a convention, and they can still be accessed.

class ProtectedClass:

def __init__(self):

self._protected_variable = "I am protected variable"

Page 286
Python Notes

def pro_fun(sel
f):

# self._protected_variable = "I am protected variable in


instance method"

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:

------------------

Private methods are conventionally denoted with a double


underscore `__` as a prefix.

They are not accessible directly from outsid


e the class.

class MyClass:

def __private_method(self):

return "This is a private method"

obj = MyClass()

Page 288
Python Notes

# Accessing private method will result in an AttributeError

# print(obj.__private_meth
od())

4. Protected Method:

--------------------

Protected methods are conventionally denoted with a single


underscore `_` as a prefix.

They are not meant to be accessed directly from outside the


class, but it's more

of a convention.

Page 289
Python Notes

class MyClass:

def _protected_method(self):

return "This is a protected method"

obj = MyClass()

print(obj._protected_method())

5. Class Method:

----------------

Class methods are denoted with the `@classmethod` decorator and

take a reference to the class (`cls`) as their first parameter.

Page 290
Python Notes
-

They are often used for operations that involve the class itself
rather than instances.

class MyClass:

class_variable = "I am from class variable"

@classmethod

def class_method(cls):

return f"This is a class method. Class variable:


{cls.class_variable}"

print(MyClass.class_metho
d())

Page 291
Python Notes

6. Static Method:

-----------------

Static methods are denoted with the `@staticmethod` decorator.

They don't have access to the class or instance and are used for
utility functions.

class MyClass:

@staticmethod

def static_method():

return "This is a static method"

Page 292
Python Notes

print(MyClass.static_method())

7. property decorator:

----------------------

The `@property` decorator is used to de


fine properties in a
Python class.

It allows us to define methods that can be accessed like


attributes.

This decorator is useful for defining computed attributes or


properties that require special behavior when accessed.

Page 293
Python Notes

class Circle:

def __init__(self, radius):

self.radius = radius

@property

def diameter(self):

return 2 * self.radius

@property

def area(self):

return 3.14 * self.radius * self.radius

Page 294
Python Notes

my_circle = Circle(5)

print("Diameter:", my_circle.diameter)

print("Area:", my_circle.area)

NOTE:

----

Use private variables and methods when you want to

encapsulate
internal implementation details and

prevent direct access from outside the class.

Page 295
Python Notes

Protected variables and methods can be used when you want to


indicate that

they are intended for internal use but still allow limited acce
ss.

Instance variables and methods are suitable for attributes and


behaviors that should be accessible from outside the class.

13.2.1 getattr, setattr, delattr, hasattr:

==========================================

I. Intoduction

II. getattr

III. setattr

IV. delattr

Page 296
Python Notes

V. hasattr

I. Intoduction:

---------------

To interact with object attributes dynamically.

II. getattr(object, attribute_name [, default]):

------------------------------------------------

Purpose

: Retrieves an attribute value from an object.

Page 297
Python Notes
-

Arguments :

object : The object from which to retrieve the


attribute.

attribute_name : The name of the attribute as a string.

default (optional) : A v
alue to return if the attribute is not
found.

Example:

--------

class Person:

Page 298
Python Notes

def __init__(self, name, age):

self.name = name

self.age = age

person = Person("Alice", 30)

# Accessing attributes using getattr

name = getattr(person, "name")

age = getattr(person, "age")

# Accessing non
-
existent attribute with default

location = getattr(person, "location", "Unknown")

Page 299
Python Notes

print(name
) # Output: Alice

print(age) # Output: 30

print(location) # Output: Unknown

III. setattr(object, attribute_name, value):

--------------------------------------------

Purpose : Sets the value of an attribute on an objec


t.

Arguments :

Page 300
Python Notes
object : The object on which to set the attribute.

attribute_name : The name of the attribute as a string.

value : The value to assign to the attribute.

Example:

--------

class Person:

def __init__(self, name, age):

self.name = name

Page 301
Python Notes
self.age = age

person = Person("Alice", 30)

# Modifying an existing attribute

setattr(person, "age
", 31)

# Creating a new attribute

setattr(person, "city", "New York")

print(person.age) # Output: 31 (updated)

print(person.city) # Output: New York (new attribute)

IV. delattr(object, attribute_name):

Page 302
Python Notes
------
------------------------------

Purpose : Deletes an attribute from an object.

Arguments :

object : The object from which to delete the attribute.

attribute_name : The name of the attribute as a string.

Example:

--------

Page 303
Python Notes

delattr(person, "city") # Delete the "city" attribute

print(hasattr(person, "city")) # Output: False (attribute is


gone)

V. hasattr(object, attribute_name):

-----------------------------------

Purpose : Checks if an object has a specific attribute.

Arguments :

object : The object to check.

Page 304
Python Notes
-

attribute_name : The name of the attribute as a string.

Return Value :

True if the attrib


ute exists, False otherwise.

Example:

--------

print(hasattr(person, "name")) # Output: True

print(hasattr(person, "location")) # Output: False

Page 305
Python Notes

13.3 Inheritance:

=================

I. Introduction

II. Us
e of Inheritance

III. Types of Inheritance

IV. Method Resolution Order (MRO)

V. super()

**********************************************************************
***
**************************

I. Introduction:

----------------

Page 306
Python Notes

Inheritance is

a mechanism where a new class (derived class or


subclass) is created by

inheriting properties and behaviors from an existing class (base


class or superclass).

This allows the derived class to reuse code from the base class and
extend its f
unctionality.

**********************************************************************
***
**************************

II. Use of Inheritance:

-----------------------

Page 307
Python Notes
Code reusability : Inheritance allows you to reuse code by
inheriting attributes
and methods from existing classes.

Extensibility : Derived classes can add new attributes and


methods or modify existing ones

to tailor the functionality to specific needs.

*******************************************
******************************
**************************

III. Types of Inheritance:

--------------------------

1. Single Inheritance : A class inherits from only one base


class.

2. Multiple Inheritance : A class inherits from multiple

base
classes.

Page 308
Python Notes
3. Multilevel Inheritance : A derived class is created from another
derived class.

4. Hierarchical Inheritance : Multiple derived classes inherit from a


single base class.

5. Hybrid Inheritance : Combination of two or


more types of
inheritance.

**********************************************************************
***
**************************

IV. Method Resolution Order (MRO):

----------------------------------

MRO is the order in which searches for methods

in the hierarchy of
classes.

Page 309
Python Notes

It is important especially in multiple inheritance scenarios to


determine the order in which methods are invoked.

Use of MRO:

-----------

MRO helps in resolving method and attribute lookup in mul


tiple
inheritance.

It ensures that the correct method is called according to the


inheritance hierarchy.

**********************************************************************
***
**************************

V. super():

Page 310
Python Notes

-----------

super() is used to access the methods and properties from the


superclass within the subclass.

It returns a temporary object of the superclass, allowing you to


call its methods.

Uses of super():

---------------

It allows
you to invoke methods of the superclass without
explicitly naming them.

Page 311
Python Notes

It ensures proper method resolution order (MRO) is followed.

10.4 Polymorphism

=================

I. Introduction

II. Method Overriding

III. Method Overloading

I
V. Constructor overloading

**********************************************************************
***
**************************

I. Introduction:

----------------

Page 312
Python Notes
-

Polymorphism in Python refers to the ability of different objects


to respond

to t
he same method call in different ways.

It allows objects of different classes to be treated as objects


of a common superclass,

enabling more flexible and dynamic code.

**********************************************************************
***
**************************

II. Method Overriding:

---------------------

Page 313
Python Notes

Method overriding occurs when a subclass provides a specific


implementation

of a method that is already defined in its superclass.

The method in the subclass override


s the implementation of the
method with the same name in the superclass.

**********************************************************************
***
**************************

III. Method Overloading:

------------------------

Python doesn't support

Page 314
Python Notes

true method overloading.

Python can achieve similar behavior using techniques like:

Default Arguments : Assign default values to some


parameters, making them optional.

*args and **kwargs : Use args to collect extra positional


argume
nts as a tuple, and

kwargs to collect extra keyword


arguments as a dictionary.

This provides flexibility in the number

Page 315
Python Notes
and types of arguments accepted.

Example:

--------

def calculate
_area(length, width=1): # Default width
argument

return length * width

# Calling with two arguments

area_rectangle = calculate_area(5, 3)

Page 316
Python Notes

print(area_rectangle) # Output: 15

# Calling with one argument (default width used)

area_s
quare = calculate_area(4)

print(area_square) # Output: 4

**********************************************************************
***
**************************

IV. Constructor overloading:

----------------------------

The ability to define mult


iple constructors with different

Page 317
Python Notes
parameter lists within a class.

While Python doesn't directly support this feature.

1. Default Arguments:

---------------------

Define a single constructor with default values for


some parameters.

T
his allows the constructor to be called with varying

Page 318
Python Notes
argument counts.

Example:

--------

class Person:

def __init__(self, name, age=18): # Default


age is 18

Page 319
Python Notes

self.name = name

self.age = age

# Creati
ng objects with different argument
patterns

person1 = Person("Alice") # Uses default age

Page 320
Python Notes
person2 = Person("Bob", 35) # Specifies age

2. Function Arguments (*args and **kwargs):

--------------------------------------------

Use *arg
s to collect extra positional arguments in a
tuple.

Use **kwargs to collect extra keyword arguments in a


dictionary.

Page 321
Python Notes

Example:

-------

class Product:

def __init__(self, name, *args, **kwargs):

self.name = name

Page 322
Python Notes

self.args = args

self.kwargs = kwargs

# Creating objects with varying arguments

product1 = Product("Book")

product2 = Product("Laptop", 15, "silver",

Page 323
Python Notes
brand="Dell")

10.5 Abstarction:

=================

I. Introduction

**********************************************************************
***
**************************

I. Introduction:

----------------

Abstraction focuses on defining the structure and behavior of


objects while hiding the

implementation details that are not relevant to the outside world.

Page 324
Python Notes
-

It focuses on the "what" (functionality) rather than the "how"


(implementation) aspect of an object.

1. Classes as Blueprints:

Classes serve as bluepri


nts for creating objects.

They encapsulate data (attributes) and behavior (methods)


related to a particular concept or entity.

Abstraction in classes involves defining methods that


provide a clear interface for interacting

with objects of that class, while hiding the internal


implementation details.

Page 325
Python Notes

2. Encapsulation:

It involves bundling data and methods that operate on that


data within a single unit (i.e., a class).

Abst
raction allows us to encapsulate complex functionality
within methods,

exposing only the necessary functionality to the outside


world.

3. Method Overriding and Polymorphism:

Abstraction also facilitates method overrid


ing and

Page 326
Python Notes
polymorphism, which are key features of OOP.

Method overriding allows subclasses to provide a specific


implementation of a method defined in their superclass,

while polymorphism allows objects of different classes to

be treated uniformly based on their common interface.

4. Abstract Base Classes (ABCs):

Python provides the abc module, which allows the creation


of abstract base classes.

Abstract base classes define abstract methods

that must be
implemented by concrete subclasses.

Page 327
Python Notes

This enforces a contract, ensuring that subclasses provide


specific behavior while allowing

for flexibility in their implementations.

15. Exception Handling:

===========
============

I. Introduction

II. Purpose of Exception Handling

III. try, except, else, and finally

IV. Exception Hirearchy

V. raise

Page 328
Python Notes
**********************************************************************
***
**************************

I. Intr
oduction:

----------------

In Python, errors are broadly categorized into three main types:

Syntax Errors : Syntax errors, also known as parsing


errors, occur when the code is not syntactically valid Python code.

Page 329
Python Notes

These errors are

detected by the Python interpreter during the


parsing of the code.

Common causes include missing colons, unmatched parentheses, or


incorrect indentation.

Runtime Errors : Runtime errors, also known as


exceptions, occur during the execu
tion of a program.

Page 330
Python Notes

These errors are not detected by the


Python interpreter until the code is actually run.

Common examples include division by


zero (ZeroDivisionError), accessing an index

that is out of range (IndexError), or


trying to use a variable that has not been defined (NameError).

Semantic Errors : Semantic errors occur when the code is


syntactically correct and executes without raising any exceptions,

Page 331
Python Notes

but it does not produce the expected


result.

These errors are often caused by


logical mistakes in the code.

Semantic errors are the most difficult


type of error to detect and fix

because
they do not result in any
error messages or exceptions.

Instead, they manifest as incorrect

Page 332
Python Notes
behavior of the program.

Exception handling is the process of detecting, responding to,


and recovering from errors or

exceptio
nal situations that occur during the execution of a
Python program.

Exceptions are events that occur during the execution of a


program that disrupt the normal flow of instructions.

Python provides a mechanism for handling exceptions through the


use

of the try, except, else, and finally blocks.

**********************************************************************

Page 333
Python Notes
***
**************************

II. Purpose of Exception Handling:

----------------------------------

Error Detection:

---------
---------

Exception handling allows you to detect errors and


exceptional conditions that occur during the execution of your code.

This helps in identifying issues that may cause your


program to behave unexpectedly.

Page 334
Python Notes
-

Graceful Failure:

------
-------------

Instead of abruptly terminating the program when an


error occurs, exception handling enables you

to gracefully handle errors and continue executing the


rest of the code.

This prevents crashes and improves the robustness of


your

program.

Page 335
Python Notes
-

Error Reporting:

------------------

Exception handling provides a mechanism for reporting


errors and providing useful feedback to users or developers.

You can customize error messages to provide information


about what went wrong

and how to fix it.

Program Control Flow:

-----------------------

Page 336
Python Notes

Exception handling allows you to control the flow of


your program based on the occurrence of errors.

You can specify different paths of execution depending


on the type of e
rror or exception that occurs.

Resource Management:

----------------------

Exception handling can be used to ensure proper cleanup


of resources, such as closing files,

Page 337
Python Notes

releasing locks, or deallocating memory, even in the


presence of error
s.

This helps in preventing resource leaks and maintaining


the integrity of your system.

Debugging and Testing:

------------------------

Exception handling aids in debugging and testing by


providing insights into the

cause of errors

Page 338
Python Notes
and helping to trace the execution flow.

By handling exceptions effectively, you can identify and


resolve issues more efficiently.

**********************************************************************
***
**************************

III. try, except


, else, and finally

-----------------------------------

try block : This block is used to enclose the code that might
raise an exception.

except block : This block is used to handle exceptions that


occur within the try block.

Page 339
Python Notes

You can specify the type of exception you want to


catch, or you can catch

all exceptions using a generic except block.

else block : This block is executed if the code in the try


block does not raise any exceptions.

It is typically used to execute code that should


run only if no exceptions occurred.

finally block : This block is always executed regardless of


whether an exception occurred or not.

Page 340
Python Notes

It is ge
nerally used to perform cleanup actions,
such as closing files or releasing resources.

Example:

-------

try:

# Code that might raise an exception

Page 341
Python Notes

x = int(input("Enter a number: "))

result = 10 / x

except Val
ueError:

# Handle ValueError (e.g., if the user enters


a non
-
integer)

Page 342
Python Notes

print("Please enter a valid integer.")

except ZeroDivisionError:

# Handle ZeroDivisionError (e.g., if the user


enters 0)

print("Cannot divide by
zero.")

Page 343
Python Notes
else:

# Executed if no exceptions occur

print("Division result:", result)

finally:

# Always executed, regardless of exceptions

Page 344
Python Notes

print("Finally block: This will always be


executed.")

****************
*********************************************************
**************************

IV. Exception Hirearchy:

------------------------

BaseException

ChildProcessError

nnectionResetError

ror

ResourceWarning

**********************************************************************
***
************
**************

V. raise:

Page 345
Python Notes

---------

raise is a keyword used to explicitly raise exceptions in code.

It is followed by an exception class or an instance of an


exception class.

It allows to generate custom errors or propagate built


-
in
excepti
ons when certain conditions are met.

It is used to signal that an exceptional condition has occurred


and to interrupt the normal flow of execution.

Page 346
Python Notes
-

raise is typically used inside functions or methods to indicate


errors or exceptional situations.

syntax :

--------

raise [ExceptionClassName(args)]

13. File Handling:

=======================

I. Introduction

II. Context Managers (with statement)

III. Error Handling

Page 347
Python Notes

****************************************************************
*********
**************************

I. Introduction:

----------------

File handling in Python is a concept that allows you to work with


data stored in external files,

which includes tasks such as reading from files, writing to files,


and
manipulating file contents.

Python provides built


-
in functions and modules to perform these
operations efficiently.

The first step is to open a file using the open() function.

Page 348
Python Notes

syntax
-

file = open(filename or path, mode)

filename : The name (or path) of the file you want to open.

mode : A string specifying the mode in which you want to open


the file.

Text Modes ('t'):

-----------------

'r' : Open the file for reading (default).

Page 349
Python Notes

'w'

: Open the file for writing. Existing content will be


overwritten!

'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!

'a+': Open the file for both reading and appending.

Page 350
Python Notes

'x' : Opens the file for exclusive creation, failing if the file
already exists.

Binary Modes (
'b'):

--------------------

'rb': Open the file for reading in binary mode.

'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

be written to the end of the file.

'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

't' (default): Opens the file in text mode.

'b': Opens the file in binary mode.

1. Opening a F
ile:

------------------

file = open("filename.txt", "mode")

2. Reading from a File:

-----------------------

# Read the entire file contents

Page 353
Python Notes

content = file.read()

# Read a
single line

line = file.readline()

# Read all lines and store them in a list

lines = file.readlines()

3. Writing to a File:

---------------------

# Write a string to the file

file.write("This is new content written to the file.


\

Page 354
Python Notes
n")

4. Closing the File (Crucial Step):

-----------------------------------

file.close() # Important to close the file explicitly

Remember: Always

close files explicitly (or use with) to avoid


resource leaks and potential data corruption.

**********************************************************************
***
**************************

II. Context Managers (with statement):

-----------------
---------------------

Page 355
Python Notes

The with statement is a convenient way to manage file objects.

It ensures the file is automatically closed, even if an exception


occurs within the code block

syntax:

---------

with context_manag
er_expression as variable_name:

# code that interacts with the resource

# (e.g., reading/writing files, opening network connections)

Page 356
Python Notes

with : This keyword initiates the context


manager construct.

context_manager_expression : This expression evaluates to a


context manager object.

Built
-
in functions like open() for
file handling.

as variable_name (optional): This assigns the result of the


context mana
ger expression to a

variable for convenient access


within the code block.

with open("data.txt", "r") as file:

Page 357
Python Notes

content = file.read()

# ... (rest of code)

********
*****************************************************************
**************************

III. Error Handling:

--------------------

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

with open("nonexistent_file.txt", "r") as file:

content = file.read()

except FileNotFoundError:

print("The file 'nonexistent_file.t


xt' does not exist.")

Note:

-----

os module

shutil module

Page 359
Python Notes
csv files

pdf files

image files

excel files

Page 360

You might also like