Python Programming Basics Guide
Python Programming Basics Guide
2
Python is a widely used general-purpose, high level programming language. It was initially
designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It
was mainly developed for emphasis on code readability, and its syntax allows programmers
to express concepts in fewer lines of code. Python is a programming language that lets you
work quickly and integrate systems more efficiently.
There are two major Python versions- Python 2 and Python 3. • On 16 October 2000,
Python 2.0 was released with many new features. • On 3rd December 2008, Python 3.0 was
released with more testing and includes new features.
2. Interpreted Language
Python does not require compilation; it is executed line by line.
3. Dynamically Typed
No need to specify variable types; Python determines them at runtime.
6. Platform-Independent
Python code runs on various operating systems (Windows, Linux, macOS) without
modification.
7. Garbage Collection
Has automatic memory management to free unused memory.
8. Highly Extensible
Can integrate with C, C++, Java, and other languages.
3
12. Machine Learning & AI
Popular in AI, ML, and data science with libraries like TensorFlow, NumPy, and
Pandas.
Working with Python Python Code Execution:
Python’s traditional runtime execution model: Source code you type is translated to byte
code, which is then run by the Python Virtual Machine (PVM). Your code is automatically
compiled, but then it is interpreted.
Sub-Topic : Keywords
Keywords in Python are reserved words that have special meanings and cannot be
used as variable names, function names, or identifiers. These words define the syntax
and structure of the Python language.
We can use them ,but we can not modify in their original task that they perform
There are 35 keywords present in python
4
What is a Variable in Python?
A variable in Python is a name that stores a value. It acts as a container that holds data, which can
be changed during the program execution.
Sub-Topic : Variable
1. Declaring a Variable
In Python, you don’t need to declare the type of a variable explicitly. Simply assign a value:
x = 10 # Integer
name = "Alice" # String
pi = 3.14 # Float
is_active = True # Boolean
5
Single Data Types in Python
A single data type in Python refers to a data type that holds a single value rather than multiple
values
A. Integer (int)
Int: Int, or integer, is a whole number, positive or negative, without decimals, of
unlimited length.
x = 100
print(type(x)) # Output: <class 'int'>
B. Float (float)
Float, or "floating point number" is a number, positive or negative, containing one or
more decimals.
y = 3.14
print(type(y)) # Output: <class 'float'>
C. Complex (complex)
Stores complex numbers with real and imaginary parts.
z = 2 + 3j
print(type(z)) # Output: <class 'complex'>
D. Boolean (bool)
Stores True or False values.
flag = True
print(type(flag)) # Output: <class 'bool'>
6
Sub-Topic : Multi Data Types
Sub-Topic : String
A string in Python is a sequence of characters enclosed in single (' '), double (" "), or
triple (''' ''' or """ """) quotes. Strings are immutable, meaning they cannot be changed
after creation.
Example:
name = "Alice"
greeting = 'Hello, World!'
multiline = """This is
a multi-line string."""
7
Function Description Example
Swaps
swapcase() "HeLLo".swapcase() → 'hEllO'
uppercase/lowercase
5. String Formatting
Function Description Example
format() Formats a string "Hello {}".format("Alice") → 'Hello Alice'
Modern string
f-strings name = "Alice"; f"Hello {name}" → 'Hello Alice'
formatting
8
Function Description Example
isalpha() Checks if string is alphabetic "abc".isalpha() → True
isalnum() Checks if string is alphanumeric "abc123".isalnum() → True
isspace() Checks if string contains only spaces " ".isspace() → True
Summary
Concept Explanation
What is a String? A sequence of characters in quotes (' ', " ", ''' ''')
Memory Allocation Uses string interning to store identical strings efficiently
Immutability Strings cannot be modified, only replaced
Key Functions upper(), lower(), strip(), find(), split(), join(), format()
Indexing refers to accessing individual characters in a string using their position (index).
Python uses zero-based indexing:
The first character is at index 0.
The last character is at index -1.
Example:
text = "Python"
print(text[0]) # Output: 'P'
print(text[3]) # Output: 'h'
print(text[-1]) # Output: 'n' (Last character)
Syntax of Slicing:
string[start:end:step]
Examples:
9
print(text[0:5]) # 'Hello' (Characters from index 0 to 4)
print(text[:5]) # 'Hello' (Start is optional)
print(text[7:]) # 'World!' (End is optional)
print(text[::2]) # 'Hlo ol!' (Every second character)
print(text[::-1]) # '!dlroW ,olleH' (Reversed string)
Slicing is used to extract a substring from a string using the colon (:) operator.
Finding the Length of a String
text = "Python"
print(len(text)) # Output: 6
Sub-Topic : List
print(lst)
11
Example:
numbers = [5, 2, 9, 1, 7]
[Link]() # [1, 2, 5, 7, 9]
[Link](reverse=True) # [9, 7, 5, 2, 1]
[Link]() # [1, 5, 9, 2, 7] (reverse without sorting)
print(numbers)
5. Searching in a List
Function Description Example
index(x) Returns the first index of x [Link](30)
Returns the count of x in the
count(x) [Link](10)
list
Example:
print([Link](30)) # Output: 2
print([Link](10)) # Output: 3
6. Copying a List
Function Description Example
Creates a shallow copy of the
copy() new_lst = [Link]()
list
Example:
original = [1, 2, 3]
copy_list = [Link]()
12
Summary Table
Operation Function Example
Add Element append(x), insert(i, x), extend(iterable) [Link](10)
Remove
remove(x), pop(i), clear() [Link](1)
Element
Find Length len(lst) len(lst)
Sort & Reverse sort(), reverse() [Link]()
Search Element index(x), count(x) [Link](30)
Copy List copy() [Link]()
Sub-Topic : Tuple
Creating Tuples
1. Using Parentheses ()
tuple1 = (1, 2, 3, 4)
single_element_tuple = (10,)
print(type(single_element_tuple)) # Output: <class 'tuple'>
13
Tuple Indexing and Slicing
1. Accessing Elements (Indexing)
Tuples use zero-based indexing.
Sub-Topic : Set
14
Unique Elements: Duplicates are not allowed.
No Indexing & Slicing: Unlike lists or tuples, sets do not support indexing or slicing.
Creating a Set
my_set = {1, 2, 3, 4, 5}
print(my_set) # Output: {1, 2, 3, 4, 5}
Summary
✅ Set is an unordered collection of unique elements.
❌ No indexing or slicing in sets.
✅ Supports operations like union (|), intersection (&), difference (-), symmetric
difference (^).
✅ Efficient for membership tests (in operator).
✅ Useful for removing duplicates from a list.
Operations on Sets
1. Adding Elements (add(), update())
Method Description Example
add(x) Adds an element x to the set {1,2}.add(3) → {1,2,3}
update(iterable Adds multiple elements from an {1,2}.update([3,4]) →
) iterable (list, tuple, etc.) {1,2,3,4}
my_set = {1, 2, 3}
my_set.add(4)
print(my_set) # Output: {1, 2, 3, 4}
my_set.update([5, 6, 7])
print(my_set) # Output: {1, 2, 3, 4, 5, 6, 7}
15
Method Description Example
clear() Removes all elements {1,2,3}.clear() → {}
my_set.remove(20)
print(my_set) # Output: {10, 30, 40}
popped_item = my_set.pop()
print(popped_item) # Output: Random element
print(my_set)
A = {1, 2, 3, 4}
B = {3, 4, 5, 6}
16
4. Checking Subsets and Supersets
Method Description Example
Returns True if all elements of this {1,2}.issubset({1,2,3}) →
issubset(set)
set exist in another True
Returns True if this set contains all {1,2,3}.issuperset({1,2})
issuperset(set)
elements of another → True
A = {1, 2}
B = {1, 2, 3, 4}
print([Link](B)) # True
print([Link](A)) # True
original_set = {1, 2, 3}
copied_set = original_set.copy()
print(copied_set) # Output: {1, 2, 3}
print(len(numbers)) # Output: 4
print(max(numbers)) # Output: 30
print(min(numbers)) # Output: 5
print(sum(numbers)) # Output: 65
17
print(sorted(numbers)) # Output: [5, 10, 20, 30]
Sub-Topic : Dictionary
✅Key Features:
Keys must be unique and immutable (e.g., strings, numbers, tuples).
Values can be any data type (including lists, tuples, and other dictionaries).
Dictionaries are unordered (in Python 3.6+, they maintain insertion order).
2. Dictionary Slicing
Unlike lists or strings, dictionaries do not support traditional slicing because they are key-based
and unordered.
18
print(sliced_dict) # Output: {'a': 1, 'c': 3}
# Using update()
my_dict.update({"country": "USA", "age": 31})
print(my_dict) # {'name': 'Alice', 'age': 31, 'city': 'New York',
'country': 'USA'}
2. Removing Elements
Method Description Example
pop(key) Removes key and returns value [Link]("age")
Removes the last inserted key-value
pop-item() [Link]()
pair
del d[key] Deletes a specific key del d["name"]
clear() Removes all items from the dictionary [Link]()
19
print(my_dict) # {'name': 'Alice', 'city': 'New York'}
# Deleting a key
del my_dict["name"]
print(my_dict) # {}
20
my_dict = {"name": "Alice", "age": 25}
5. Copying a Dictionary
Method Description Example
Returns a shallow copy of the
copy() new_dict = old_dict.copy()
dictionary
7. Sorting a Dictionary
Method Description Example
sorted(dict) Returns sorted keys sorted(d)
Returns sorted (key, value)
sorted([Link]()) sorted([Link]())
pairs
21
my_dict = {"b": 2, "c": 3, "a": 1}
Copying objects in Python is important for preserving data integrity and managing
memory efficiently. Python provides multiple ways to copy objects, and each type of
copy affects memory allocation differently.
There are three main types of copy operations:
1. Normal Assignment (Reference Copy)
2. Shallow Copy ([Link]())
3. Deep Copy ([Link]())
original_list = [1, 2, 3]
referenced_list = original_list # No copy, just a reference
referenced_list[0] = 99
print(original_list) # [99, 2, 3]
print(referenced_list) # [99, 2, 3]
22
2. Shallow Copy ([Link]())
A shallow copy creates a new outer object, but does not create new copies of
nested objects. Instead, the nested objects still reference the original memory
location.
Example: Shallow Copy
import copy
import copy
23
print(original_list) # [[1, 2, 3], [4, 5, 6]]
print(deep_copied_list) # [[99, 2, 3], [4, 5, 6]]
✅ Completely new memory allocation for all objects, including nested structures.
Memory Allocation in Deep Copy
The outer object gets a new memory address.
All inner objects (nested elements) also get new memory addresses.
Changes made in the deep-copied object do not affect the original object.
Key Takeaways
1. Use = when you want a reference to the same object.
2. Use [Link]() for a shallow copy (outer object is new, but nested objects
are shared).
3. Use [Link]() for a full, independent copy (both outer and inner
objects are new).
24
1. Operator
An operator is a symbol that tells the program to perform a specific mathematical,
relational, or logical computation.
Examples of Operators in Python:
Arithmetic Operators: +, -, *, /
Comparison Operators: >, <, ==, !=
Logical Operators: and, or, not
Bitwise Operators: &, |, ^
Assignment Operators: =, +=, -=, *=
2. Operand
An operand is a value or variable on which an operator performs an operation.
Example:
a = 10
b = 5
c = a + b # '+' is the operator, 'a' and 'b' are operands
print(c) # Output: 15
3. Operation
An operation is the process of applying an operator to operands to produce a result.
Example of an Operation:
x = 8
y = 4
result = x * y # '*' is the operator, 'x' and 'y' are operands
print(result) # Output: 32
25
1. Arithmetic Operators
These operators perform basic mathematical operations.
Example:
a = 10
b = 5
print(a + b) # Output: 15
print(a % b) # Output: 0
print(a ** b) # Output: 100000
2. Assignment Operators
Used to assign values to variables.
Example:
x = 10
x += 5 # Same as x = x + 5
print(x) # Output: 15
26
Operator Meaning Example (a = 10, b = 5) Output
== Equal to a == b False
!= Not equal to a != b True
> Greater than a > b True
< Less than a < b False
>= Greater or equal a >= b True
<= Less or equal a <= b False
Example:
a = 10
b = 5
print(a > b) # Output: True
print(a == b) # Output: False
4. Logical Operators
Used to combine conditional statements.
Example:
x = True
y = False
print(x and y) # Output: False
print(x or y) # Output: True
print(not x) # Output: False
5. Bitwise Operators
Used for binary (bit-level) operations.
27
Example:
a = 5 # Binary: 101
b = 3 # Binary: 011
Example:
a = [1, 2, 3]
b = a # Same reference
c = [1, 2, 3] # Different object
Example:
28
Conclusion
Python provides a variety of operators to perform different types of computations and logical
operations. Here’s a quick summary:
Sub-Topic : if Statement
29
1. if Statement
✅The if statement executes a block of code if the
given condition is True.
❌ If the condition is False, it skips the block.
Syntax:
if condition:
# Code to execute when condition is
True
Example:
age = 18
if age >= 18:
print("You are eligible to vote.")
2. if-else Statement
✅The if-else statement executes one block if the
condition is True and another block if the condition is
False.
Syntax:
if condition:
# Code if condition is True
else:
# Code if condition is False
Example:
age = 16
if age >= 18:
print("You are eligible to vote.")
else:
print("You are not eligible to vote.")
Flowchart:
30
3. if-elif-else Statement (Multiple Conditions)
✅The if-elif-else statement allows checking multiple conditions one by one.
🚨 If one elif condition is True, it executes that block and skips the rest.
❌ If no conditions are True, the else block
runs.
Syntax:
if condition1:
# Code if condition1 is True
elif condition2:
# Code if condition2 is True
elif condition3:
# Code if condition3 is True
else:
# Code if all conditions are False
Example:
marks = 75
4. Nested if Statement
✅A nested if statement means if conditions inside another if condition.
🚨 The inner if condition only checks if the outer condition is True.
31
Syntax:
if condition1:
if condition2:
# Code if both conditions are True
else:
# Code if condition1 is True but condition2 is
False
else:
# Code if condition1 is False
Example:
age = 20
citizen = "Yes"
Summary Table
Conditional
Description Example
Statement
Executes code if condition
if if x > 10: print("Big number")
is True
Executes one block if if x > 10: print("Big") else:
if-else
True, another if False print("Small")
Checks multiple conditions if x > 90: print("A") elif x > 75:
if-elif-else
one by one print("B") else: print("F")
Nested if if inside another if if x > 10: if y > 5: print("Valid")
Loops in Python
A loop is a programming construct that repeats a block of code multiple times until a condition is
met. Python provides two types of loops:
1. for loop
2. while loop
32
1🚨 for Loop
✅The for loop is used to iterate over a sequence (list, tuple, string, etc.).
🚨 It runs for a fixed number of iterations.
Syntax:
Example:
Start
|
Initialize Loop Variable
|
Check Condition (Sequence)
|
+----+----+
| Yes |
v v
Execute Exit Loop
Block (No More Items)
|
Increment / Next Item
|
|
Repeat
2🚨 while Loop
✅The while loop runs as long as the condition is True.
🚨 It is used when the number of iterations is unknown beforehand.
Syntax:
while condition:
# Code block to execute
Example:
33
count = 0
while count < 5: # Runs until count reaches 5
print("Count:", count)
count += 1
Start
|
Check Condition
|
+----+----+
| True |
v v
Execute Exit Loop
Block (Condition False)
|
Increment / Update
|
|
Repeat
Nested Loops
✅A loop inside another loop is called a nested loop.
✅ It is useful for working with tables, matrices, or patterns.
Example:
34
Example:
for i in range(5):
if i == 3:
break # Stops when i = 3
print(i) # Output: 0, 1, 2
Conclusion
✅ Loops automate repetitive tasks, making code efficient.
✅ for loops iterate over sequences, while loops run until a condition is False.
✅ Flowcharts help visualize how loops work.
1. Built-in Functions
These are pre-defined functions in Python that can be used directly. Examples:
2. User-Defined Functions
These are functions created by the user using the def keyword. Example:
def greet(name):
return f"Hello, {name}!"
print(greet("Alice"))
35
Returns a value using the return statement.
Syntax:
Example:
Syntax:
Example:
def greet(name):
print(f"Hello, {name}!")
def function_name():
# Function logic
return result
Example:
36
def get_pi():
return 3.14159
✅ Used when a function always returns the same result without needing input.
def function_name():
# Function logic
Example:
def greet():
print("Hello, World!")
1. Positional Arguments
Arguments that are passed in order and must match the function parameters in the same sequence.
Example:
37
2. Default Arguments
Arguments that have default values. If no value is provided, the default value is used.
Example:
3. Keyword Arguments
Arguments that are passed with parameter names, allowing flexibility in order.
Example:
def add_numbers(*args):
return sum(args)
38
def student_info(**kwargs):
for key, value in [Link]():
print(f"{key}: {value}")
8. Combination of Arguments
You can mix different types of arguments, but the order should be:
Example:
39
def example(a, b=2, *args, c=3, **kwargs):
print(f"a: {a}, b: {b}, args: {args}, c: {c}, kwargs: {kwargs}")
Summary Table
Argument Type Syntax Description
Positional func(a, b) Must be passed in order
Default func(a, b=10) Has default values if not provided
Keyword func(a=10, b=20) Passed using parameter names
Accepts multiple positional
Variable-Length (*args) func(*args)
arguments
Variable-Length Keyword Accepts multiple keyword
func(**kwargs)
(**kwargs) arguments
Positional-Only (/) func(a, b, /) Must be passed as positional
Keyword-Only (*) func(a, *, b) Must be passed as keyword
1. Packing
Packing means grouping multiple values into a single variable (usually as a tuple, list, or
dictionary).
Tuple Packing
When multiple values are assigned to a single variable, Python automatically packs them into a
tuple.
Example:
List Packing
A list can also be packed explicitly:
Example:
40
data = [1, 2, 3, 4, 5] # List packing
print(data) # Output: [1, 2, 3, 4, 5]
Example:
def student_info(**kwargs):
print(kwargs)
✅ Packing is useful when we don’t know how many values will be passed.
2. Unpacking
Unpacking means extracting values from a packed variable into individual variables.
Tuple Unpacking
Values from a tuple can be unpacked into individual variables.
Example:
t
data = (10, 20, 30) # Tuple
a, b, c = data # Unpacking
print(a, b, c) # Output: 10 20 30
List Unpacking
Similar to tuple unpacking but with lists.
Example:
data = [1, 2, 3]
x, y, z = data
print(x, y, z) # Output: 1 2 3
Example:
data = (1, 2, 3, 4, 5)
a, *b, c = data
print(a) # Output: 1
print(b) # Output: [2, 3, 4]
print(c) # Output: 5
41
Dictionary Unpacking (**)
You can unpack a dictionary into function arguments.
Example:
✅ Unpacking is useful for easy data extraction and function argument passing.
def add_numbers(*args):
return sum(args)
Unpacking with *
Used for unpacking arguments into function parameters.
numbers = (2, 3, 4)
print(multiply(*numbers)) # Output: 24
Summary Table
Concept Description Example
Packing (Tuple/List) Combining multiple values into one data = (1, 2, 3)
Groups multiple function arguments
Packing (*args) def func(*args): print(args)
into a tuple
Groups multiple keyword arguments def func(**kwargs):
Packing (**kwargs)
into a dictionary print(kwargs)
Unpacking Extracting values from a packed
a, b = (10, 20)
(Tuple/List) variable
Unpacking (*) Assigns remaining values to a list a, *b, c = (1, 2, 3, 4)
Unpacking Passing dictionary values as func(**{"name": "Bob"})
42
Concept Description Example
Dictionary (**) arguments
Sub-Topic : Inheritance
1. Class
A class is a blueprint for creating objects. It defines a structure that objects follow,
including attributes (variables) and methods (functions).
Example of a Class
class Car:
def __init__(self, brand, model):
[Link] = brand # Attribute
[Link] = model # Attribute
2. Object
An object is an instance of a class. It represents a specific entity that has real values
assigned to its attributes.
🚨 Example:
class Dog:
def __init__(self, name):
[Link] = name # Instance Attribute
dog1 = Dog("Buddy")
[Link]() # Output: Buddy says Woof!
🚨 Example:
class Dog:
species = "Canine" # Class Attribute
44
@classmethod
def get_species(cls):
return [Link]
🚨 Use Case: When you need to work with class attributes instead of instance attributes.
🚨 Example:
class MathUtils:
@staticmethod
def add(a, b):
return a + b
🚨 Use Case: Use when a function doesn’t need to access class or instance data (e.g., utility
functions).
✅ Use @staticmethod when the method does not need self or cls.
✅ Use @classmethod when working with class-level data.
✅ Use instance methods when working with object-specific data.
Inheritance means that using code again and again using the classname as it is
class Parent:
def func1(self):
print("This is Parent class")
obj = Child()
obj.func1() # Accessing Parent class method
obj.func2()
2. Multiple Inheritance
A subclass inherits from multiple parent classes.
class Parent1:
def func1(self):
print("This is Parent1 class")
class Parent2:
def func2(self):
print("This is Parent2 class")
obj = Child()
obj.func1()
obj.func2()
46
obj.func3()
3. Multilevel Inheritance
A class inherits from another class, which in turn inherits from another class.
class Grandparent:
def func1(self):
print("This is Grandparent class")
class Parent(Grandparent):
def func2(self):
print("This is Parent class")
class Child(Parent):
def func3(self):
print("This is Child class")
obj = Child()
obj.func1()
obj.func2()
obj.func3()
4. Hierarchical Inheritance
Multiple child classes inherit from a single parent class.
class Parent:
def func1(self):
print("This is Parent class")
class Child1(Parent):
def func2(self):
print("This is Child1 class")
class Child2(Parent):
def func3(self):
47
print("This is Child2 class")
obj1 = Child1()
obj2 = Child2()
obj1.func1()
obj1.func2()
obj2.func1()
obj2.func3()
5. Hybrid Inheritance
A combination of two or more types of inheritance.
class A:
def func1(self):
print("This is class A")
class B(A):
def func2(self):
print("This is class B")
class C(A):
def func3(self):
print("This is class C")
obj = D()
obj.func1()
obj.func2()
obj.func3()
obj.func4()
48
A constructor is a special method in Python used to initialize an object when it is
created. In Python, the constructor method is named __init__() and is called
automatically when a new object of a class is instantiated.
Syntax of a Constructor
class ClassName:
def __init__(self, parameters): # Constructor
# Initialize attributes
class Person:
def __init__(self): # Default constructor
print("Default Constructor Called!")
# Object creation
obj = Person()
2. Parameterized Constructor
A constructor that takes parameters to initialize object attributes.
class Person:
def __init__(self, name, age): # Parameterized constructor
[Link] = name
[Link] = age
def display(self):
print(f"Name: {[Link]}, Age: {[Link]}")
class Car:
def __init__(self, brand="Toyota", model="Corolla"):
[Link] = brand
[Link] = model
def display(self):
print(f"Car: {[Link]} {[Link]}")
4. Constructor Overriding
A subclass can override the constructor of its parent class.
class Parent:
def __init__(self):
print("Parent Constructor")
class Child(Parent):
def __init__(self):
super().__init__() # Calls Parent constructor
print("Child Constructor")
obj = Child()
Output:
50
Parent Constructor
Child Constructor
class Parent:
def __init__(self, name):
[Link] = name
print("Parent Constructor Called")
class Child(Parent):
def __init__(self, name, age):
super().__init__(name) # Calls Parent's constructor
[Link] = age
print("Child Constructor Called")
51
c = Child("Alice", 25)
Output:
class Parent:
def __init__(self, name):
[Link] = name
print("Parent Constructor Called")
class Child(Parent):
def __init__(self, name, age):
Parent.__init__(self, name) # Explicitly calling Parent's
constructor
[Link] = age
print("Child Constructor Called")
c = Child("Bob", 30)
Output:
Example:
class Car:
def start(self):
print("Car Started")
return self # Returning the same object
def accelerate(self):
print("Car is Accelerating")
return self
def stop(self):
print("Car Stopped")
return self
# Method chaining
car = Car()
[Link]().accelerate().stop()
Output:
Car Started
Car is Accelerating
Car Stopped
53
2. Method Chaining Between Parent and Child Class
In inheritance, a child class can call a parent class method using:
1. super().method() (Preferred)
2. [Link](self, ...) (Older method)
class Parent:
def display(self):
print("Parent Method")
return self # Allows further chaining
class Child(Parent):
def show(self):
print("Child Method")
return self
# Method chaining
obj = Child()
[Link]().show()
Output:
Parent Method
Child Method
class Parent:
def display(self):
print("Parent Method")
return self
class Child(Parent):
def show(self):
[Link](self) # Explicitly calling parent method
print("Child Method")
return self
# Method chaining
obj = Child()
[Link]()
Output:
Parent Method
54
Child Method
Sub-Topic : Polymorphism
Polymorphism in Python
Polymorphism means "many forms" and allows the same function, method, or operator to
behave differently based on the object or data type.
It is a process of performing multiple tasks using one single operator or method
Python do not support polymorphism
✅ Why Use Polymorphism?
Code Reusability → Avoids writing duplicate code.
Flexibility → Works with different data types & objects.
Extensibility → Easy to add new functionality.
Example:
class Calculator:
def add(self, a, b=0, c=0): # Default values allow multiple cases
return a + b + c
calc = Calculator()
print([Link](5)) # Calls add(a)
print([Link](5, 10)) # Calls add(a, b)
print([Link](5, 10, 15)) # Calls add(a, b, c)
Output:
55
5
15
30
Example:
class Animal:
def sound(self):
print("Animals make sound")
class Dog(Animal):
def sound(self): # Overriding parent method
print("Dog barks")
class Cat(Animal):
def sound(self): # Overriding parent method
print("Cat meows")
dog = Dog()
cat = Cat()
[Link]() # Calls Dog's version
[Link]() # Calls Cat's version
Output:
Dog barks
Cat meows
56
3. Operator Overloading (Using __magic__ Methods)
Python allows overloading operators (+, -, *, etc.) for custom objects using special methods like
__add__(), __sub__(), etc.
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
p1 = Point(2, 3)
p2 = Point(4, 5)
p3 = p1 + p2 # Calls __add__() method
print(p3.x, p3.y)
Output:
6 8
2. String Representation
Method Description
__str__(self) Defines str(obj), used in print(obj).
__repr__(self) Defines repr(obj), used in debugging (print([obj])).
57
Method Description
Defines custom string formatting (format(obj,
__format__(self, format_spec)
"spec")).
__bytes__(self) Defines bytes(obj), converts object to bytes.
5. Comparison Operators
Operator Magic Method Example Usage
== (Equal) __eq__(self, other) a == b
!= (Not Equal) __ne__(self, other) a != b
< (Less Than) __lt__(self, other) a < b
<= (Less Than or Equal) __le__(self, other) a <= b
> (Greater Than) __gt__(self, other) a > b
>= (Greater Than or Equal) __ge__(self, other) a >= b
58
Operator Magic Method Example Usage
` ` (Bitwise OR) __or__(self, other)
^ (Bitwise XOR) __xor__(self, other) a ^ b
<< (Left Shift) __lshift__(self, other) a << b
>> (Right Shift) __rshift__(self, other) a >> b
~ (Bitwise NOT) __invert__(self) ~a
7. Attribute Access
Method Description
__getattr__(self, name) Called when an attribute is not found in an object.
__setattr__(self, name, value) Called when an attribute is set on an object.
__delattr__(self, name) Called when an attribute is deleted from an object.
59
Sub-Topic : Encapsulation
Encapsulation in Python
Encapsulation is one of the core OOP (Object-Oriented Programming) principles in Python.
It means restricting direct access to object data and allowing controlled access through methods
(getters & setters).
It Is a phenomenon of wrapping up data to provide security to the data with the help of access
specifier
just like an outer layer of a capsule provides security to the medicine that is present inside it
60
Why Encapsulation?
🚨 Data Hiding: Prevents direct modification of object attributes.
🚨 Security: Protects important data from accidental changes.
🚨 Flexibility: Allows controlled access using methods.
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable (Encapsulated)
# Creating an account
acc = BankAccount(1000)
[Link](500)
[Link](300)
print("Balance:", acc.get_balance())
61
Access Modifier Example Access
Private __name Cannot be accessed directly from outside
def show_details(self):
return f"Car: {[Link]}, Speed: {self._speed}, Engine: {self.__engine}"
Sub-Topic : Abstraction
Abstraction in Python
Abstraction is an Object-Oriented Programming (OOP) principle that hides implementation
details and exposes only the necessary functionalities. It helps in reducing code complexity by
focusing on what an object does rather than how it does it.
62
Defined using the @abstractmethod decorator.
# Abstract Class
class Vehicle(ABC):
@abstractmethod
def start(self): # Abstract Method
pass
# Concrete Class
class Car(Vehicle):
def start(self):
return "Car engine starts with a key."
class Bike(Vehicle):
def start(self):
return "Bike starts with a self-start button."
# Creating objects
car = Car()
bike = Bike()
Advantages of Abstraction
✔ Hides Complexity – Users don't need to know how methods work internally.
✔ Enhances Security – Prevents direct access to certain functionalities.
✔ Improves Code Reusability – Encourages the use of common base classes.
Real-World Example
Think of a TV remote – You press buttons to change the channel, but you don't need to know the
internal circuit workings. That's abstraction in action!
63
✅ Used in real-world applications – Implements logic for practical use.
✅ Can inherit from abstract classes – But must implement abstract methods.
def stop(self):
return "Car is stopping..."
# Creating an object
my_car = Car()
print(my_car.start()) # Output: Car is starting...
print(my_car.stop()) # Output: Car is stopping...
✔ Here, Car is a concrete class because it has complete implementations for all methods.
64
lambda arguments: expression
# Normal function
def add(a, b):
return a + b
65
map() Function in Python
The map() function in Python is used to apply a function to each item in an
iterable (like a list or tuple) and return a new iterable with the modified values.
Syntax of map()
map(function, iterable)
def square(num):
return num ** 2
numbers = [1, 2, 3, 4, 5]
result = map(square, numbers)
66
Syntax of filter()
filter(function, iterable)
def is_even(num):
return num % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
result = filter(is_even, numbers)
Sub-Topic : Comprehension
Advantages of Comprehensions
✅ More readable than loops.
✅ More concise than traditional loops.
✅ Faster execution due to optimized internal implementation.
✅ Memory efficient (especially generators).
numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]
numbers = [1, 2, 3, 4, 5, 6]
evens = [x for x in numbers if x % 2 == 0]
print(evens) # Output: [2, 4, 6]
numbers = [1, 2, 3, 4, 5]
labels = ["Even" if x % 2 == 0 else "Odd" for x in numbers]
print(labels) # Output: ['Odd', 'Even', 'Odd', 'Even', 'Odd']
68
✔ Assigns "Even" for even numbers and "Odd" for odd numbers.
Comparison Table
Type Syntax Example Output
Basic [x for x in iterable] [1, 4, 9, 16, 25]
With if [x for x in iterable if condition] [2, 4, 6]
[x if condition else y for x in ['Odd', 'Even', 'Odd',
With if-else
iterable] 'Even']
generator comprehension.
numbers = [1, 2, 3, 4, 5]
squares = (x ** 2 for x in numbers)
print(squares) # Output: <generator object at 0x...>
print(tuple(squares)) # Output: (1, 4, 9, 16, 25)
numbers = [1, 2, 3, 4, 5, 6]
evens = (x for x in numbers if x % 2 == 0)
print(tuple(evens)) # Output: (2, 4, 6)
69
✔ Only even numbers are included in the tuple.
numbers = [1, 2, 3, 4, 5]
labels = ("Even" if x % 2 == 0 else "Odd" for x in numbers)
print(tuple(labels)) # Output: ('Odd', 'Even', 'Odd', 'Even', 'Odd')
✔ Assigns "Even" for even numbers and "Odd" for odd numbers.
Comparison Table
Type Syntax Example Output
Basic (x for x in iterable) (1, 4, 9, 16, 25)
With if (x for x in iterable if condition) (2, 4, 6)
(x if condition else y for x in ('Odd', 'Even', 'Odd',
With if-else
iterable) 'Even')
🚨 Easy Definition
Tuple comprehension does not exist in Python.
Using () creates a generator instead of a tuple.
Convert the generator to a tuple using tuple().
numbers = [1, 2, 3, 4]
squares_dict = {x: x**2 for x in numbers}
print(squares_dict) # Output: {1: 1, 2: 4, 3: 9, 4: 16}
70
✔ Each number is a key, and its square is the value.
numbers = [1, 2, 3, 4, 5]
even_squares_dict = {x: x**2 for x in numbers if x % 2 == 0}
print(even_squares_dict) # Output: {2: 4, 4: 16}
numbers = [1, 2, 3, 4, 5]
labels_dict = {x: "Even" if x % 2 == 0 else "Odd" for x in numbers}
print(labels_dict) # Output: {1: 'Odd', 2: 'Even', 3: 'Odd', 4: 'Even', 5: 'Odd'}
Comparison Table
Type Syntax Example Output
{1: 1, 2: 4, 3: 9,
Basic {key: value for item in iterable}
4: 16}
With if {key: value for item in iterable if condition} {2: 4, 4: 16}
With if- {key: value_if_true if condition else {1: 'Odd', 2:
else value_if_false for item in iterable} 'Even', 3: 'Odd'}
🚨 Easy Definition
Dictionary comprehension is used to create dictionaries quickly.
It replaces traditional loops with a single line of code.
Can include if for filtering and if-else for conditional values.
71
Syntax:
Read Methods
Method Description
read() Reads the entire file.
read(n) Reads the first n characters.
readline() Reads one line at a time.
readlines() Reads all lines as a list.
72
Example: Reading line by line
if [Link]("[Link]"):
[Link]("[Link]")
else:
print("File does not exist")
73
Summary of File Handling
Operation Mode Description
Read "r" Opens file for reading. Error if the file does not exist.
Write "w" Creates a new file or overwrites existing content.
Append "a" Adds content at the end without deleting old data.
Create "x" Creates a new file but gives an error if the file exists.
Binary "b" Used for binary files like images and PDFs.
Would you like examples for handling binary files (.jpg, .pdf)? 🚨
74
print("Database connected successfully!")
3🚨 Creating a Table
conn = [Link]("my_database.db")
cursor = [Link]()
[Link]("""
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
age INTEGER
)
""")
[Link]("INSERT INTO users (name, age) VALUES (?, ?)", ("Alice", 25))
[Link]()
75
]
conn = [Link]("my_database.db")
cursor = [Link]()
[Link]()
print(row)
[Link]()
76
[Link]()
🚨 Deleting a Table
conn = [Link]("my_database.db")
cursor = [Link]()
print("Table deleted!")
[Link]()
77
Executing the SQL File in Python
conn = [Link]("my_database.db")
cursor = [Link]()
[Link]()
[Link]()
🚨 Key Takeaways
✅ SQLite stores data in a single file (.db).
✅ Always use commit() after modifying the database.
✅ Use fetchall() for multiple rows and fetchone() for a single row.
✅ Use executemany() for inserting multiple records efficiently.
✅ Use executescript() to run an entire SQL file in Python.
78
Sub-Topic : Exception handling
1🚨 What is an Exception?
An exception is an error that occurs during execution, disrupting the program flow.
Example:
try:
x = 5 / 0 # Risky code
except ZeroDivisionError:
print("Cannot divide by zero!")
try:
a = int(input("Enter a number: ")) # ValueError if input is not a number
b = 5 / a # ZeroDivisionError if a = 0
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input! Please enter a number.")
79
4️⃣🚨 Catching Multiple Exceptions in One except Block
try:
a = int(input("Enter a number: "))
b = 10 / a
except (ZeroDivisionError, ValueError) as e:
print("Error:", e)
try:
num = int(input("Enter a number: "))
print("Valid input:", num)
except ValueError:
print("Invalid number!")
else:
print("No errors occurred!")
try:
file = open("[Link]", "r")
data = [Link]()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing file.")
[Link]() # Ensures the file is closed
x = -5
if x < 0:
80
raise ValueError("Negative value not allowed!")
class NegativeNumberError(Exception):
pass # Custom exception class
def check_positive(num):
if num < 0:
raise NegativeNumberError("Negative number not allowed!")
return num
try:
print(check_positive(-10))
except NegativeNumberError as e:
print("Error:", e)
try:
try:
x = int(input("Enter a number: "))
y = 10 / x
except ZeroDivisionError:
print("Cannot divide by zero!")
except ValueError:
print("Invalid input!")
81
Keyword Description
pass Used to define custom exceptions without adding code.
🚨 Key Takeaways
✅ Use try-except to prevent program crashes.
✅ Use finally for cleanup actions like closing files.
✅ Use raise to trigger custom exceptions.
✅ Handle multiple exceptions separately or in a single except block.
✅ Use else when you need to run code only if no exceptions occur.
Exception Categories
Python exceptions are categorized into different classes:
1🚨 Arithmetic Errors
Exception Name Description
ZeroDivisionError Dividing by zero.
OverflowError Numeric calculation exceeds limit.
FloatingPointError Floating point error (rarely occurs).
82
4️⃣🚨 Import Errors
Exception Name Description
ImportError Import statement fails.
ModuleNotFoundError The specified module is not found.
8🚨 Runtime Errors
Exception Name Description
RuntimeError Generic runtime error.
RecursionError Exceeding the maximum recursion depth.
83
Sub-Topic : Iterator
Example of an Iterator:
class MyNumbers:
def __iter__(self):
[Link] = 1
return self
def __next__(self):
if [Link] > 5: # Stop after 5 iterations
raise StopIteration
val = [Link]
[Link] += 1
return val
Output:
1
2
3
4
5
Built-in Iterators
Python has built-in iterators like lists, tuples, and dictionaries that can be used with the iter() and
next() functions.
84
print(next(my_iter)) # 10
print(next(my_iter)) # 20
print(next(my_iter)) # 30
Sub-Topic : Generator
Unlike normal functions that use return, generators use the yield keyword to produce a sequence
of values lazily, allowing them to be paused and resumed.
def my_generator():
yield 1
yield 2
yield 3
gen = my_generator()
print(next(gen)) # Output: 1
print(next(gen)) # Output: 2
print(next(gen)) # Output: 3
def countdown(n):
while n > 0:
yield n
n -= 1
Output:
85
4
3
2
1
Sub-Topic : Decorator
1🚨 Basic Decorator
def my_decorator(func):
def wrapper():
print("Function is about to run...")
func()
print("Function has finished running.")
return wrapper
86
@my_decorator
def say_hello():
print("Hello, World!")
say_hello()
📌 Output:
🚨 How It Works
1. my_decorator takes a function (func) as input.
2. It wraps func() inside another function called wrapper().
3. wrapper() adds extra behavior before and after calling func().
4. Using @my_decorator, we apply this behavior to say_hello() without modifying its
original code.
87