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

Synapse Club

The document is a comprehensive guide to Python programming, covering essential concepts such as variables, data types, operators, control flow, and data structures like lists, tuples, dictionaries, and sets. It includes code snippets and examples to demonstrate the use of various Python features, including functions, comments, and input handling. Additionally, it explains loops, conditional expressions, and the use of modules and package management with pip.
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)
14 views

Synapse Club

The document is a comprehensive guide to Python programming, covering essential concepts such as variables, data types, operators, control flow, and data structures like lists, tuples, dictionaries, and sets. It includes code snippets and examples to demonstrate the use of various Python features, including functions, comments, and input handling. Additionally, it explains loops, conditional expressions, and the use of modules and package management with pip.
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/ 32

THE ULTIMATE PYTHON

CODEBOOK
A Comprehensive Collection of Python Code
Snippets Covering Essential Concepts
WHAT IS PROGRAMMING?
Just like we use Hindi or English to communicate with each other, we use a programming
language like Python to communicate with the computer.

Programming is a way to instruct the computer to perform various tasks.

MODULES, COMMENTS & PIP


print("hello world") # print is a function (more later)

hello world

MODULES

A module is a file containing code written by somebody else (usually) which can be imported and
used in our programs.

PIP

Pip is the package manager for python. You can use pip to install a module on your system

pip install pandas

COMMENTS

# print("AI/ML/DL")

Multiline Comments

""" AI/Ml/DL is a amazing domain of this world."""

VARIABLES AND DATATYPE


a = 45 # variables = container to store a value.
b = "Ai" # keywords = reserved words in python
c = 722.3 # identifiers = class/function/variable name

DATA TYPES

Primarily these are the following data types in Python:

1. Integers
2. Floating point numbers
3. Strings
4. Booleans
5. None
a= 71 # identifies a as class <int>
b=88.44 # identifies b as class <float>
name= "ML" # identifies name as class <str>

OPERATORS IN PYTHON
1. Arithmetic operators: +, -, *, / etc.
2. Assignment operators: =, +=, -= etc.
3. Comparison operators: ==, >, >=, <, != etc.
4. Logical operators: and, or, not.

TYPE() FUNCTION AND TYPECASTING.

a = "ai"
type(a)

str

a = 90
type(a)

int

a = 345.687689
type(a)

float

a = True
type(a)

bool

INPUT () FUNCTION

A = input ("enter name : ")

enter name : Rishabh

A = int(input ("enter Age : "))

enter Age : 23

A = float(input ("enter yout weights : "))

enter yout weights : 45.677

A = str(input ("enter name : "))

enter name : rishabh


STRINGS
a ='AI/dl' # Single quoted string
b = "AI/nlp" # Double quoted string
c = '''AI/ml''' # Triple quoted string

print(a,b,c)

AI/dl AI/nlp AI/ml

STRING SLICING

word = "Synapse"
Word = word[:4]
print(Word)

Syna

word = "Synapse"
word[1: 6: 2]

{"type":"string"}

STRING FUNCTIONS

Len

str = "Ai/ML/Dl"
print(len(str))

String.endswith

str = "Rishabh"
print(str.endswith("bh"))
True

string.count("")

str = "Rishabh"
count = str.count("h")
print(count)

The first character of a given string

str = "rishabh"
capitalized_string = str.capitalize()
print(capitalized_string)

Rishabh

string.find

str = "rishabh"
index = str.find("ab")
print(index)

string.replace

str = "lishabh"
replaced_string = str.replace("l", "r")
print(replaced_string)

rishabh

ESCAPE SEQUENCE CHARACTERS

print("Escape Sequence Characters in Python:\n")


print("1. New Line: Hello\nWorld") # \n for new line
print("2. Tab Space: Hello\tWorld") # \t for tab space
print("3. Backslash: C:\\Users\\User") # \\ for backslash
print("4. Single Quote: It\'s a beautiful day!") # \' for single
quote
print("5. Double Quote: He said \"Hello!\"") # \" for double quote
print("6. Backspace: Hello\bWorld") # \b for backspace
print("7. Carriage Return: Hello\rWorld") # \r for carriage return
print("8. Form Feed: Hello\fWorld") # \f for form feed
print("9. Unicode Character: \u2764") # Unicode for heart symbol
print("10. Octal Value: \110\145\154\154\157") # Octal value for
'Hello'
print("11. Hex Value: \x48\x65\x6C\x6C\x6F") # Hexadecimal value for
'Hello'

Escape Sequence Characters in Python:

1. New Line: Hello


World
2. Tab Space: Hello World
3. Backslash: C:\Users\User
4. Single Quote: It's a beautiful day!
5. Double Quote: He said "Hello!"
6. Backspace: HelloWorld
7. Carriage Return: Hello World
8. Form Feed: HelloWorld
9. Unicode Character: ❤
10. Octal Value: Hello
11. Hex Value: Hello

#LISTS AND TUPLES

Python lists are containers to store a set of values of any data type.

A list in Python is a built-in data structure that allows you to store multiple items in a single
variable. Lists are ordered, mutable (modifiable), and allow duplicate values.

l = [7,9,"harry",False]

Lists can be nested:

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


print(nested_list)

[[1, 2, 3], ['a', 'b', 'c']]

LIST INDEXING

l1 = [7,9,"harry"]
print(l1[0]) # 7
print(l1[1]) # 9
print(l1[0:2]) # [7,9] #list slicing

7
9
[7, 9]

LIST METHODS.

l1 = [1, 8, 7, 2, 21, 15]


print("Original List:", l1)
# Sorting the list
l1.sort()
print("Sorted List:", l1) # [1, 2, 7, 8, 15, 21]

# Reversing the list


l1.reverse()
print("Reversed List:", l1) # [21, 15, 8, 7, 2, 1]

# Appending an element
l1.append(8)
print("After Appending 8:", l1) # Adds 8 at the end

# Inserting an element at index 3


l1.insert(3, 8)
print("After Inserting 8 at index 3:", l1)

# Popping element at index 2


popped_element = l1.pop(2)
print("After Popping Index 2:", l1)
print("Popped Element:", popped_element)

# Removing the first occurrence of 21


l1.remove(21)
print("After Removing 21:", l1)

Original List: [1, 8, 7, 2, 21, 15]


Sorted List: [1, 2, 7, 8, 15, 21]
Reversed List: [21, 15, 8, 7, 2, 1]
After Appending 8: [21, 15, 8, 7, 2, 1, 8]
After Inserting 8 at index 3: [21, 15, 8, 8, 7, 2, 1, 8]
After Popping Index 2: [21, 15, 8, 7, 2, 1, 8]
Popped Element: 8
After Removing 21: [15, 8, 7, 2, 1, 8]

TUPLES IN PYTHON

a = () # empty tuple
a = (1,) # tuple with only one element needs a comma
a = (1,7,2) # tuple with more than one element

# Creating a tuple
tup1 = (1, 2, 3, 4, 5)
print(tup1)

(1, 2, 3, 4, 5)

tup2 = (5,) # Single-element tuple


print(type(tup2)) # Output: <class 'tuple'>
not_a_tuple = (5) # Not a tuple
print(type(not_a_tuple)) # Output: <class 'int'>

<class 'tuple'>
<class 'int'>

tup = (10, 20, 30, 40, 50)

print(tup[0]) # First element: 10


print(tup[-1]) # Last element: 50
print(tup[1:4]) # Slicing: (20, 30, 40)

10
50
(20, 30, 40)

Tuple Operations

tup1 = (1, 2, 3)
tup2 = (4, 5, 6)
tup3 = tup1 + tup2 # Combines two tuples
print(tup3)

(1, 2, 3, 4, 5, 6)

tup = (7, 8) * 3
print(tup)

(7, 8, 7, 8, 7, 8)

#Checking Membership
tup = (10, 20, 30)
print(20 in tup) # Output: True
print(50 in tup) # Output: False

True
False

tup = ('a', 'b', 'c')


for item in tup:
print(item)

a
b
c

Tuple Methods count(value)

tup = (1, 2, 2, 3, 2, 4)
print(tup.count(2))
3

index(value)

tup = (10, 20, 30, 40)


print(tup.index(30))

Tuple Packing & Unpacking

tup = ("Apple", "Banana", "Cherry")


fruit1, fruit2, fruit3 = tup
print(fruit1) # Output: Apple
print(fruit2) # Output: Banana
print(fruit3) # Output: Cherry

Apple
Banana
Cherry

Why Use Tuples Instead of Lists?

Immutability → Prevents accidental changes.

Faster than lists.

Memory-efficient due to fixed size.

Used as dictionary keys (lists cannot be used as dictionary keys).

#DICTIONARY & SETS

A dictionary (dict) is an unordered, mutable, and indexed collection of key-value pairs.

Key Features of Dictionaries: Keys must be unique and immutable (strings, numbers, tuples).
Values can be anything (numbers, lists, another dictionary, etc.). Uses hashing for fast lookup.

student = {
"name": "Rishabh",
"age": 20,
"course": "Data Science"
}

print(student["name"])

Rishabh

a = {
"key": "value",
"harry": "code",
"marks": "100",
"list": [1, 2, 9]
}
print(a["key"])
print(a["list"])

value
[1, 2, 9]

DICTIONARY METHODS

• a.items(): Returns a list of (key,value)tuples.

• a.keys(): Returns a list containing dictionary's keys . • a.update({"friends":}): Updates the


dictionary with supplied key-value pairs.

• a.get("name"): Returns the value of the specified keys (and value is returned eg."harry" is
returned here).

Adding & Updating Elements

student = {
"name": "Rishabh",
"age": 20,
"course": "Data Science"
}
student["age"] = 21
student["college"] = "IIT Patna"
print(student)

{'name': 'Rishabh', 'age': 21, 'course': 'Data Science', 'college':


'IIT Patna'}

Removing Elements

del student["age"]
student.pop("course")

{"type":"string"}

print(student)

{'name': 'Rishabh', 'college': 'IIT Patna'}

Looping Through a Dictionary

for key, value in student.items():


print(key, "->", value)

name -> Rishabh


college -> IIT Patna
Sets in Python
A set is an unordered collection of unique elements.

Key Features of Sets:

No duplicate elements.

Unordered (no indexing).

Mutable, but only holds immutable data types.

s = set()
s.add(1)
s.add(2)

print(s)

{1, 2}

PROPERTIES OF SETS

1. Sets are unordered => Element’s order doesn’t matter


2. Sets are unindexed => Cannot access elements by index
3. There is no way to change items in sets.
4. Sets cannot contain duplicate values.

OPERATIONS ON SETS

# Creating a set
s = {1, 2, 3, 8}

# Getting the length of the set


print("Length of set:", len(s)) # Output: 4

# Removing an element (8) from the set


s.remove(8)
print("Set after removing 8:", s) # Output: {1, 2, 3}

# Popping an arbitrary element


removed_element = s.pop()
print("Popped element:", removed_element)
print("Set after pop:", s)

# Clearing the set


s.clear()
print("Set after clear:", s) # Output: set()

# Re-creating the set for union and intersection operations


s = {1, 2, 3}
new_set = {8, 11}
# Union of sets
union_set = s.union(new_set)
print("Union of sets:", union_set) # Output: {1, 2, 3, 8, 11}

# Intersection of sets
intersection_set = s.intersection(new_set)
print("Intersection of sets:", intersection_set) # Output: set()

Length of set: 4
Set after removing 8: {1, 2, 3}
Popped element: 1
Set after pop: {2, 3}
Set after clear: set()
Union of sets: {1, 2, 3, 8, 11}
Intersection of sets: set()

CONDITIONAL EXPRESSION
A conditional expression in Python allows you to write if-else conditions in a single line using the
ternary operator.

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

# If else statement
if(a>=18):
print("You are above the age of consent")
print("Good for you")

else:
print("You are below the age of consent")

print("End of Program")

Enter your age: 45


You are above the age of consent
Good for you
End of Program

RELATIONAL OPERATORS

Relational Operators are used to evaluate conditions inside the if statements. Some examples of
relational operators are:
LOGICAL OPERATORS

In python logical operators operate on conditional statements. For Example:

• and : true if both operands are true else false.

• or : true if at least one operand is true or else false.

• not : inverts true to false & false to true.

ELIF CLAUSE

marks = int(input("Enter a marks : "))

if marks >= 90:


print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
elif marks >= 60:
print("Grade: C")
else:
print("Grade: F") # Failing grade

Enter a marks : 45
Grade: F
LOOPS IN PYTHON
TYPES OF LOOPS IN PYTHON

1.for loop – Used for iterating over sequences (lists, tuples, strings, etc.)

2.while loop – Repeats as long as a condition is True.

for loop

fruits = ["apple", "banana", "cherry"]


for fruit in fruits:
print(fruit)

apple
banana
cherry

for i in range(1, 6):


print(i)

1
2
3
4
5

for char in "Python":


print(char)

P
y
t
h
o
n

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

for i in range(1, 11):


print(f"{n} X {i} = {n * i}")

Enter a number: 90
90 X 1 = 90
90 X 2 = 180
90 X 3 = 270
90 X 4 = 360
90 X 5 = 450
90 X 6 = 540
90 X 7 = 630
90 X 8 = 720
90 X 9 = 810
90 X 10 = 900

def table():
n = int(input("Enter a number "))
for i in range(1,11):
print(f"{n}X{i} = {n*i}")
table()

Enter a number 78
78X1 = 78
78X2 = 156
78X3 = 234
78X4 = 312
78X5 = 390
78X6 = 468
78X7 = 546
78X8 = 624
78X9 = 702
78X10 = 780

while Loop

count = 1
while count <= 5:
print(count)
count += 1

1
2
3
4
5

password = ""
while password != "secret":
password = input("Enter password: ")
print("Access granted!")

Enter password: 79459*/-


Enter password: 43536dfg
Enter password: 756+
Enter password: 78680-l
Enter password: 68709
Enter password: 784509i
Enter password: ewret-0p
Enter password: secret
Access granted!
i = 0
while i < 5:
print("Synapse")
i = i + 1

Synapse
Synapse
Synapse
Synapse
Synapse

THE BREAK STATEMENT

for i in range(1, 6):


if i == 3:
break
print(i)

1
2

continue – Skips the current iteration

for i in range(1, 6):


if i == 3:
continue
print(i)

1
2
4
5

else with Loops

for i in range(1, 4):


print(i)
else:
print("Loop completed successfully!")

1
2
3
Loop completed successfully!

Nested Loops

for i in range(1, 4):


for j in range(1, 4):
print(i, "*", j, "=", i * j)
print()

1 * 1 = 1
1 * 2 = 2
1 * 3 = 3

2 * 1 = 2
2 * 2 = 4
2 * 3 = 6

3 * 1 = 3
3 * 2 = 6
3 * 3 = 9

PASS STATEMENT

It instructs to “do nothing”.

l = [1,7,8]
for item in l:
pass

FUNCTIONS & RECURSIONS


Functions in Python Functions allow us to organize code into reusable blocks.

def func1():
print('hello')
func1()

hello

Types of Functions

1 Built-in Functions Python has many built-in functions like print(), len(), sum(), etc.
1️⃣

2️⃣User-Defined Functions We can define our own functions using def.

Basic Built-in Functions

x = 10
print("Value of x:", x)
print("Data type of x:", type(x))
print("Memory location of x:", id(x))
Value of x: 10
Data type of x: <class 'int'>
Memory location of x: 10751144

def greet(name):
gr = "hello" + name
return gr
a = greet ("ai")
print(a)

helloai

RECURSION

Recursion is a process where a function calls itself to solve a problem. It is useful for problems
that can be broken down into smaller subproblems

#Factorial of a Number
def factorial(n):
if n == 0 or n == 1: # Base Case
return 1
else:
return n * factorial(n - 1) # Recursive Call

print(factorial(5)) # Output: 120

120

#Fibonacci Sequence
def fibonacci(n):
if n <= 0:
return "Invalid Input"
elif n == 1:
return 0
elif n == 2:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2) # Recursive Call

print(fibonacci(6)) # Output: 5

#Sum of First n Natural Numbers


def sum_natural(n):
if n == 0: # Base Case
return 0
else:
return n + sum_natural(n - 1) # Recursive Call

print(sum_natural(5)) # Output: 15 (1+2+3+4+5)

15

#Reverse a String Using Recursion


def reverse_string(s):
if len(s) == 0: # Base Case
return s
else:
return s[-1] + reverse_string(s[:-1]) # Recursive Call

print(reverse_string("hello")) # Output: "olleh"

olleh

FILE I/O
File I/O in Python allows us to read from and write to files. Python provides built-in functions to
handle files efficiently.

Opening a File

file = open("sampple1.txt", "w")

Mode Description

"r" Read mode (default). Opens a file for reading.

"w" Write mode. Creates a new file or overwrites an existing file.

"a" Append mode. Adds data at the end of the file.

"x" Exclusive creation mode. Fails if the file exists.


"b" Binary mode (e.g., "rb", "wb", "ab" for non-text files).

Writing Data to a File

file = open("sampple1.txt", "w") # Open file in write mode


file.write("Hello, this is a file handling example!") # Write data
file.close() # Close the file

<_io.TextIOWrapper name='sampple1.txt' mode='w' encoding='UTF-8'>

Reading a File

file = open("sampple1.txt", "r") # Open file in read mode


content = file.read() # Read the entire file
print(content) # Output: Hello, this is a file handling example!
file.close()

Hello, this is a file handling example!

Reading File Line by Line

Using readline() and readlines()

file = open("sampple1.txt", "r")


print(file.readline()) # Reads only the first line
file.close()

Hello, this is a file handling example!

file = open("sampple1.txt", "r")


lines = file.readlines() # Reads all lines into a list
print(lines) # Output: ['Hello, this is a file handling example!\n']
file.close()

['Hello, this is a file handling example!']

Appending Data to a File Using Append Mode

file = open("sampple1.txtt", "a") # Open file in append mode


file.write("\nAppending this new line.") # Adds new content at the
end
file.close()

Using with ensures the file is closed automatically

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


content = file.read()
print(content) # File is automatically closed after exiting the
block
Appending this new line.

Checking if a File Exists

import os

if os.path.exists("example.txt"):
print("File exists!")
else:
print("File not found!")

File exists!

Deleting a File

import os

if os.path.exists("example.txt"):
os.remove("example.txt") # Deletes the file
print("File deleted!")
else:
print("File not found!")

File deleted!

OBJECT ORIENTED PROGRAMMING


What is OOP?

Object-Oriented Programming (OOP) is a programming paradigm that organizes code into


objects. These objects represent real-world entities and have attributes (data) and methods
(functions).

INIT() CONSTRUCTOR

init() is a special method which is first run as soon as the object is created.

init() method is also known as constructor.

class Employee:
def __init__(self, name):
self.name=name
def getSalary(self):
...
harry = Employee("AI")

CLASS A class is a blueprint for creating object


OBJECT An object is an instantiation of a class. When class is defined, a template (info) is
defined. Memory is allocated only after object instantiation.

Defining a Class and Creating Objects

class Car:
def __init__(self, brand, model, year): # Constructor
self.brand = brand # Attribute
self.model = model
self.year = year

def display_info(self): # Method


print(f"Car: {self.brand} {self.model}, Year: {self.year}")

# Creating an object of the Car class


my_car = Car("Toyota", "Camry", 2022)
my_car.display_info() # Output: Car: Toyota Camry, Year: 2022

Car: Toyota Camry, Year: 2022

Encapsulation (Data Hiding)

class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number # Private attribute
self.__balance = balance # Private attribute

def deposit(self, amount):


self.__balance += amount

def withdraw(self, amount):


if amount <= self.__balance:
self.__balance -= amount
else:
print("Insufficient funds!")

def get_balance(self):
return self.__balance # Access private variable

# Creating an object
account = BankAccount("123456", 5000)
account.deposit(1000)
print(account.get_balance()) # Output: 6000

6000

Inheritance (Reusing Code) Inheritance allows a child class to inherit methods and attributes
from a parent class.
class Animal:
def __init__(self, name):
self.name = name

def speak(self):
return "Some sound"

class Dog(Animal): # Dog class inherits from Animal


def speak(self):
return "Bark"

class Cat(Animal):
def speak(self):
return "Meow"

dog = Dog("Buddy")
cat = Cat("Whiskers")

print(dog.name, "says:", dog.speak()) # Output: Buddy says: Bark


print(cat.name, "says:", cat.speak()) # Output: Whiskers says: Meow

Buddy says: Bark


Whiskers says: Meow

Polymorphism (Different Behavior for Same Method)

Polymorphism allows methods to have different implementations in different classes.

class Bird:
def fly(self):
return "Flying..."

class Sparrow(Bird):
def fly(self):
return "Sparrow flies low."

class Eagle(Bird):
def fly(self):
return "Eagle flies high."

# Using polymorphism
birds = [Sparrow(), Eagle()]

for bird in birds:


print(bird.fly())
# Output:
# Sparrow flies low.
# Eagle flies high.
Sparrow flies low.
Eagle flies high.

Abstraction (Hiding Implementation Details)

Abstraction is achieved using abstract classes and methods, which define a structure but leave
implementation to subclasses.

from abc import ABC, abstractmethod

class Vehicle(ABC): # Abstract class


@abstractmethod
def start(self):
pass

class Car(Vehicle):
def start(self):
print("Car is starting...")

class Bike(Vehicle):
def start(self):
print("Bike is starting...")

car = Car()
car.start() # Output: Car is starting...

Car is starting...

SUPER() METHOD

super() method is used to access the methods of a super class in the derived class

class Animal:
def __init__(self, name):
self.name = name
print(f"Animal {self.name} is created.")

class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calling Parent Constructor
self.breed = breed
print(f"Dog breed is {self.breed}")

# Creating an object
d = Dog("Buddy", "Golden Retriever")

Animal Buddy is created.


Dog breed is Golden Retriever
CLASS METHOD

A class method is a method which is bound to the class and not the object of the class.

@classmethod decorator is used to create a class method.

class Student:
school = "IIT Patna" # Class variable

@classmethod
def change_school(cls, new_school):
cls.school = new_school # Modifying class variable

# Calling class method


Student.change_school("IIT Delhi")
print(Student.school) # Output: IIT Delhi

IIT Delhi

@PROPERTY DECORATORS

class Student:
def __init__(self, name, marks):
self.name = name
self._marks = marks # Private attribute

@property
def marks(self): # Getter method
return self._marks # Read-only access

# Creating an object
s = Student("Rishabh", 90)

print(s.marks) # ✅ Accessing like an attribute (Output: 90)


# s.marks = 95 # ❌ AttributeError: can't set attribute

90

Example: Using @property for Getters and Setters

class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self._balance = balance # Private variable (conventionally
using `_`)

@property
def balance(self): # Getter method
"""Returns the account balance"""
return self._balance
@balance.setter
def balance(self, amount): # Setter method with validation
"""Sets a new balance if the amount is valid"""
if amount < 0:
raise ValueError("Balance cannot be negative!")
self._balance = amount

# Creating an object
account = BankAccount("Rishabh", 5000)

# Using the getter


print(account.balance) # ✅ Output: 5000

# Using the setter


account.balance = 7000 # ✅ Updating balance
print(account.balance) # ✅ Output: 7000

# Trying to set an invalid balance


# account.balance = -1000 # ❌ Raises ValueError: Balance cannot be
negative!

5000
7000

Summary of OOP Concepts

Class : A blueprint for objects.

Object : An instance of a class.

Encapsulation : Protecting data using private variables.

Inheritance : Reusing code by deriving a class from another.

Polymorphism : The same method behaves differently in different classes.

Abstraction : Hiding implementation details using abstract classes.

Exception Handling
Exception handling in Python allows you to manage and respond to runtime errors, preventing
your program from crashing. Python uses the try-except block for handling exceptions.

Basic Exception Handling

try:
a = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("You cannot divide by zero!")
You cannot divide by zero!

Handling Multiple Exceptions

try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("You cannot divide by zero!")
except ValueError:
print("Invalid input! Please enter a number.")

Enter a number: 10

Catching Any Exception

try:
print(10 / 0)
except Exception as e:
print("An error occurred:", e)

An error occurred: division by zero

Using else Block

try:
num = int(input("Enter a number: "))
result = 10 / num
except ZeroDivisionError:
print("Cannot divide by zero!")
else:
print("Division successful:", result)

Enter a number: 45
Division successful: 0.2222222222222222

Using finally Block

The finally block always executes, whether an exception occurs or not.

try:
file = open("sample.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Closing the program.")
File not found!
Closing the program.

Raising Custom Exceptions

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


if age < 18:
raise ValueError("You must be 18 or older to proceed!")

Enter your age: 45

** Creating a Custom Exception Class**

class CustomError(Exception):
pass

try:
raise CustomError("This is a custom exception!")
except CustomError as e:
print(e)

This is a custom exception!

Lambda Functions in Python


A lambda function in Python is a small, anonymous function defined using the lambda keyword.
It is often used for short, simple operations where defining a full function is unnecessary.

#Lambda Function for Addition


add = lambda x, y: x + y
print(add(5, 3))

# Using Lambda in map()


numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)

[1, 4, 9, 16, 25]

# Using Lambda in filter()


numbers = [1, 2, 3, 4, 5, 6]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)

[2, 4, 6]
# Using Lambda in sorted()
students = [("John", 20), ("Alice", 18), ("Bob", 22)]
sorted_students = sorted(students, key=lambda x: x[1])
print(sorted_students)

[('Alice', 18), ('John', 20), ('Bob', 22)]

# Using Lambda with reduce()


from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)

24

Debugging and Testing in Python


Debugging and testing are essential for writing reliable and error-free Python programs. Python
provides several built-in tools for debugging and different testing frameworks for verifying code
correctness.

Using print() for Debugging (Basic Method)

def add(a, b):


print(f"a: {a}, b: {b}") # Debugging print statement
return a + b

print(add(3, 5))

a: 3, b: 5
8

Using pdb (Python Debugger)

Commands in pdb

n (Next line)

s (Step into function)

c (Continue execution)

q (Quit debugger)

import pdb

def divide(a, b):


pdb.set_trace() # Start debugging
return a / b
print(divide(10, 2))

PYDEV DEBUGGER WARNING:


sys.settrace() should not be used when the debugger is being used.
This may cause the debugger to stop working correctly.
If this is needed, please check:
http://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-
with.html
to see how to restore the debug tracing back correctly.
Call Location:
File "/usr/lib/python3.11/bdb.py", line 336, in set_trace
sys.settrace(self.trace_dispatch)

> <ipython-input-109-8350b5630154>(5)divide()
3 def divide(a, b):
4 pdb.set_trace() # Start debugging
----> 5 return a / b
6
7 print(divide(10, 2))

ipdb> N
*** NameError: name 'N' is not defined
ipdb> Q
*** NameError: name 'Q' is not defined
ipdb> q

PYDEV DEBUGGER WARNING:


sys.settrace() should not be used when the debugger is being used.
This may cause the debugger to stop working correctly.
If this is needed, please check:
http://pydev.blogspot.com/2007/06/why-cant-pydev-debugger-work-
with.html
to see how to restore the debug tracing back correctly.
Call Location:
File "/usr/lib/python3.11/bdb.py", line 361, in set_quit
sys.settrace(None)

Using logging for Debugging

import logging

logging.basicConfig(level=logging.DEBUG)

def multiply(a, b):


logging.debug(f"Multiplying {a} and {b}")
return a * b

print(multiply(4, 5))

20

Testing in Python

Types of Testing

Unit Testing: Testing individual functions.

Integration Testing: Testing combined modules.

System Testing: Testing the entire application.

Unit Testing with unittest

Common Assertions in unittest:

assertEqual(a, b): Check if a == b

assertNotEqual(a, b): Check if a != b

assertTrue(x): Check if x is True

assertFalse(x): Check if x is False

assertRaises(Error, func, args): Check if an error is raised

import unittest

def add(a, b):


return a + b

class TestMathOperations(unittest.TestCase):
def test_add(self):
self.assertEqual(add(2, 3), 5) # Check if 2 + 3 = 5

if __name__ == "__main__":
unittest.main()

E
======================================================================
ERROR: /root/ (unittest.loader._FailedTest./root/)
----------------------------------------------------------------------
AttributeError: module '__main__' has no attribute '/root/'

----------------------------------------------------------------------
Ran 1 test in 0.001s

FAILED (errors=1)
An exception has occurred, use %tb to see the full traceback.

SystemExit: True

/usr/local/lib/python3.11/dist-packages/IPython/core/
interactiveshell.py:3561: UserWarning: To exit: use 'exit', 'quit', or
Ctrl-D.
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)

Testing with pytest (Advanced)

pip install pytest

Requirement already satisfied: pytest in


/usr/local/lib/python3.11/dist-packages (8.3.5)
Requirement already satisfied: iniconfig in
/usr/local/lib/python3.11/dist-packages (from pytest) (2.0.0)
Requirement already satisfied: packaging in
/usr/local/lib/python3.11/dist-packages (from pytest) (24.2)
Requirement already satisfied: pluggy<2,>=1.5 in
/usr/local/lib/python3.11/dist-packages (from pytest) (1.5.0)

def subtract(a, b):


return a - b

def test_subtract():
assert subtract(5, 3) == 2
assert subtract(10, 7) == 3

Best Practices

✅ Use logging instead of print().

✅ Write unit tests for critical functions.

✅ Use pdb for step-by-step debugging.

✅ Automate tests using pytest or unittest.

✅ Run tests frequently to catch bugs early.

Would you like to practice some debugging or testing exercises? 🚀

You might also like