1.
Python Data Structure
Lists
Creating a List
my_list = [1, 2, 3, 'a', 'b', 'c']
Accessing Elements
print(my_list[0]) # Output: 1
print(my_list[-1]) # Output: 'c' (last element)
De
Slicing
print(my_list[1:3]) # Output: [2, 3]
print(my_list[:2]) # Output: [1, 2] (first two elements)
Modifying Elements
my_list[0] = 10
e_
Adding Elements
my_list.append(5)
my_list.insert(1, 'x')
cod
# Add to the end
# Insert 'x' at index 1
es
Removing Elements
my_list.remove(3) # Remove element with value 3
element = my_list.pop(2) # Remove and return element at index 2
my_list.clear() # Remove all elements
Other List Methods
my_list.sort() # Sort list in ascending order
my_list.reverse() # Reverse the list
my_list.count('a') # Count occurrences of 'a'
len(my_list) # Get the number of elements
2. Tuples
Creating a Tuple
my_tuple = (1, 2, 3, 'a', 'b')
Accessing Elements
print(my_tuple[1]) # Output: 2
Slicing
print(my_tuple[1:3]) # Output: (2, 3)
Tuple Unpacking
a, b, c = (1, 2, 3) # Assign 1 to a, 2 to b, 3 to c
Tuple Methods
my_tuple.count(1) # Count occurrences of 1
my_tuple.index('a') # Find the index of 'a'
Note: Tuples are immutable, meaning elements cannot be modified after creation.
De
3. Sets
Creating a Set
e_
cod
my_set = {1, 2, 3, 'a'}
Adding/Removing Elements
my_set.add(4) # Add an element
my_set.remove(2) # Remove an element (raises error if not found)
es
my_set.discard(5) # Remove element if present (no error if not
found)
Set Operations
set1 = {1, 2, 3}
set2 = {3, 4, 5}
union = set1 | set2 # Union: {1, 2, 3, 4, 5}
intersection = set1 & set2 # Intersection: {3}
difference = set1 - set2 # Difference: {1, 2}
Other Set Methods
set1.isdisjoint(set2) # Check if sets have no elements in common
set1.issubset(set2) # Check if set1 is a subset of set2
len(my_set) # Get the number of elements
4. Dictionaries
Creating a Dictionary
my_dict = {"name": "John", "age": 25, "city": "New York"}
Accessing Elements
print(my_dict["name"]) # Output: John
print(my_dict.get("age")) # Output: 25
Adding/Modifying Elements
my_dict["email"] = "[email protected]" # Add new key-value pair
my_dict["age"] = 26 # Modify existing value
Removing Elements
del my_dict["city"] # Delete the key-value pair 'city'
my_dict.pop("email") # Remove and return value of 'email'
De
my_dict.clear() # Remove all elements
Iterating Over a Dictionary
e_
for key, value in my_dict.items():
print(key, value)
Dictionary Methods
cod
my_dict.keys() # Get all keys
my_dict.values() # Get all values
my_dict.items() # Get all key-value pairs
2. OBJECT ORIENTED PROGRAMMING
1. Creating a Class
class MyClass:
def __init__(self, name):
self.name = name
def greet(self):
# Constructor
# Instance attribute
# Instance method
print(f"Hello, {self.name}!")
es
# Creating an object (instance of MyClass)
obj = MyClass("Alice")
obj.greet() # Output: Hello, Alice!
__init__ Method (Constructor)
Used to initialize objects.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
2. Class Attributes vs Instance Attributes
Class Attributes
Shared across all instances of the class.
class Employee:
company = "Google" # Class attribute
def __init__(self, name):
self.name = name # Instance attribute
emp1 = Employee("John")
emp2 = Employee("Jane")
print(emp1.company) # Output: Google
print(emp2.company) # Output: Google
De
Instance Attributes
Unique to each instance.
e_
emp1.company = "Amazon" # Changing instance attribute, not class attribute
print(emp1.company) # Output: Amazon
print(emp2.company) # Output: Google (unchanged for emp2)
3. Methods
Instance Methods
Operate on object instances.
cod
class Dog:
def __init__(self, name):
self.name = name
def bark(self): # Instance method
print(f"{self.name} is barking!")
Class Methods
es
Operate on the class itself, not instances. Use @classmethod.
class Cat:
species = 'Feline'
@classmethod
def print_species(cls): # 'cls' refers to the class
print(f"Species: {cls.species}")
Static Methods
Do not depend on instance or class attributes. Use @staticmethod.
class Utility:
@staticmethod
def add(a, b):
return a + b
print(Utility.add(3, 5)) # Output: 8
4. Inheritance
Basic Inheritance
Allows one class to inherit the attributes and methods of another class.
class Animal:
def __init__(self, name):
De
self.name = name
def speak(self):
print(f"{self.name} makes a sound.")
e_
class Dog(Animal): # Dog inherits from Animal
def speak(self):
print(f"{self.name} barks.")
dog = Dog("Buddy")
cod
dog.speak() # Output: Buddy barks.
super() Function
Calls the parent class's methods.
es
class Bird(Animal):
def __init__(self, name, wingspan):
super().__init__(name) # Call parent class constructor
self.wingspan = wingspan
5. Encapsulation
Public, Protected, and Private Attributes
Public Attributes: Accessible anywhere.
class Car:
def __init__(self, brand):
self.brand = brand # Public attribute
Protected Attributes: Indicated by a single underscore _, meant for internal use, but
still accessible.
class Car:
def __init__(self, brand):
self._brand = brand # Protected attribute
Private Attributes: Indicated by double underscore __, not accessible directly.
class Car:
def __init__(self, brand):
self.__brand = brand # Private attribute
Accessing Private Attributes (Name Mangling)
car = Car("Tesla")
print(car._Car__brand) # Access private attribute with name mangling
6. Polymorphism
De
Method Overriding
Redefining a method in a derived class that exists in the parent class.
e_
class Shape:
def area(self):
pass
cod
class Circle(Shape):
def area(self):
return 3.14 * self.radius ** 2
Duck Typing
es
If it behaves like a duck, it's a duck. Focuses on methods rather than inheritance.
class Dog:
def sound(self):
print("Bark")
class Cat:
def sound(self):
print("Meow")
def animal_sound(animal):
animal.sound()
animal_sound(Dog()) # Output: Bark
animal_sound(Cat()) # Output: Meow
7. Abstraction
Abstract Classes
Cannot instantiate abstract classes directly; used as a blueprint.
Use abc module to define abstract classes.
from abc import ABC, abstractmethod
class Animal(ABC):
@abstractmethod
def sound(self):
pass # Define an abstract method
class Dog(Animal):
def sound(self):
print("Bark")
dog = Dog() # Must implement abstract method
dog.sound() # Output: Bark
8. Multiple Inheritance
De
Multiple Inheritance Example
class A:
e_
def method_a(self):
print("Method A")
class B:
def method_b(self):
cod
print("Method B")
class C(A, B):
pass
obj = C()
obj.method_a() # Output: Method A
es
obj.method_b() # Output: Method B
3. FUNCTIONS
Defining a Function
Basic Syntax
def function_name(parameters):
# function body
return result
Example
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # Output: Hello, Alice!
2. Function Arguments
Positional Arguments
Passed by position in the function call.
def add(a, b):
return a + b
add(2, 3) # Output: 5
Keyword Arguments
Passed by name during function call.
def describe(name, age):
De
return f"{name} is {age} years old."
describe(age=25, name="Alice") # Output: Alice is 25 years old.
Default Arguments
e_
Assign default values to parameters.
def greet(name, message="Hello"):
cod
return f"{message}, {name}!"
greet("Alice") # Output: Hello, Alice!
greet("Alice", "Hi") # Output: Hi, Alice!
es
3. Variable-length Arguments
*args (Positional Variable-Length)
Allows passing multiple arguments.
def add(*args):
return sum(args)
add(1, 2, 3, 4) # Output: 10
**kwargs (Keyword Variable-Length)
Allows passing multiple keyword arguments.
def greet(**kwargs):
return f"{kwargs['greeting']}, {kwargs['name']}!"
greet(greeting="Hi", name="Bob") # Output: Hi, Bob!
4. Scope
Local Scope
Variables defined within a function are local to that function.
def my_func():
x = 10 # Local variable
print(x)
my_func() # Output: 10
Global Scope
Variables defined outside any function are global.
x = 20 # Global variable
De
def my_func():
print(x) # Accessing global variable
my_func() # Output: 20
Using global Keyword
e_
Modify global variables inside a function.
x = 5
def modify_global():
global x
x = 10 cod
es
modify_global()
print(x) # Output: 10
5. Returning Values
Returning a Single Value
def square(x):
return x ** 2
result = square(4) # Output: 16
Returning Multiple Values
def coordinates():
return (1, 2, 3)
x, y, z = coordinates() # x=1, y=2, z=3
6. Recursion
Basic Recursive Function
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120
Base Case and Recursive Case
Base case stops recursion, and recursive case calls the function again.
De
7. *args and **kwargs
Using *args
e_
Accepts a variable number of positional arguments.
def add(*args):
return sum(args)
print(add(1, 2, 3)) # Output: 6
cod
es
Using **kwargs
Accepts a variable number of keyword arguments.
def greet(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
greet(name="Alice", age=25) # Output: name: Alice, age: 25
8. Built-in Functions (Useful Examples)
map(): Apply a function to each item in an iterable.
python
Copy code
list(map(lambda x: x * 2, [1, 2, 3])) # Output: [2, 4, 6]
filter(): Filter items based on a condition.
python
Copy code
list(filter(lambda x: x % 2 == 0, [1, 2, 3])) # Output: [2]
sorted(): Sort items in an iterable.
python
Copy code
sorted([3, 1, 2]) # Output: [1, 2, 3]
4. FILE HANDLING
Opening and Closing Files
Basic Syntax:
De
file_object = open("filename", "mode")
file_object.close()
2. File Modes:
e_
'r': Read (default)
'w': Write (overwrites file if exists)
'a': Append (adds to file if exists)
cod
'b': Binary mode
'x': Create (fails if file exists)
't': Text mode (default)
'r+': Read + Write
es
3. Reading Files
Reading Entire File:
with open("file.txt", "r") as file:
content = file.read()
print(content)
Reading Line by Line:
with open("file.txt", "r") as file:
for line in file:
print(line)
readline(): Reads one line at a time.
with open("file.txt", "r") as file:
line = file.readline()
print(line)
readlines(): Returns a list of lines.
with open("file.txt", "r") as file:
lines = file.readlines()
print(lines)
4. Writing Files
Writing with 'w' (Overwrites):
with open("file.txt", "w") as file:
file.write("Hello, world!")
Appending with 'a':
with open("file.txt", "a") as file:
file.write("\nAdding a new line.")
5. File Object Methods
De
file.seek(offset): Move to specific position in file.
file.tell(): Get current position in file.
file.flush(): Flush the internal buffer.
file.truncate(): Resize the file.
e_
6. Working with Binary Files
Writing Binary:
file.write(b"Binary data")
Reading Binary:
cod
with open("file.bin", "wb") as file:
with open("file.bin", "rb") as file:
data = file.read()
print(data)
7. Checking if File Exists
Using os module:
es
import os
if os.path.exists("file.txt"):
print("File exists")
else:
print("File does not exist")
5. Exception Handling
1. Basic Try-Except Syntax
Syntax:
try:
# Code that may raise an exception
except ExceptionType:
# Code that runs if an exception occurs
Example:
try:
num = 1 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
2. Catching Multiple Exceptions
Using Multiple except Blocks:
De
try:
x = int(input("Enter a number: "))
y = 1 / x
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
e_
print("You cannot divide by zero!")
Using Single except Block:
cod
try:
x = int(input("Enter a number: "))
y = 1 / x
except (ValueError, ZeroDivisionError) as e:
print(f"Error occurred: {e}")
es
3. Finally Block
The finally block runs no matter what happens in the try block:
try:
file = open("file.txt", "r")
# Some code that may raise an exception
except FileNotFoundError:
print("File not found")
finally:
file.close()
print("File closed")
4. Else Block
Runs if no exceptions occur:
try:
file = open("file.txt", "r")
except FileNotFoundError:
print("File not found")
else:
print("File opened successfully")
file.close()
5. Raising Exceptions
Manually raising an exception:
try:
raise ValueError("Invalid value")
except ValueError as e:
print(e)
6. Custom Exceptions
Creating a Custom Exception:
class MyError(Exception):
De
pass
def check_value(value):
if value < 0:
raise MyError("Value cannot be negative")
e_
try:
check_value(-1)
except MyError as e:
print(e)
Modules and Packages
1. Importing Modules cod
Basic import:
python
Copy code
import module_name
Import specific functions or classes:
python
es
Copy code
from module_name import function_name, ClassName
Import with an alias:
python
Copy code
import module_name as alias
2. Accessing Module Content
Calling functions from imported module:
python
Copy code
import math
result = math.sqrt(16)
print(result) # Output: 4.0
Importing multiple functions:
python
Copy code
from math import sqrt, ceil
result = ceil(sqrt(10))
List of all functions and attributes of a module:
python
De
Copy code
import module_name
print(dir(module_name))
3. Creating a Module
python
e_
Create your own module by saving functions/classes in a .py file:
cod
Copy code
# In my_module.py
def greet(name):
print(f"Hello, {name}!")
Importing your custom module:
python
Copy code
import my_module
my_module.greet("John")
4. Packages (Directories of Modules)
Structure:
es
markdown
Copy code
my_package/
__init__.py
module1.py
module2.py
Importing a module from a package:
python
Copy code
from my_package import module1
Importing specific functions or classes:
python
Copy code
from my_package.module1 import function_name
De
e_
cod
es