Python
Python
Conditional statements are used to execute certain blocks of code based on logical conditions.
➤ Syntax:
python
if condition:
# code block
elif another_condition:
# another block
else:
# fallback block
These constructs are fundamental for flow control in any decision-making logic.
2. Looping Constructs
for Loop
Example:
for i in range(5):
print(i)
while Loop
Example:
i=0
while i < 5:
print(i)
i += 1
Nested Loops
Example:
for i in range(3):
for j in range(2):
print(i, j)
Syntax:
def function_name(parameters):
# function body
Example:
def greet(name):
print("Hello", name)
4. Return Statements
➤ Purpose:
Example:
return a + b
Lambda Functions
Anonymous functions defined using the lambda keyword. Used for short operations.
Syntax:
Example:
square = lambda x: x * x
🔹 Higher-Order Functions
Examples:
Recursion
Example:
def factorial(n):
if n == 1:
return 1
return n * factorial(n - 1)
Function Scope
1. Local
2. Enclosing
3. Global
4. Built-in
Built-in Functions
Common examples:
Example:
print(len("Python")) # Output: 6
Custom Functions
Syntax:
def my_function():
# code
➤ What is a List?
A list is a mutable, ordered collection of items. It can contain elements of different data types.
➤ List Creation:
➤ List Manipulation:
Update: my_list[1] = 10
*****************************************************************************
Text Files:
Modes: 'r' (read), 'w' (write), 'a' (append), 'rb', 'wb' (binary modes).
Example:
content = f.read()
CSV Files:
Use the csv module for reading and writing tabular data.
Example:
import csv
reader = csv.reader(f)
print(row)
JSON Files:
Example:
import json
with open('data.json') as f:
data = json.load(f)
Excel Files:
df = pd.read_excel('file.xlsx')
os Module:
Common Functions:
Purpose:
Syntax:
try:
# risky code
except ValueError:
# handle ValueError
except Exception as e:
finally:
finally Block:
raise Statement:
Used to throw an exception manually.
Example:
if age < 0:
class MyError(Exception):
pass
Logging:
Better than print statements for tracing program execution and debugging.
Example:
import logging
logging.basicConfig(level=logging.INFO)
logging.info("Program started")
Log Levels:
Class: A class is a blueprint for creating objects. It defines attributes (data) and methods (functions)
that are common to all objects of that type.
Object: An object is an instance of a class. It represents a real-world entity with attributes and
behaviors.
Example:
class Dog:
def bark(self):
print('Woof')
dog1 = Dog()
Instance Variables: These are variables defined inside the constructor (__init__) using self keyword
and are specific to each object (instance) of the class.
Class Variables: These are shared across all instances of the class. They are declared inside the class
but outside of any method.
Example:
class Car:
car1 = Car("Red")
car2 = Car("Blue")
The __init__ method is a special method in Python, known as a constructor. It is automatically invoked
when a new object of the class is created. It is used to initialize the attributes of the object.
Example:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# Creating an object
print(person1.age) # Output: 25
Inheritance: Inheritance allows a class to inherit methods and attributes from another class.
Types of Inheritance:
Multiple Inheritance: A class inherits from more than one base class.
Multilevel Inheritance: A class inherits from another class, which is already derived from a third
class.
Example:
Single Inheritance:
class Animal:
def speak(self):
print("Animal speaking")
class Dog(Animal):
def bark(self):
print("Woof")
dog = Dog()
Multiple Inheritance:
class Animal:
def speak(self):
print("Animal speaking")
class Dog:
def bark(self):
print("Woof")
pass
dog_animal = DogAnimal()
Method Overriding: Method overriding is the process of redefining a method in a derived class that
already exists in the base class, allowing for specialized behavior in the derived class.
Example:
class Animal:
def sound(self):
class Dog(Animal):
def sound(self):
print("Bark")
animal = Animal()
dog = Dog()
Encapsulation: Encapsulation is the concept of restricting access to some of the object's attributes
or methods to protect the object’s internal state. This is achieved by using private variables and
methods.
Private Variables: Variables that are meant to be inaccessible from outside the class are prefixed
with double underscores (__). These variables can still be accessed using special methods, but it's
not recommended.
Example:
class Account:
def __init__(self):
self.__balance += amount
def get_balance(self):
return self.__balance
account = Account()
account.deposit(1000)
You can still access it indirectly using getter methods like get_balance()