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

Python Job Level Material

This document provides an introduction to Python, highlighting its key features such as simple syntax, versatility, and extensive standard library. It covers various applications of Python including AI, web development, and data science, as well as fundamental concepts like data types, control structures, and collections. Additionally, it discusses functions, their definitions, and usage in Python programming.
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)
5 views

Python Job Level Material

This document provides an introduction to Python, highlighting its key features such as simple syntax, versatility, and extensive standard library. It covers various applications of Python including AI, web development, and data science, as well as fundamental concepts like data types, control structures, and collections. Additionally, it discusses functions, their definitions, and usage in Python programming.
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/ 202

Python

Brahmas Infotech Solutions Private Limited


Introduction to Python
• Python is a high-level, interpreted programming language known
for its:
• Simple syntax (easy to read and write)
• Versatility (used in web development, data science, AI,
automation, etc.)
• Large standard library
• Support for multiple programming paradigms: object-oriented,
functional, and procedural
• It is one of the most popular and beginner-friendly programming
languages in the world.
Topics covered
Key Features of Python
Applications of Python
Key Features of Python
• Easy to Learn and Read
1. Clean and simple syntax (like English).
2. Ideal for beginners and professionals.

print("Hello, World!")
• Interpreted Language
1. No need to compile; Python code runs line by line.
2. Easy to test and debug.

• Dynamically Typed
1. You don't need to declare variable types.
x = 10 # No need to say int x = 10

• Object-Oriented and Functional


1. Supports OOPS: classes, inheritance, encapsulation.
2. Also supports functional programming:lambda,filter,,map, reduce
Key Features of Python continued
• Extensive Standard Library
Comes with many built-in modules for:
• File I/O
• Math
• Web access
• JSON
• Databases
• and more
Applications of Python

• Artificial Intelligence (AI) & Machine Learning (ML)


• Data Science & Data Analysis
• Web Development
• Automation & Scripting (Task Automation)
• Software Development
• Scientific & Numeric Computing
• Cybersecurity & Ethical Hacking
• Game Development
Editors for python
• Jupyter Notebook
• VS Code (Visual Studio Code)
• PyCharm
• Thonny
• Sublime Text
• Atom
• Spyder
• Notepad++
Installation of Jupiter notebook
• For installing Jupiter notebook • https://www.youtube.com/
follow below link for this tutorial. watch?v=PxMN8xT9NbA
Data Types and Variables
Data
• Data type: A data type tells Python what
Types
type of data you are working with — like
numbers, text, or True/False.

• A variable is like a label attached to a Data Type Example Description

value, so you can use that label instead of


the value directly.
int x = 10 Integer (whole number)

Floating point (decimal)


float y = 10.5
number

str name = "Sam" String (text)

bool is_valid = True Boolean (True or False)


print() Function

• print("Hello, World!") • You can also print multiple


values:
print("Name:", "Lohitaksh")
f-strings (f-literals) in Python

• f-strings (also called formatted string literals) are a


powerful and readable way to format strings in Python.

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Input() function

• Used to take input from • name = input("Enter your


the user (always returns a name: ")
string). • print("Hello,", name)
Operators in python

Arithmetic Operators Operator Description Example Result


+ 3+2 5
• Used for basic -
Addition
3-2 1
Subtraction
mathematical operations: * Multiplication 3 * 2 6
/ Division 3/2 1.5
// Floor Division 3 // 2 1

% Modulus 3%2 1
(remainder)
** Exponentiatio 2 ** 3 8
n
Comparison Operators (Relational)

• Used to compare values


Operator Description Example
• Returns True or False == Equal to 3 == 3 → True
!= Not equal to 3 != 4 → True
> Greater than 5 > 2 → True
< Less than 2 < 5 → True

>= Greater or
5 >= 5 → True
equal
<= Less or equal 4 <= 5 → True
Logical Operators

• Used to combine
conditions Operator Description Example Result

True if both True and


and False
are true False

True if at
True or
or least one is True
False
true

Reverses
not not True False
the result
Assignment Operators

• Used to assign values to


Operator Example Meaning
variables.
= Assign 5 to
x=5
x
+= x += 2 x=x+2
-= x -= 1 x=x-1
*= x *= 3 x=x*3
/= x /= 2 x=x/2
//= x //= 2 x = x // 2
%= x %= 3 x=x%3
**= x **= 2 x = x ** 2
Membership Operators

• Test for presence in


sequences: Operator Example Result
in 'a' in 'apple' True
'x' not in
not in False
'box'
Indentation in Python
• Indentation refers to the spaces or tabs used at the
beginning of a line of code.
• Why is Indentation Important?
Unlike other languages like C, Java which use {} to
define the code blocks python uses indentation.
Conditional statements

• If statement
Executes a block of code only if the condition is
true.
if condition:
# code block
age = 18
if age >= 18:
print("You are eligible to vote.")
Conditional statemets
• If-else statement
Executes one block if the condition is true, another if it's false.
if condition:
# true block
else:
# false block
Example
age = 16
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
Conditional statemets
• If-elif-else ladder
Checks multiple conditions one by one.if condition:
if condition1:
# block 1
elif condition2:
# block 2
elif condition3:
# block 3
else:
# default block
range() Function in Python

• The range() function is used to generate sequence of


numbers , commonly used in loops.
range(stop) # 0 to stop-1
range(start, stop) # start to stop-1
range(start, stop, step) # start to stop-1 with steps
for Loop in Python

• for loop in python is used to iterate over a sequence.


for variable in sequence:
# code block
Break and continue with for
for i in range(5):
if i == 3:
break
print(i)
for Loop in Python

continue- skip the current iteration


for i in range(5):
if i == 2:
continue
print(i)
While Loop in Python

The while loop in python is used to repeat a block of code as


long as condition is True.
while condition:
# code block
i=1
while i <= 5:
print(i)
i += 1
Collections

 List
 Tuple
 Dictionary
 set
list

 List – A list is a mutuable collection of items . It can hold


elements of different datatypes.
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4]
mixed = [1, "hello", 3.14, True]
list

Creating a list using list constructor.


The list() constructor is used to create a new list from a iterable.
list(iterable)
s = "hello"
lst = list(s)
print(lst) # ['h', 'e', 'l', 'l', 'o']
List index

• my_list = ['apple', 'banana',


'cherry', 'date']

Index Element
0 apple
1 banana
2 cherry
3 date
list
Method Description Example
Adds item at the
append(x) list.append(5)
 List – A list is a mutuable end
list.insert(1,
insert(i, x) Inserts at index i
collection of items . It can "orange")
Removes first list.remove("apple"
hold elements of different remove(x)
occurrence of x )
datatypes. Removes and
pop(i) returns item at list.pop(2)
fruits = ["apple", "banana", index i
list.index("banana"
"cherry"] index(x) Returns index of x
)
count(x) Returns count of x list.count(1)
numbers = [1, 2, 3, 4] Sorts list in
sort() list.sort()
ascending order
mixed = [1, "hello", 3.14, Reverses list in
reverse() list.reverse()
True] place
clear() Empties the list list.clear()
Returns a shallow copy_list =
copy()
copy list.copy()
List comprehension

A compact way to create lists using a single line of code.


squares = [x**2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
Nested lists

A nested list is a list inside another list — useful for representing


tables, grids, matrices, etc.
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
Tuple

A tuple is an immutable, ordered collection of elements. It’s


similar to a list, but once a tuple is created, its values cannot
be changed.
Creating a Tuple
t = (1, 2, 3)
print(t) # (1, 2, 3)
Single-element tuple (note the comma!)
t = (5,)
Tuple

• Why Use Tuples?


• Faster than lists
• Safer (immutable = can't be modified accidentally)
• Can be used as dictionary keys
• Useful for fixed data (e.g., coordinates, RGB colors)
Tuple

Accessing Elements
t = (10, 20, 30)
print(t[0]) # 10
print(t[-1]) # 30
Tuple Methods

Method Description
.count(x) Returns number of times x occurs
.index(x) Returns index of first occurrence of x
Tuple

Tuple Packing and Unpacking


Packing
person = ("Alice", 25, "India")
name, age, country =
person```````````````````````````````````````````````````
print(name) # Alice
Unpacking
name, age, country = person
print(name) # Alice
Tuple

Tuples vs Lists

Feature Tuple List


Mutable ❌ No ✅ Yes
Syntax (1, 2) [1, 2]
Speed Faster Slower
Use Case Fixed data Dynamic data
Dictionaries

A dictionary is a collection of key-value pairs. It is ordered


mutable, and indexed by keys.
Creating a Dictionary
my_dict = {
"name": "Alice",
"age": 25,
"city": "Hyderabad"
}
Dictionaries

Accessing Values
print(my_dict["name"]) # Alice
print(my_dict.get("age")) # 25
.get() is safer – returns none if key is missing instead of throwing
an error.
my_dict["age"] = 26 # Modify
my_dict["country"] = "India" # Add new key
Dictionaries

Deleting Items
del my_dict["city"]
my_dict.pop("age")
Looping Through Dictionary
for key in my_dict:
print(key, my_dict[key])

# or
for key, value in my_dict.items():
print(key, value)
Dictionaries

Common Dictionary Methods

Method Description
dict.keys() Returns all keys
dict.values() Returns all values
dict.items() Returns key-value pairs
dict.get(key) Returns value for key, or None
dict.pop(key) Removes key and returns its value
dict.update({...}) Updates with another dictionary
Sets

A set is an unordered, mutable collection of unique elements.


It is used when you want to remove duplicates or perform
mathematical set operations (like union, intersection).
Creating a Set
s = {1, 2, 3, 4}
print(s)
Or using the set constructor
s = set([1, 2, 2, 3])
print(s) # {1, 2, 3}
Sets
❗ Note:
You cannot create an empty set using {} – that creates an
empty dictionary
Use set() instead
Sets

Common Set Methods

Method Description
.add(x) Adds element x
.remove(x) Removes x (error if not found)
.discard(x) Removes x (no error if missing)
.pop() Removes random item
.clear() Empties the set
.copy() Returns a shallow copy
Functions in Python

Functions are reusable blocks of code that perform a specific


task.
Defining a Function
Functions in Python

Functions are reusable blocks of code that perform a specific


task.
Example:
def greet(name):
print(f"Hello, {name}!")
Functions in Python

Fixed Arguments
You must pass the exact number of arguments.
def add(a, b):
return a + b

print(add(3, 5)) # 8
Functions in Python

Variable-length Arguments – *args


Used when you're not sure how many positional
arguments will be passed.
Example
def total(*args):
return sum(args)
print(total(1, 2, 3)) # 6
Functions in Python

Variable number of arguments at the end.


Example
def greet(greeting, *names):
for name in names:
print(f"{greeting}, {name}!")

greet("Hello", "Alice", "Bob", "Charlie")


Functions in Python

Variable number of arguments at the start.


Example
def greet(*names, greeting):
for name in names:
print(f"{greeting}, {name}!")

greet("Alice", "Bob", greeting="Hi") # Keyword needed


for 'greeting'
Functions in Python

Variable number of arguments at the start.


Example
def greet(*names, greeting):
for name in names:
print(f"{greeting}, {name}!")

greet("Alice", "Bob", greeting="Hi") # Keyword needed


for 'greeting'
Functions in Python

Keyword Arguments – **kwargs.


Example
Used when you're not sure how many named arguments
will be passed.
def show_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
show_info(name="Ravi", age=30, city="Delhi")
Functions in Python

Function as an argument.
Passing a Function as an Argument
def greet(name):
return f"Hello, {name}!"

def call_func(func, value):


return func(value)

print(call_func(greet, "Alice")) # Output: Hello, Alice!


Functions in Python

Inner function
In Python, an inner function (also called a nested function) is a
function defined inside another function.
def outer_function():
print("This is the outer function.")

def inner_function():
print("This is the inner function.")

inner_function()

outer_function()
Lambda Functions in Python
A lambda function in Python is a small anonymous function defined with the
lambda keyword. It can have any number of arguments but only one
expression.
lambda arguments: expression
Example 1: Simple addition
add = lambda x, y: x + y
print(add(3, 5)) # Output: 8
Example 2: Square of a number
square = lambda x: x * x
print(square(4)) # Output: 16
Lambda Functions in Python

Common Use Cases:


With map()
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x**2, nums))
print(squares) # [1, 4, 9, 16]
With filter()
nums = [1, 2, 3, 4, 5]
evens = list(filter(lambda x: x % 2 == 0, nums))
print(evens) # [2, 4]
Lambda Functions in Python
Common Use Cases:
The reduce() function in Python is used to apply a rolling computation to a
sequence, cumulatively combining items using a specified function.
It’s available in the functools module, so you need to import it first:
from functools import reduce

nums = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, nums)
print(total) # Output: 10
:

File handling in Python

File handling in Python is used to create, read, write, and delete


files. Python provides built-in functions to perform these
operations easily.
Basic File Operations:
Opening a File
Use the open() function:
file1=open(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\file
_handling.txt", "r")
:

File handling in Python

Common modes:

'r' – Read (default), file must exist.


'w' – Write, creates a new file or overwrites.
'a' – Append, adds to the end of file.
'x' – Create, fails if file exists.
'b' – Binary mode (e.g., 'rb' or 'wb')
't' – Text mode (default)
:

File handling in Python

Reading from a File


# Read the entire file
content = file.read()

# Read one line


line = file.readline()

# Read all lines into a list


lines = file.readlines()
:

File handling in Python

Writing to a File
file1 = open("example.txt", "w")
file1.write("Hello, world!")
Appending to a File
file = open("example.txt", "a")
file.write("\nAppended line.")
:

File handling in Python

Writing to a File
file1 = open("example.txt", "w")
file1.write("Hello, world!")
Appending to a File
file = open("example.txt", "a")
file.write("\nAppended line.")
:

File handling in Python

writelines() in Python
The writelines() method is used to write a list (or any iterable) of
strings to a file in Python. It writes everything in one go and does
not automatically add newlines between lines.
file.writelines(iterable)
:

File handling in Python

Using the with keyword for file operations in Python is the


recommended way to handle files. It ensures that the file is
automatically closed after the block of code is executed.
with open("example.txt", "r") as f:
content = f.read()
print(content)
:

File handling in Python

OS module: The os module in Python provides a way to interact


with the operating system—like working with files, directories.
Common Uses of the os Module
:

File handling in Python

import os
# Get current working directory
print(os.getcwd())
# Change working directory
os.chdir("C:/Users/YourName/Desktop")
# List files and directories
print(os.listdir())
# Make a new directory
os.mkdir("new_folder")
:

File handling in Python

# Make nested directories


os.makedirs("folder1/folder2")

# Remove a directory (only if empty)


os.rmdir("new_folder")

# Remove nested directories


os.removedirs("folder1/folder2")
:

File handling in Python

Working with Files


# Check if a path exists
print(os.path.exists("example.txt"))
# Check if it's a file or directory
print(os.path.isfile("example.txt"))
print(os.path.isdir("my_folder"))
# Join paths correctly for any OS
path = os.path.join("folder", "file.txt")
print(path) # Outputs "folder/file.txt" or "folder\file.txt"
:

Exception handling in Python

Exception handling lets you gracefully manage errors that would


otherwise crash your program. Python uses try, except, else,
and finally blocks.

Syntax error:
A syntax error in Python occurs when the code is not written
according to the correct rules of the language—in other words,
Python doesn’t understand it at all because it breaks grammar
rules.
:

Exception handling in Python

Example
if 5 > 2
print("Yes") # Syntax error
Programmer is responsible to correct these syntax errors.
Runtime Errors or exceptions: These errors occurs due to
incorrect input from the user or memory issues
:

Exception handling in Python

Three important questions


What is exception?
An unwanted and unexpected event that disturbs the
normal flow of program is called exception.
Eg:
ZeroDivisonError
FileNotFoundError
Value Error
:

Exception handling in Python


Three important questions
What is exception?
What is main objective of exception handling ?

An unwanted and unexpected event that disturbs the normal flow of


program is called exception.
Eg:
ZeroDivisonError
FileNotFoundError
Value Error
:

Exception handling in Python

+-------------------------+
| Connection Pool |
| |
| +-------------------+ |
| | Conn 1 (Open) | |
| | Conn 2 (Open) | |
| | Conn 3 (Open) | |
| | Conn 4 (Open) | |
| | Conn 5 (Open) | |
| | Conn 6 (Open) | |
| | Conn 7 (Open) | |
:

Exception handling in Python

What is main objective of exception handling?


The main objective of exception is graceful or normal
termination of the application.(i.e we should not block our
resources)
:

Exception handling in Python

What is meaning of exception handling?


Exception is not correcting the exception but allowing the rest of
the program to run normally by defining an alternative way

This way of defining alternative way is called exception handling


:

Exception handling in Python

Every exception in python is an object for every exception


respective class is available.
When ever exception occurs pvm will check if there is an
handling for the exception.
:

Exception handling in Python

Every exception in python is an object for every exception


respective class is available.
When ever exception occurs pvm will check if there is an
handling for the exception.
:

Exception handling in Python


Top-Level Exception Hierarchy in Python
BaseException
├── SystemExit
├── KeyboardInterrupt
├── GeneratorExit
└── Exception
├── ArithmeticError
│ ├── FloatingPointError
│ ├── OverflowError
│ └── ZeroDivisionError
├── AssertionError
├── AttributeError
├── BufferError
├── EOFError
├── ImportError
│ └── ModuleNotFoundError
├── LookupError
│ ├── IndexError
│ └── KeyError
├── MemoryError
├── NameError
│ └── UnboundLocalError
:

Exception handling in Python

Example for try-except with default exception


try:
a = int(input("enter a first number"))
b = int(input("enter second number "))
print(a/b)
except Exception :
print(a/2)
:

Exception handling in Python

Example for try-except with exact exception


try:
a = int(input("enter a first number"))
b = int(input("enter second number "))
print(a/b)
except ZeroDivisionError :
print(a/2)
:

Exception handling in Python

Finally block will be executed irrespective of what happens in try


and except blocks
Example for try-except-finally with exact exception
try:
a = int(input("enter a first number"))
b = int(input("enter second number "))
print(a/b)
except ZeroDivisionError :
print(a/2)
Finally:
print(“This is finally block”)
:

Exception handling in Python

Else block will be executed if there is no exception in the try


block
Example for try-except-else-finally with exact exception
try:
a = int(input("enter a first number"))
b = int(input("enter second number "))
print(a/b)
except ZeroDivisionError :
print(a/2)
Else:
print(“no exception occurred so else block will be executed”)
Exception handling in python

• try: • Case3: If there is a


stmt1 exception in stmt2 and no
stmt2 corresponding exception
stmt3 block is found
except: (stmt1,stmt6)
stmt4
else:
stmt5
finally:
stmt6
:

Decorator in Python

A decorator is a function that modifies the behavior of


another function without changing its code.
:

Decorator in Python
def smart_div(func):
def inner_func(a,b):
if a<b:
a,b=b,a
return func(a,b)
return inner_func
@smart_div
def div(a,b):
return a/b
print(div(2,4))
:

Regular expressions

Regular Expressions (RegEx) in Python are patterns used to


match strings or parts of strings.
They are extremely useful for searching, validating, extracting,
and replacing text.
Python provides the re module to work with regular expressions.
:

Regular expressions

For finding any pattern two steps need to be followed.


1. Create a regex object
2. Create a matcher object.
:

Regular expressions

Search for a group like any digit or alphabet.


[abc] – will search for either a or b or c
[^abc] – will search for except a,b,c
[a-z] – will search for a to z
[A-Z] – will search for A to Z
[0-9]-will search for any digit 0 to 9
[a-zA-Z]- will search for any alphabet symbol
[a-zA-Z0-9]-will serach for any alphabet or any digit
[^a-zA-Z0-9]-will search for special characters
:

Regular expressions

\s- match a space character


\S – except space character
\d-match any digit[0-9]
\D- match except digit
\w – any word character
\W- any character except word character like a special character
. – every character including a alphanumeric or a special
character
:

Regular expressions

a – matching only one a


a+ - either one a or more than one a
a* - any number of a (including zero number of a )
a? – atmost one a means either 1 a or zero a
a{n} – Exactly n number of a
a{m,n}-minimum m number of a and maximum n number of a
^a-whether target number starts with a or not
a$- whether target string ends with a or not.
[^a] – except a all remaining
:

Regular expressions

match() - Matches the pattern only at the beginning of the


string.
fullmatch()-Matches the entire string against the pattern.
search()-Searches the entire string for the first match.
findall()-Returns a list of all matches
sub()-Replaces all matches with a new string.
subn()-Like sub() but also returns the number of replacements.
split()-Splits the string by the pattern.
:

Database connectivity using python


Step 1: Install DB Connector . As I’m connecting to mysql db in this tutorial
we will install MySQL Connector.
pip install mysql-connector-python
Step 2: Import the Connector Module
import mysql.connector
Step 3: Establish the Connection
conn = mysql.connector.connect(
host="localhost",
user="root",
password="your_password",
database="your_database"
)
:

Database connectivity using python

Step 4: Create a Cursor Object


cursor = conn.cursor()
Step 5:Execute SQL Queries
cursor.execute("SELECT * FROM students")
result = cursor.fetchall()
for row in result:
print(row)
:

Database connectivity using python

Step 6:Commit Changes (for INSERT/UPDATE/DELETE)


conn.commit()
step 7: Close Cursor and Connection
cursor.close()
conn.close()
:

Database connectivity using python

execute()- is used to run a single SQL query (like SELECT,


INSERT, UPDATE, DELETE, etc.).
executemany()- is used to execute the same SQL statement
multiple times with different values.
fetchall() - Get all rows
fetchmany() - Get a limited number of rows
fetchone()- You can also use fetchone() to get just the next row
:

Object oriented programming

What is a class in Python?


class- A class in Python is a blueprint or template for creating
objects.
It defines attributes (variables) and methods (functions) that
describe the behavior of the objects.

What is an object in Python?


An object is an instance of a class.
It is a real-world entity that has its own data and behavior
based on the class it was created from.
:

Object oriented programming

What is self in Python?


self is a reference to the current object (instance) of a class.
It's used inside class methods to access instance variables and
other methods.
It must be the first parameter of instance methods, including the
constructor (__init__).
:

Object oriented programming

What is construtor in Python?


A constructor is a special method called __init__() that runs
automatically when an object is created.
It is used to initialize instance variables.
It is similar to constructors in other languages like Java or C++.
:

Object oriented programming

Different types of methods.


Instance method : Methods which instance variables are called
instance methods. instance methods are using objects. All
instance methods will have first parameter as self
Class method : class methods will use class variables and
class methods are called using class name. We need to use
decorator classmethod for making method as class method.
Static method : Methods which use local variables are called
static methods. We need to use decorator staticmethod for
making method as class staticmethod. Static method can be
called using either class or an object.
:

Encapsulation

Encapsulation is one of the four pillars of Object-Oriented


Programming (OOP).
It refers to bundling data (attributes) and methods
(functions) together and restricting direct access to some of
an object's components.
Modifier Syntax Access Level
Public self.name Accessible everywhere
Suggests internal use (by
Protected self._name
convention)
Name mangled, not directly
Private self.__name
accessible
:

Encapsulation

Getters and setters :


Getters and setters are methods used to access (get) and
modify (set) private attributes of a class, while keeping
encapsulation intact.
:

Object oriented programming

Methods to access private variables and methods outside the


class.
Name mangling is a technique Python uses to make private
attributes harder to access from outside the class.
When you define a variable with two leading underscores (like
__salary), Python automatically renames it to:
_ClassName__attributeName
:

Object oriented programming

Inheritance is a fundamental concept in Object-Oriented


Programming (OOP) that allows one class (called a child or
subclass) to inherit attributes and methods from another
class (called a parent or superclass).
:

Object oriented programming

Types of inheritance:
Single Inheritance - A child class inherits from one parent
class.
Multilevel Inheritance - A child class inherits from a class that
is already a child of another class.
Multiple Inheritance - A class inherits from more than one
parent class.
:

Object oriented programming

Diamond Shaped problem


The diamond problem occurs in multiple inheritance when a
class inherits from two classes that share a common parent,
creating a diamond-like structure in the class hierarchy.
A
/\
B C
\/
D
:

Object oriented programming

Method resolution order(MRO): MRO is the order in which


Python looks for a method or attribute in a hierarchy of
classes when multiple inheritance is used.
You can see the MRO using:
print(C.mro())
:

Object oriented programming

Super() keyword
The super() keyword is used to call methods from a parent
(super) class in a child (subclass).
It's most commonly used with inheritance, especially to call the
parent's constructor or overridden methods.
:

Object oriented programming

Polymorphism means "many forms".


In Python (and Object-Oriented Programming), it allows
different classes to be accessed through the same
interface, even if they implement it differently.

Different types of polymorphism


Polymorphism with Inheritance (Method Overriding)
Ducktyping
Operator overloading
:

Object oriented programming

Method Overriding
Polymorphism with Inheritance(Method Overriding) occurs
when a child class overrides a method of its parent class,
and we can use the same method name to perform different
actions depending on the object's class.
:

Object oriented programming

Duck typing
Duck Typing is a concept in dynamic programming
languages like Python where the type of an object is
determined by its behavior, not by inheritance or class
hierarchy.
“If it walks like a duck and quacks like a duck, it must be a duck.”
In Python, you don’t care what class an object belongs to — you
only care whether it has the methods or attributes you need.
:

Object oriented programming

Operator overloading
Operator Overloading means giving extended meaning to built-
in operators (+, -, *, etc.) when used with user-defined objects
(classes).
In Python, this is done using special methods (magic methods)
like:
__add__() for +
__sub__() for -
__mul__() for *
__eq__() for == and many more.
:

Abstraction

Abstraction is one of the core principles of Object-Oriented


Programming (OOP). It refers to hiding the internal details
and showing only the essential features of an object.
Why Use Abstraction?
• Simplifies complex systems.
• Focuses on what an object does rather than how it does
it.
• Improves code readability, modularity, and
maintenance.
:

MultiThreading

Multithreading is a technique that allows concurrent execution of


two or more threads (smaller units of a process) for maximum
utilization of CPU. It is especially useful when your program
involves I/O-bound operations (e.g., reading files, network
requests).
:

MultiThreading

threading module is used to create threads.


1. By making function as target in the thread object
2. By Subclassing threading.Thread
3. Using threading.Thread with a target function
:

Generator

What is a Generator?
A generator is a special type of function in Python that returns
values one at a time using the yield keyword instead of return.

Generators are:
Memory efficient (they don’t store all values in memory)
Lazy (they generate values only when needed)
Used for large datasets, infinite sequences, or custom iterators
:

Iterator

An iterator is an object in Python that allows you to loop through


elements one at a time using the next() function.
Any object that implements the methods:
__iter__() → returns the iterator object itself
__next__() → returns the next value from the sequence
is called an iterator.
:

Iterator

Iterable vs iterator

Concept Meaning
Iterable Any object you can loop over (list, tuple, string)
An object that remembers its state during iteration
Iterator
(has __next__())
:

Iterator

Summary

Iterator: object with __iter__() and __next__()


Used for memory-efficient looping
Stops when StopIteration is raised
:

Generator vs
Iterator
Feature Iterator Generator
An object with __iter__() and A special kind of iterator created
Definition
__next__() methods with a function using yield
Must implement a class with Created using a function with
Creation
__iter__() and __next__() the yield keyword
Can be memory-efficient if Very memory-efficient – values
Memory Usage
implemented carefully are generated on the fly
Much simpler to write and
Complexity Requires more code to define
understand
Custom class with __next__() Uses yield in a function to return
Syntax Example
method values one at a time
Must manage state manually (like Generator automatically
State Management
counters) remembers the last state
Any iterable object (list, tuple, Only functions with yield produce
Built-in Support
etc.) can become an iterator generators
Instance of a class with
Return Type Returns a generator object
__next__()
:

Logging

What is Logging?
Logging in Python is used to record events or messages that
happen during the execution of a program. It is very useful for:
Debugging
Error tracking
Monitoring
Auditing program behavior
Unlike print(), logs can be saved to files, filtered by severity, and
formatted.
:

Logging

Python's built-in logging module supports 5 standard log levels,


from least to most severe:
Level Number Level Name Purpose
10 Detailed information (mostly for
DEBUG
developers)
20 General information (program is
INFO
working fine)
30 Something unexpected but not a
WARNING
problem yet
40 A serious issue – something went
ERROR
wrong
50 A very serious error – the program
CRITICAL
may crash
:

Logging

Python's built-in logging module supports 5 standard log levels,


from least to most severe:
import logging

logging.basicConfig(level=logging.WARNING)
logging.debug("Debug") # ❌ Not printed
logging.info("Info") # ❌ Not printed
logging.warning("Warning") # ✅ Printed
logging.error("Error") # ✅ Printed
logging.critical("Critical") # ✅ Printed
:

Logging

Set Level Levels That Will Be Printed


DEBUG DEBUG, INFO, WARNING, ERROR, CRITICAL
INFO INFO, WARNING, ERROR, CRITICAL
WARNING WARNING, ERROR, CRITICAL
ERROR ERROR, CRITICAL
CRITICAL CRITICAL only
:

Pandas

Introduction
Pandas is a powerful open-source Python library used for data
manipulation, analysis, and cleaning. Particularly useful for
working with structured data (tables, spreadsheets, CSVs,
databases).
Pandas id capable of offering an in-memory 2d object called
DataFrame.
The mostly used pandas data structure are the series and the
data frame
Simply series is data with one column data frame is data with
rows and columns
:

Pandas

Installation
Use below command to install pandas
pip install pandas
Dataset is collection of data
Data is information collected systematically and stated with in its
context.
You can download free dataset from
https://www.Kaggle.com
:

Creating a DataFrame

• Load data from excel file.


read_excel(file localtion()
• Load data from csv file
read_csv(file location()
• Create DataFrame using dictionary
• Create DataFrame using list of tuples
:

Indexing and slicing

DataFrame.head(number_of_rows)
DataFrame.tail(number_of_rows)
DataFrame.describe()
DataFrame.shape
DataFrame[start:stop:step]
DataFrame[column_name]
DataFrame[[column1, column2]]
DataFrame.iterrows()
loc&iloc
:

Understanding loc(stop index included)


DataFrame.loc[row_number]
DataFrame.loc[row_number, [column_name]]
DataFrame.loc[start:stop]
DataFrame.loc[start:stop,”column_name”]
DataFrame.loc[start:stop,[“column1, column2”]]
DataFrame.loc[start:stop, “column1:column2”]
:

Understanding iloc(stop index excluded)


DataFrame.iloc[row_number]
DataFrame.iloc[row_number, [column_name]]
DataFrame.iloc[start:stop]
DataFrame.iloc[start:stop,”column_name”]
DataFrame.iloc[start:stop,[“column1, column2”]]
DataFrame.iloc[start:stop, “column1:column2”]
:

Sorting a dataframe
DataFrame.sort_values(“column_name”)
DataFrame.sort_values(“column_name”, ascending=False)
DataFrame.sort_values([“column1”, “column2”])
DataFrame.sort_values([“column1”, “column2”],
ascending=[0,1])
:

Manuplating a DataFrame
Adding Column
DataFrame[‘new_column_name’] = default_value
DataFrame[‘new_column_name’] = Expression/condition

Removing a column
DataFrame.drop(columns=“column_name”)
DataFrame.drop(columns=“column_name”, inplace=True)
:

Removing Dupicates
import pandas as pd
# 1. Load the CSV file
df = pd.read_csv("your_file.csv")
# 2. Remove duplicate rows (based on all columns by default)
df_no_duplicates = df.drop_duplicates()
# Optional: If you want to remove duplicates based on a specific
column or columns:
# df_no_duplicates =
df.drop_duplicates(subset=["column_name"])
# 3. Save the cleaned DataFrame back to CSV
df_no_duplicates.to_csv("your_file_cleaned.csv", index=False)
:

Data filtering and conditional changes


DataFrame.loc[simple_condition]
DataFrame.loc[Compound condition]
DataFrame.loc[simplecondition.str.contains(str)]
DataFrame.loc[simplecondition.str.startswith(str)]
DataFrame.loc[simplecondition.str.endswith(str)]
:

Handling missing data


Removing missing data

DataFrame.dropna()
DataFrame.dropna(inplace=True)

Fill with default values.


DataFrame.fillna(default_na)
:

NumPy
Introduction to Numpy
NumPy is a python library used for working with arrays
NumPy is a library consisting of multidimensional array objects
and a collection of routines for processing arrays
In python we have lists to serve the purpose of arrays but they
are slow to process
NumPy aim to provide an array objects which works faster than
traditional python lists
Numpy arrays are stored in one continuous place in memory
unlike lists so processes can access and manipulate them very
efficiently
:

NumPy
Introduction to Numpy
NumPy is a python library used for working with arrays
NumPy is a library consisting of multidimensional array objects
and a collection of routines for processing arrays
In python we have lists to serve the purpose of arrays but they
are slow to process
NumPy aim to provide an array objects which works faster than
traditional python lists
Numpy arrays are stored in one continuous place in memory
unlike lists so processes can access and manipulate them very
efficiently
:

NumPy
Installation to Numpy
pip install numpy
Creating an arrays
Creating an array with array()
0-Dimensional arrays
1- Dimensional arrays
2- Dimensional arrays
3- Dimensional arrays
asarray() with nditer()
frombuffer()
fromiter()
:

NumPy
Creating an array with asarray()
syntax for asarray()
asarray(list, dtype,order)
Creating an array with frombuffer() method. This is used to
convert a string in to an array
:

Matplotlib
Matplotlib is a data visullization package
We will create different charts using pyplot and pylab
We can represent data
– Line chart
– Bar chart
– Histogram
– Scatter plot
– Pie plot
:

Request module
The requests module in Python is a powerful and user-friendly
library used to send HTTP requests to interact with websites or
APIs.
Common methods
Method Description
get() Retrieve data
post() Send data
put() Update data
delete() Delete data
head() Retrieve headers only
:

Pickling and unpickling

Pickling is the process of converting a Python object into a


byte stream (a binary format) so that it can be:

Sent over a file


Sent over a network
Stored in a database
:

Pickling and unpickling

What is Unpickling?
Unpickling is the reverse process — it converts the byte stream
back into a Python object.
THANK YOU
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

#printing a value

print(3)

print(4)

print(5)

#assigining values to a variable

a=3

print(a)

#variables hold latest value

glass = "water"

glass = "cool drink"

glass = "cocunt water"

print(glass)

# example for assiging integer type

a= 3 #integer

print(type(a))

# example for assiging float type

b = 3.25 #float

print(type(b))

# example for assiging string type

c = 'Bhramha'

d = "Harsha"

e = '3'

print(type(e))

f = True

print(type(f))

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

g=2+3j

print(type(g))

# example for assigining boolean type

f = True

print(type(f))

# example for assigining complex type

g=2+3j

print(type(g))

#example for printing mulriple statements in one print method

a=3

b=3.0

print("a is a integer value",a,"b is a float value",b)

# f-literal

name="Harsha"

age = 25

print(f"my name is {name} and my age is {age}")

#input method

name = input("enter your name")

print(type(name))

age = int(input("enter your age"))

print(type(age))

print(f"my name is {name} and my age is {age}")

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# By default input method takes parameter as a string need to type cast if required

num=int(input("enter a number"))

print(type(num))

#operators

m=2

n=5

print(m==n)

print(m!=n)

#assigining values to multiple values at a time

a,b,c=18,19,20

print(a,b,c)

#swapping two variables

a=30

b=20

# after swapping result should be a=20, b=30

print("the value of a before swapping",a,"the value of a before swapping",b)

a,b=b,a

print("the value of a after swapping",a,"the value of a after swapping",b)

# a="Harsha" single line comment

Multiline comment

'''a=4

b=7

t="tangpp"''' multi line comment

#operators

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

name="Harsha"

print("H" not in "Harsha")

#for assigning need to use “=” and for comparison need to use “==”

if (3==3):

print("Harsha)

# or operator

a=4

if a==5 or (4==4):

print("im learning python")

# if statement

age = 17

if age >= 17:

print("You are eligible to vote.")

#if else

age = 18

if age >= 18:

print("You are eligible to vote.")

else:

print("you are not eligible to vote")

#if elif ladder

a, b, c = 10, 9, 22

if a>b and a>c:

print("a is greater")

elif b>c:

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

print("b is greater")

else:

print("c is greater")

# range function

"""range(5) 0,1,2,3,4

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

range(1,10,2) 1 3 5 7 9"""

# for loop

#for temporary_variable in sequence:

#print()

for i in range(5):

print(i)

#range function

a= range(5)

print(type(a))

for i in range(5): #range(stop)

print(i)

for i in range(1,5): #range(start,stop)

print(i)

# break

for i in range(5):

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

if i == 3:

break

print(i)

#continue

for i in range(5):

if i == 3:

continue

print(i)

#while loop

i=1

while i <= 5:

print(i)

i += 1

# collections list

list1 = []

print(type(list1))

# list methods

list2 = [1,2,3,"Harsha"]

#list2.pop()

print(list2)

# code to square the elements of a list and appending it to a new list withot list comprehension

list_1 = [1,2,3,4]

list_squares=[]

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

for i in list_1:

list_squares.append(i*i)

print(list_squares)

# list comprehension

list_1 = [1,2,3,4]

list_squares=[i*i for i in list_1]

print(list_squares)

#inner list

matrix = [

[1, 2, 3],

[4, 2, 6],

[7, 8, 9]

print(matrix[0][2])

# reverse a list

list_3 = [1,2,3,4,5,6,7,8,9]

print(list_3[::-1])

#printing length of a list

print(len(list_3))

# negative indexing

print(list_3[-1])

# looping through a list

my_list = ['apple', 'banana', 'cherry', 'date']

print(my_list[1])

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

for i in my_list:

print(i)

# using append method on list

my_list.append("Mango")

# appending a value to tuple

a=(1,2,3)

list_a = list(a)

list_a.append(4)

a= tuple(list_a)

print(a)

# removing duplicates from a list

l=[1,2,3,4,4,4,4]

set1=set(l)

l = list(set1)

print(l)

person = ("Alice", 25, "India") #packing

name,age,country=person #unpacking

print(name)

print(age)

print(country)

# dictionary

my_dict = {

"name": "Alice",

"age": 25,

"city": "Hyderabad"

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

#print(my_dict["country"])

print(my_dict.get("country"))

my_dict["age"] = 26 # Modify

my_dict["country"] = "India" # Add new key

print(my_dict)

#using keys method

for i in my_dict.keys():

print(i)

# using values method

for i in my_dict.values():

print(i)

#using items method

for i,j in my_dict.items():

print(i,j)

# passing values to a dictionary during runtime

my_dict = {}

n = int(input("How many key-value pairs? "))

for _ in range(n):

key = input("Enter key: ")

value = input("Enter value: ")

my_dict[key] = value

print("Final dictionary:", my_dict)

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# set method

set1 = {1,2,3,4}

set2 = {4,5,6,7}

print(set1.intersection(set2))

# functions with no parameter

def greet():

print("good morning")

g = greet()

# function with one parameter

def greet():

print("good morning")

g = greet()

# function with two parameters

def add_two_num(a,b):

c=a+b

return c

m=int(input("enter a number"))

n=int(input("enter a number"))

print(add_two_num(m,n))

# function with variable number of argeuments

def var_args(*a):

for i in a:

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

print (i)

print(var_args(1,2,3,4,5,6,7))

# example for variable number of arguments at the end

def var_args_end(a,*b):

print ("the value a is",a)

print("the value of b is",b)

print(var_args(1,2,3,4,5,6,7))

# Example program for variable number of arguments a the end

def var_args_start(*a,b):

print ("the value a is",a)

print("the value of b is",b)

print(var_args_start(1,2,3,4,5,6,b=7))

#passing function as paramater

def greet(name):

return "good morning",name

#print(greet("harsha"))

def func_as_param(func,name):

result = func(name)

return result

print(func_as_param(greet,"yesuratnam"))

# function inside a function(inner function)

def outer_function():

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

print("This is the outer function.")

def inner_function():

print("This is the inner function.")

inner_function()

outer_function()

# Example for keyword as an argument

def show_info(**kwargs):

for key, value in kwargs.items():

print(f"{key}: {value}")

show_info(name="Ravi", age=30, city="Delhi", country="India")

# using filter map reduce with lambda functions

"""nums = [1, 2, 3, 4, 5]

evens =[]

for i in nums:

if i%2==0:

evens.append(i)

print(evens)"""

"""nums = [1, 2, 3, 4, 5]

evens = list(filter(lambda x: x % 2 == 0, nums))

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

print(evens) # [2, 4]"""

"""num = [1, 2, 3, 4, 5, 6]

cubes = []

for n in num:

cubes.append(n ** 3)

print("Cubes of numbers:", cubes)"""

nums = [1, 2, 3, 4, 5]

cubes = list(map(lambda x: x ** 3 , nums))

print(cubes)

# finding sum of all the values inside a list without reduce

nums = [1, 2, 3, 4, 5]

total = 0

for num in nums:

total += num

print(total)

#finding sum of all the values using lambda and reduce

nums = [1, 2, 3, 4, 5]

from functools import reduce

list_sum = reduce(lambda x,y:x+y , nums)

print(list_sum)

# file handling opening a file in read mode

list_to_be_written = ["\nDivya", "\npooja", "\nkusuma"]

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

file1 = open(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\new_folder\file_handling_123.txt",
"r")

print(file1.readline())

print(file1.readline())

print(file1.readline())

# readlines method()

# opening a file in write mode

file1 = open(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\file_handling.txt", "w")

file1.write("hello world")

# writing to file using writelines method

list_file = ["I'm learning python\n", "at bramhas institue\n", "trainer is harsha\n"]

file12 = open(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\file_handling12.txt", "r")

print(file12.readlines())

#using readlines to read values inside a file

list_file = ["I'm learning python\n", "at bramhas institue\n", "trainer is harsha\n"]

file12 = open(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\file_handling12.txt", "r")

print(file12.readlines())

# opening a file in binary mode

file_binary = open(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\pooja.jpg", "rb")

print(file_binary.read())

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# os module

import os

# Get current working directory

print(os.getcwd())

# Change working directory

os.chdir(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas")

# List files and directories

os.listdir()

# Make a new directory

os.mkdir("new_folder_11")

# Make nested directories

#os.rename("new_folder_11","old_folder_11")

os.makedirs("folder11/folder21/folder31")

# Remove a directory (only if empty)

os.rmdir("new_folder")

# Remove nested directories

os.removedirs("folder1/folder2/folder3")

# Check if a path exists

print(os.path.exists("example.txt"))

# Check if it's a file or directory

print(os.path.isfile("example.txt"))

print(os.path.isdir("my_folder"))

# Join paths correctly for any OS

path = os.path.join("folder", "file.txt")

print(path) # Outputs "folder/file.txt" or "folder\file.txt"

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# Exception handling

# example for zero divison error and value error

x = int(input("enter first number"))

y = int(input("enter second number"))

print(x/y)

"""#example for file not found error

f=open("harsha123.txt")

print(f.read())"""

list13=["\nthis is python class\n", "Harsha is the trainer\n", "Bhramha sir is monitoring\n"]

file13 = open(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\file_handling13.txt", "w+")

file13.writelines(list13)

file13.seek(0)

content = file13.read()

print(content)

file13.close()

# try-except blocks

try:

a = int(input("enter a first number"))

b = int(input("enter second number "))

print(a/b)

except Exception:

print(e)

#Example for try-except with default exception

try:

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

a = int(input("enter a first number"))

b = int(input("enter second number "))

print(a/b)

except Exception :

print(10/2)

#Example for try-except with specific exception

try:

a = int(input("enter a first number"))

b = int(input("enter second number "))

print(a/b)

except ZeroDivisionError :

print(a/2)

#Example for try-except-finally with exact exception

try:

a = int(input("enter a first number"))

b = int(input("enter second number "))

print(a/b)

except ValueError :

print(a/2)

finally:

print("This is finally block")

#Example for try-except-else-finally with exact exception

try:

a = int(input("enter a first number"))

b = int(input("enter second number "))

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

print(a/b)

except ZeroDivisionError :

print(a/2)

else:

print("no exception occurred so else block will be executed")

finally:

print("This is finally block")

# decorator without using "@" to call the decorator

def div(a,b):

return a/b

def smart_div(func):

def inner_func(num,den):

if num<den:

num,den=den,num

return func(num,den)

return inner_func

a = int(input("enter first number"))

b = int(input("enter second number"))

div=smart_div(div)

print(div(a,b))

# other way

def smart_div(func):

def inner_func(a,b):

if a<b:

a,b=b,a

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

return func(a,b)

return inner_func

@smart_div

def div(a,b):

return a/b

print(div(2,4))

# write a function called greet which should take name as an argument and shoud return good
morning,name

def decor_func(func):

def inner_func(name):

if name=="kusuma":

return f"goodevening,{name}"

else:

return func(name)

return inner_func

@decor_func

def greet(name):

return f"goodmorning,{name}"

print(greet("kusuma"))

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

#step1 - create a regular expression object

#step2 - create a matcher matcher object

import re

pattern1=re.compile("Python")

print(type(pattern1))

matcher=pattern1.finditer("Python is a programmibg language. Python is easy")

for match in matcher:

print(match.start(),'=============',match.group())

#ditrectly calling finiter on re module

import re

matcher=re.finditer("Python","Python is a programming language and harsha teaches Python")

for match in matcher:

print("start match is available at",match.start())

print("end of match is available at",match.end())

print("group match is avilable at",match.group())

import re

text = 'a78b@9ckuio'

#matcher = re.finditer('[abc]', text)

#matcher = re.finditer('[^abc]', text)

#matcher = re.finditer('[a-z]', text)

#matcher = re.finditer('[A-Z]', text)

#matcher = re.finditer('[0-9]', text)

#matcher = re.finditer('[a-zA-Z]', text)

#matcher = re.finditer('[a-zA-Z0-9]', text)

#matcher = re.finditer('[^a-zA-Z0-9]', text)

for match in matcher:

print(match.group())

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

text = 'A1 b@3#'

#matcher = re.finditer(r'\s', text)

matcher = re.finditer(r'\S', text)

#matcher = re.finditer(r'\d', text)

#matcher = re.finditer(r'\D', text)

#matcher = re.finditer(r'\w', text)

#matcher = re.finditer(r'\w', text)

#matcher = re.finditer(r'\W', text)

#matcher = re.finditer(r'.', text)

for match in matcher:

print(match.start(), '------------', match.group())

text = 'aa aba aaaa ba ca da aaab'

#matcher = re.finditer(r'a', text)

#matcher = re.finditer(r'a+', text)

matcher = re.finditer(r'a*', text)

#matcher = re.finditer(r'a?', text)

#matcher = re.finditer(r'a{2}', text)

#matcher = re.finditer(r'a{2,4}', text)

#matcher = re.finditer(r'^a', text)

#matcher = re.finditer(r'a$', text)

#matcher = re.finditer(r'[^a]', text)

for match in matcher:

print(match.start(), '*********', match.group())

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

#match() - Matches the pattern only at the beginning of the string.

import re

result = re.match(r"Hello", "Hello World")

print(result.group()) # Output: Hello

#fullmatch()-Matches the entire string against the pattern.

"""import re

result = re.fullmatch(r"Hello World", "Hello World")

print(result.group()) # Output: Hello World"""

#search()-Searches the entire string for the first match.

"""import re

result = re.search(r"World", "Hello World")

print(result.group()) # Output: World"""

#findall()-Returns a list of all matches

"""import re

result = re.findall(r"\d", "Order 123 has 4 items")

print(result) # Output: ['1', '2', '3', '4']"""

#sub()-Replaces all matches with a new string.

"""import re

result = re.sub(r"\d", "#", "Room 101, Floor 2")

print(result) # Output: Room ###, Floor #"""

#subn()-Like sub() but also returns the number of replacements.

"""import re

result = re.subn(r"\d", "#", "Room 101, Floor 2")

print(result) # Output: ('Room ###, Floor #', 4)"""

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

#split()-Splits the string by the pattern.

"""import re

result = re.split(r"\s", "Split this sentence")

print(result) # Output: ['Split', 'this', 'sentence']"""

"""To validate a mobile number in Python where:

The first digit must be 6, 7, 8, or 9

The number must be exactly 10 digits long"""

import re

def is_valid_mobile(number):

pattern = r'^[6-9]\d{9}$'

if re.fullmatch(pattern, number):

return "Valid mobile number"

else:

return "Invalid mobile number"

# Test cases

print(is_valid_mobile("9876543210")) # Valid

print(is_valid_mobile("1234567890")) # Invalid

print(is_valid_mobile("987654321")) # Invalid (only 9 digits)

"""

Reads mobile numbers from a file (one per line)

Validates each number (must start with 6–9 and be exactly 10 digits)

Stores only valid numbers in a new file

"""

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

import re

def is_valid_mobile(number):

pattern = r'^[6-9]\d{9}$'

return re.fullmatch(pattern, number) is not None

# File names

input_file = 'input.txt'

output_file = 'valid_numbers.txt'

# Read from input file and write valid numbers to output file

with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:

for line in infile:

number = line.strip()

if is_valid_mobile(number):

outfile.write(number + '\n')

print("Valid numbers have been written to", output_file)

import re

def is_valid_email(email):

pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'

return re.fullmatch(pattern, email) is not None

emails = [

"[email protected]",

"[email protected]",

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

"[email protected]",

"missingatsign.com",

"hello@domain"

for email in emails:

print(email, "->", "Valid" if is_valid_email(email) else "Invalid")

# Database connectivity using python

import mysql.connector

# Connect to DB

#creating connection object

conn = mysql.connector.connect(

host="localhost",

user="root",

password="Yellowparrot@143",

database="mysql"

#creation of cursor object

cursor = conn.cursor()

cursor.execute("SELECT * FROM students_1")

rows = cursor.fetchall()

for row in rows:

print(row)

cursor.close()

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

conn.close()

# using execute

import mysql.connector

# Establish connection

conn = mysql.connector.connect(

host="localhost",

user="root",

password="Yellowparrot@143",

database="mysql"

cursor = conn.cursor()

# Create table

cursor.execute("DROP TABLE IF EXISTS students")

cursor.execute("CREATE TABLE students (id INT, name VARCHAR(100))")

print("students table created successfully")

#executemany()- is used to execute the same SQL statement multiple times with different values.

students = [(1, 'Alice'), (2, 'Bob'), (3, 'Charlie'), (4, 'David')]

cursor.executemany("INSERT INTO students (id, name) VALUES (%s, %s)", students)

conn.commit()

#fetchall() - Get all rows

cursor.execute("SELECT * FROM students")

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

rows = cursor.fetchall()

print("All rows:")

for row in rows:

print(row)

#fetchmany() - Get a limited number of rows

cursor.execute("SELECT * FROM students")

rows = cursor.fetchmany(2)

print("First two rows:")

for row in rows:

print(row)

cursor.close()

conn.close()

print("connections are closed")

# databse connectivity using exception handling

import mysql.connector

from mysql.connector import Error

try:

# Attempt to connect to MySQL

conn = mysql.connector.connect(

host='localhost',

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

user='root',

password='Yellowparrot@143',

database='mysql'

if conn.is_connected():

print("Connection successful")

cursor = conn.cursor()

# Create table (if not exists)

cursor.execute("CREATE TABLE IF NOT EXISTS students (id INT, name VARCHAR(100))")

# Insert sample data

cursor.execute("INSERT INTO students (id, name) VALUES (1, 'Alice')")

conn.commit()

# Retrieve data

cursor.execute("SELECT * FROM students")

rows = cursor.fetchall()

print("Student Records:")

for row in rows:

print(row)

except Error as e:

print("Error while connecting or running query:", e)

finally:

if 'cursor' in locals() and cursor:

cursor.close()

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

if 'conn' in locals() and conn.is_connected():

conn.close()

print("Connection closed")

#OOPS - Object oriented programming

#class creation class class_name:

class A:

def display(self): #self is current object

print("This is our first class creation")

#object creation

#object_name=class_name()

a=A()

b=A()

c=A()

#accessing methods inside a class

#objectname.methodname()

a.display()

b.display()

"""constructor - constructor is a special function. You will declare your data inside constructor.

Constructor is the first thing that will be executed when an object is created"""

class Employee:

def __init__(self,ename,salary):

self.ename=ename

self.salary = salary

def display(self):

print(f"employee name is {self.ename}, employee salary is {self.salary}")

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

e = Employee("Harsha",20000)

d = Employee("Pavani",30000)

# different types of methods in python

class Employee:

company = "Bhramha institute"

def __init__(self,ename,salary):

self.ename=ename

self.salary = salary

def display(self): # instance method

print(f"employee name is {self.ename}, employee salary is {self.salary}")

@classmethod

def display_company_name(cls): #classmethod

print(f"company name is {cls.company}")

@staticmethod

def caluculate_sum(a,b):

return a+b

e = Employee("Harsha",20000)

e.display() #calling instance method

Employee.display_company_name() #calling class method

print(e.caluculate_sum(2,3)) # calling static method uing object

print(Employee.caluculate_sum(2,3)) # calling static method using class name

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# getters and setters

class Student:

def __init__

"""def set_name(self,name):

self.name=name

def get_name(self):

return self.name"""

s = Student()

s.set_name("Harsha")

s.get_name()

class Student:

def set_name(self,name):

self.name=name # Harsha

def get_name(self):

return self.name

s = Student()

s.set_name("Harsha")

s.get_name()

class Student:

def __init__(self,name):

self.name=name

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

def display(self):

print(self.name)

a=Student("Divya")

a.display()

class Student:

def __init__(self, name, age):

self.__name = name # Private attribute

self.__age = age

# Getter for name

def get_name(self):

return self.__name

# Setter for name

def set_name(self, new_name):

if new_name:

self.__name = new_name

else:

print("Name cannot be empty!")

# Getter for age

def get_age(self):

return self.__age

# Setter for age

def set_age(self, new_age):

if new_age > 0:

self.__age = new_age

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

else:

print("Age must be positive.")

s = Student("Alice", 20)

# Access via getter

print(s.get_name()) # Alice

# Update via setter

s.set_name("Bob")

print(s.get_name()) # Bob

# Invalid update

s.set_age(-5) # Age must be positive.

print(s.get_age()) # 20 (unchanged)

class Employee:

def __init__(self):

self.name = "John" # Public

self._department = "HR" # Protected

self.__salary = 50000 # Private

def show_info(self):

print("Name:", self.name)

print("Department:", self._department)

print("Salary:", self.__salary) # Accessing private variable inside class

class student:

e=Employee()

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

def print_name(self):

print(e.name)

#accessing private variables using getters and setters

class BankAccount:

def __init__(self, name, owner, balance):

self.name = name # public attribute

self.__owner = owner # Private attribute

self.__balance = balance # Private attribute

# Getter for balance

def get_balance(self):

return self.__balance

# Setter for balance

def set_balance(self, amount):

if amount >= 0:

self.__balance = amount

else:

print(" Balance cannot be negative!")

# Getter for owner

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

def get_owner(self):

return self.__owner

# Setter for owner

def set_owner(self, name):

if name:

self.__owner = name

else:

print(" Owner name cannot be empty!")

acc = BankAccount("sbi","Alice", 10000)

print(acc.name)

print(acc._BankAccount__owner)

# Accessing private variables using getters

print(acc.get_owner()) # Alice

print(acc.get_balance()) # 10000

# Updating private variables using setters

acc.set_balance(12000)

print(acc.get_balance()) # 12000

acc.set_owner("Bob")

print(acc.get_owner()) # Bob

# Invalid update

acc.set_balance(-5000) # Balance cannot be negative!

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

#Example for single inheritance

class Animal:

def sound(self):

print("Animal makes sound")

class Dog(Animal):

def bark(self):

print("Dog barks")

d = Dog()

d.sound() # Inherited

d.bark()

#Example for multilevel inheritance

class Grand_father:

def grand_father_method(self):

print("This is grand father method")

class Father(Grand_father):

def father_method(self):

print("This is father method")

class Child(Father):

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

def child_method(self):

print("This is child method")

c = Child()

c.grand_father_method()

c.father_method()

c.child_method()

#Example for multiple inheritance

class A:

def show(self):

print("Class A")

class B:

def show(self):

print("Class B")

class C(A, B):

pass

obj = C()

obj.show()

print(C.mro())

#super() with a Method

class Vehicle:

def start(self):

print("Starting the vehicle")

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

class Car(Vehicle):

def start(self):

super().start() # Calls Vehicle's start()

print("Starting the car engine")

# Creating an object of Car

my_car = Car()

my_car.start()

"""Suppose we have a Person class,

and an Employee class that adds more attributes but still wants to reuse the initialization logic from
Person."""

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

print("Person initialized")

class Employee(Person):

def __init__(self, name, age, employee_id):

super().__init__(name, age) # Reuse Person's constructor

self.employee_id = employee_id

print("Employee initialized")

# Creating an Employee object

e = Employee("Alice", 30, "E101")

# Accessing attributes

print("Name:", e.name)

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

print("Age:", e.age)

print("Employee ID:", e.employee_id)

#Example for method overriding

class Animal:

def speak(self):

print("Animal makes a sound")

class Dog(Animal):

def speak(self):

print("Dog barks")

class Cat(Animal):

def speak(self):

print("Cat meows")

a= Animal()

b=Dog()

c=Cat()

a.speak()

b.speak()

c.speak()

#Example for duck typing

class Duck:

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

def speak(self):

print("Quack!")

class Person:

def speak(self):

print("Hello!")

def make_speak(obj_name):

obj_name.speak() # It doesn't matter what 'object' is, as long as it has a speak() method

make_speak(Duck()) # Output: Quack!

make_speak(Person()) # Output: Hello!

#Why operator overloading is required?

class Point:

def __init__(self, x, y):

self.x = x

self.y = y

p1 = Point(2, 3)

p2 = Point(4, 1)

result = p1 + p2 #Point(6,4) # You can't add objects without implementing operator overloading

print(result) # error

# Example for abstraction

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

from abc import ABC, abstractmethod

class Vehicle(ABC):

@abstractmethod

def start(self):

pass

@abstractmethod

def stop(self):

pass

# Child class must implement all abstract methods

class Car(Vehicle):

def start(self):

print("Car started")

def stop(self):

print("Car stopped")

# You can't instantiate an abstract class

# v = Vehicle() # Error

# Valid: instantiate subclass that implements all methods

my_car = Car()

my_car.start()

my_car.stop()

#Multi threading

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

import threading

print("current executing thread is:",threading.current_thread())

print("current executing thread is:",threading.current_thread().name)

from threading import *

def display():

print("this code is executed by child thread:", current_thread().name)

print("current executing thread is:", current_thread().name)

t1 = Thread(target=display)

print("current executing thread is:", current_thread().name)

# In the above example though you created a thread but didn't start it so you see whole program is
running on main thread

from threading import *

def display():

print("this code is executed by child thread:", current_thread().name)

print("current executing thread is:", current_thread().name)

t1 = Thread(target=display)

t1.start() # Child thread will start the main thread

print("******")

print("current executing thread is:", current_thread().name)

# 2nd way to create a thread by extending the thread class

from threading import *

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

class MyDemo(Thread):

def run(self) : # In run method we need to specify the job need to be executed by child thread

for x in range(10):

print("child thread executes")

#create object and start the thread (no need to mention target in this way)

t=MyDemo()

t.start()

for x in range(10):

print("parent thread executes")

#Example to see duration a program ran without multithreading

import time

numbers=[10,20,30,40,50]

def get_double_of_numbers(numbers):

for n in numbers:

time.sleep(2)

print("double of no is:",n*2)

def get_square_of_numbers(numbers):

for n in numbers:

time.sleep(2)

print("square of a number is", n**2)

begintime = time.time()

get_double_of_numbers(numbers)

get_square_of_numbers(numbers)

endtime=time.time()

print("total time taken is", endtime-begintime)

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

import time

numbers=[10,20,30,40,50]

def get_double_of_numbers(numbers):

for n in numbers:

time.sleep(2)

print("double of no is:",n*2)

def get_square_of_numbers(numbers):

for n in numbers:

time.sleep(2)

print("square of a number is", n**2)

begintime = time.time()

t1=Thread(target=get_double_of_numbers, args=(numbers,))

t2=Thread(target=get_square_of_numbers, args=(numbers,))

t1.start()

t2.start()

t1.join() # main thread will wait untill child thread gets executed

t2.join()

endtime=time.time()

print("total time taken is", endtime-begintime)

# generators

#l1 = ["A", "B", "C"]

def mygen():

yield 'A'

yield 'B'

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

yield 'C'

g = mygen()

print(type(g))

print(next(g))

print(next(g))

print(next(g))

print(next(g))

# count down using generators

import time

def count_down(num):

print("count down starting")

while num>0:

yield num

num-=1

values = count_down(5)

for x in values:

print(x)

time.sleep(3)

# generating fibonacci series using generators

def fib():

a,b = 0,1

while True:

yield a

a,b=b,a+b

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

for n in fib():

if n>100:

break

print(n)

def fact(num):

fact = 1

while num>1:

fact = fact* num

num=num-1

yield fact

print(list(fact(5)))

def fact(num):

result = 1

i=1

while i <= num:

result *= i

yield result

i += 1

print(list(fact(5)))

#Using an Iterator Manually

nums = [10, 20, 30] # iterable

it = iter(nums) # Get iterator from list

print(type(it))

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

print(next(it)) # 10

print(next(it)) # 20

print(next(it)) # 30

# print(next(it)) # Raises StopIteration

# Looping Using an Iterator (Behind the Scenes)

# When you use a for loop:

for num in nums:

print(num)

# Python automatically calls iter() and next() behind the scenes.

# Create Your Own Iterator (Custom Class)

class CountDown:

def __init__(self, start):

self.num = start

def __iter__(self):

return self

def __next__(self):

if self.num <= 0:

raise StopIteration

value = self.num

self.num -= 1

return value

cd = CountDown(3)

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

for i in cd:

print(i) # Output: 3, 2, 1

# Getting Started with Logging

import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug("This is a debug message")

logging.info("This is an info message")

logging.warning("This is a warning")

logging.error("This is an error")

logging.critical("This is critical")

# customizing logging output

import logging

# Remove any existing handlers before setting up a new config

for handler in logging.root.handlers[:]:

logging.root.removeHandler(handler)

logging.basicConfig(

level=logging.INFO,

format='%(asctime)s - %(levelname)s - %(message)s'

logging.info("Program started")

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# logging to a file

import logging

logging.basicConfig(

filename='C:\\Users\\Lohitaksh\\OneDrive\\Desktop\\brahmas\\app.log',

filemode='a', # Overwrite each time; use 'a' to append

level=logging.WARNING,

format='%(levelname)s:%(message)s'

logging.warning("This is a warning message")

logging.error("This is an error message")

# logging in functions

def divide(a, b):

try:

return a / b

except ZeroDivisionError:

logging.exception("Tried to divide by zero")

divide(5, 0)

# impoting and creating dataframe

import pandas as pd

d = pd.read_csv(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\pandas_example.csv")

df = pd.DataFrame(d)

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# to view the data frame created

Df

#slicing

df.head(5)

# creating a data frame from dictionary

dict1 = {"name":["abc", "def", "ghi"], "percent":[90,76,91]}

df1 = pd.DataFrame(dict1)

df1

df.tail(5)

df.describe()

# shape will give rows and columns in your dataframe

df.shape

#df[start:stop:step]

df[0:10:2]

df["student_id"]

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

df_des=df[["student_id", "age"]]

df_des

# using iterrows

for rec in df.iterrows():

print(rec)

#DataFrame.loc[row_number, [column_name]]

df.loc[1,["student_id"]]

# DataFrame.loc[start:stop]

df.loc[0:5]

# DataFrame.loc[start:stop,”column_name”]

df.loc[0:5, "student_id"]

# creating a new column

df["total"]=100

# drops the column temporarily

df.drop(columns="total")

# dropping the columns permanently

df.drop(columns="total", inplace=True)

#finding the duplicate values

df.duplicated()

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

#dropping the duplicates

d.drop_duplicates()

# Simple condition

d.loc[d["age"]==23]

# compound condition

d.loc[(d["age"] > 23) & (d["age"] < 60)]

# impoting and creating dataframe for NAN

import pandas as pd

d2 = pd.read_csv(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\pandas_example_missing.csv")

df2 = pd.DataFrame(d2)

# dropping NAN records temporary

df2.dropna()

# fill NAN values

df2.fillna(80)

# dropping NAN records permanently

df2.dropna(inplace=True)

# Numpy array

import numpy as np

# creating zero diemensional array

a = np.array(10)

print(a)

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# creating one diemesional arrys

o = np.array([10,20,30])

print(o) # [10 20 30] observe the result list is a comma seperated values and array is a space
separated

# creating two dimensional array

t = np.array([[10,20],[30,40]])

print(t)

# creating three diemensional arrays

t = np.array([[[10,20],[30,40]], [[50,60],[70,80]]])

print(t)

# creating an array with as array method

a= [10,20,30]

as_a= np.asarray(a, dtype=float)

print(as_a)

# creating an array with row major order using nditer

a = [[10,20],[30,40]]

as_a= np.asarray(a, dtype=float, order='C') # using C which means row major order

for i in np.nditer(as_a):

print(i)

# creating an array with row major order using nditer

a = [[10,20],[30,40]]

as_a= np.asarray(a, dtype=float, order='C') # using C which means row major order

for i in np.nditer(as_a):

print(i)

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# creating an array with column major order using nditer

a = [[10,20],[30,40]]

as_a= np.asarray(a, dtype=float, order='F') # using F which means column major order

for i in np.nditer(as_a):

print(i)

# creating an array from a string using buffer

s = b"welcome to python course"

print(np.frombuffer(s, dtype="S1"))

a=[10,20,30,40]

print(np.fromiter(a, dtype=int, count=3))

# line chart

import matplotlib.pyplot as plt

x = [1940, 1960, 1980, 2000, 2020]

y = [25, 50, 75, 100, 150]

plt.plot(x, y, marker='o')

plt.title("population in crores")

plt.xlabel("year")

plt.ylabel("population")

plt.grid(color='gray', linestyle='--', linewidth=0.5)

plt.show()

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

# Bar chart

import matplotlib.pyplot as plt

categories = ['A', 'B', 'C', 'D']

values = [23, 17, 35, 29]

plt.bar(categories, values, color='skyblue')

plt.title("Bar Chart")

plt.xlabel("Categories")

plt.ylabel("Values")

plt.show()

# Histograms

import matplotlib.pyplot as plt

data = [10, 20, 20, 30, 30, 30, 40, 40, 50, 60]

plt.hist(data, bins=5, color='orange', edgecolor='black')

plt.title("Histogram")

plt.xlabel("Value Range")

plt.ylabel("Frequency")

plt.show()

# scatter plot

import matplotlib.pyplot as plt

x = [5, 7, 8, 7, 2, 17, 2, 9, 4, 11]

y = [99, 86, 87, 88, 100, 86, 103, 87, 94, 78]

plt.scatter(x, y, color='red')

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

plt.title("Scatter Plot")

plt.xlabel("X-axis")

plt.ylabel("Y-axis")

plt.grid(True)

plt.show()

# pie chart

import matplotlib.pyplot as plt

labels = ['Python', 'Java', 'C++', 'Ruby']

sizes = [45, 30, 15, 10]

plt.pie(sizes, labels=labels, autopct='%1.1f%%', startangle=140)

plt.title("Pie Chart")

plt.axis('equal') # Equal aspect ratio ensures the pie is a circle

plt.show()

#http requests

import requests

response = requests.get('https://api.github.com')

print(response.status_code) # HTTP status code (e.g., 200 OK)

print(response.text) # Response content as string

print(response.json()) # Convert JSON response to dictionary (if JSON)

# pickling and unpickling

WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY

import pickle

data = {'name': 'Alice', 'age': 25, 'is_student': True}

# Save to a file

with open(r'C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\data.pkl', 'wb') as file:

pickle.dump(data, file)

# unpickling

import pickle

# Load from a file

with open(r'C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\data.pkl', 'rb') as file:

loaded_data = pickle.load(file)

print(loaded_data)

WWW.BRAHMASACADEMY.IN
PYTHON INTERVIEW QUESTIONS

1. What is difference between list and tuple


2. Given a tuple (1,2,3) append “4” to this tuple result should be (1,2,3,4)
3. Given a list l=[1,2,3,4,4,4] remove duplicates from this list using set() constructor and
without using it
4. Swap two numbers
5. Reverse a sting str1 = “python”
Result should be “nohtyp” do with and without using str1[::-1]
6. Print squares of a numbers using list comprehension
7. Dict1={“name”:”bits”,”age”:30}
Loop and print both keys and values together
8. List the steps to connect to a database and retrieve the records from a table and print them
9. What is encapsulation, inheritance polymorphism and abstraction
10. What are access specifier
11. What is name mangling
12. What is preferred way to call private methods or variables
13. What is exception handling and how do you implement in python. Exlain what code is
written in try and finally block and when else block will be executed
14. What are generators in python
15. Write Fibonacci series using generator function
16. What are decorators write an example code
17. What is operator overloading, method overriding , ducktyping write an example for each
18. What is loc and iloc in pandas
19. What is difference between series and dataframe
20. What is pickling and unpickling
21. What is difference in opening a file manually and opening using “with keyword”
22. What is a module and how do you import them
23. List the modules or package names you know
24. What is a frozen set
25. What is a lambda function how it is different from normal functions and explain about filter
map reduce
26. What is multithreading
27. How do you create thread and explain about start method
28. What is use of join method in multi threading
29. What is difference between a list and numpyarray and which is faster and what is the reason
to be faster
30. Explain about few runtime errors you know
31. What is diamond shaped problem and explain about mro()
32. What are http methods you know and explain the difference between put and post
33. What is packing and unpacking a tuple with an example
34. Can we create an object for abstract classes?
35. Explain about different methods instance, class and static methods
36. What is self and explain about constructor
37. What are getters and setters in python
38. Can we use self outside the class?

WWW.BRAHMASACADEMY.IN

You might also like