Synapse Club
Synapse Club
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.
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
COMMENTS
# print("AI/ML/DL")
Multiline Comments
DATA TYPES
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.
a = "ai"
type(a)
str
a = 90
type(a)
int
a = 345.687689
type(a)
float
a = True
type(a)
bool
INPUT () FUNCTION
enter Age : 23
print(a,b,c)
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)
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
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]
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.
# Appending an element
l1.append(8)
print("After Appending 8:", l1) # Adds 8 at the end
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)
<class 'tuple'>
<class 'int'>
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
a
b
c
tup = (1, 2, 2, 3, 2, 4)
print(tup.count(2))
3
index(value)
Apple
Banana
Cherry
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.get("name"): Returns the value of the specified keys (and value is returned eg."harry" is
returned here).
student = {
"name": "Rishabh",
"age": 20,
"course": "Data Science"
}
student["age"] = 21
student["college"] = "IIT Patna"
print(student)
Removing Elements
del student["age"]
student.pop("course")
{"type":"string"}
print(student)
No duplicate elements.
s = set()
s.add(1)
s.add(2)
print(s)
{1, 2}
PROPERTIES OF SETS
OPERATIONS ON SETS
# Creating a set
s = {1, 2, 3, 8}
# 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.
# 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")
RELATIONAL OPERATORS
Relational Operators are used to evaluate conditions inside the if statements. Some examples of
relational operators are:
LOGICAL OPERATORS
ELIF CLAUSE
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.)
for loop
apple
banana
cherry
1
2
3
4
5
P
y
t
h
o
n
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!")
Synapse
Synapse
Synapse
Synapse
Synapse
1
2
1
2
4
5
1
2
3
Loop completed successfully!
Nested Loops
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
l = [1,7,8]
for item in l:
pass
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️⃣
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
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
15
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
Mode Description
Reading a File
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!
INIT() CONSTRUCTOR
init() is a special method which is first run as soon as the object is created.
class Employee:
def __init__(self, name):
self.name=name
def getSalary(self):
...
harry = Employee("AI")
class Car:
def __init__(self, brand, model, year): # Constructor
self.brand = brand # Attribute
self.model = model
self.year = year
class BankAccount:
def __init__(self, account_number, balance):
self.__account_number = account_number # Private attribute
self.__balance = balance # Private attribute
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 Cat(Animal):
def speak(self):
return "Meow"
dog = Dog("Buddy")
cat = Cat("Whiskers")
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()]
Abstraction is achieved using abstract classes and methods, which define a structure but leave
implementation to subclasses.
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")
A class method is a method which is bound to the class and not the object of the class.
class Student:
school = "IIT Patna" # Class variable
@classmethod
def change_school(cls, new_school):
cls.school = new_school # Modifying class variable
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)
90
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)
5000
7000
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.
try:
a = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("You cannot divide by zero!")
You cannot divide by zero!
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
try:
print(10 / 0)
except Exception as e:
print("An error occurred:", e)
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
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.
class CustomError(Exception):
pass
try:
raise CustomError("This is a custom exception!")
except CustomError as e:
print(e)
[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)
24
print(add(3, 5))
a: 3, b: 5
8
Commands in pdb
n (Next line)
c (Continue execution)
q (Quit debugger)
import pdb
> <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
import logging
logging.basicConfig(level=logging.DEBUG)
print(multiply(4, 5))
20
Testing in Python
Types of Testing
import unittest
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)
def test_subtract():
assert subtract(5, 3) == 2
assert subtract(10, 7) == 3
Best Practices