Python Job Level Material
Python Job Level Material
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
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")
Input() function
% Modulus 3%2 1
(remainder)
** Exponentiatio 2 ** 3 8
n
Comparison Operators (Relational)
>= Greater or
5 >= 5 → True
equal
<= Less or equal 4 <= 5 → True
Logical Operators
• Used to combine
conditions Operator Description Example Result
True if at
True or
or least one is True
False
true
Reverses
not not True False
the result
Assignment Operators
• 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
List
Tuple
Dictionary
set
list
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
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
Tuples vs Lists
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
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
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
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
Function as an argument.
Passing a Function as an Argument
def greet(name):
return f"Hello, {name}!"
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
nums = [1, 2, 3, 4]
total = reduce(lambda x, y: x + y, nums)
print(total) # Output: 10
:
Common modes:
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.")
:
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.")
:
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)
:
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")
:
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.
:
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
:
+-------------------------+
| Connection Pool |
| |
| +-------------------+ |
| | Conn 1 (Open) | |
| | Conn 2 (Open) | |
| | Conn 3 (Open) | |
| | Conn 4 (Open) | |
| | Conn 5 (Open) | |
| | Conn 6 (Open) | |
| | Conn 7 (Open) | |
:
Decorator in Python
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
Regular expressions
Regular expressions
Regular expressions
Regular expressions
Encapsulation
Encapsulation
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.
:
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.
:
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.
:
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.
:
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
MultiThreading
MultiThreading
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
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
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
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
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
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
:
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)
:
DataFrame.dropna()
DataFrame.dropna(inplace=True)
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
:
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)
a=3
print(a)
glass = "water"
print(glass)
a= 3 #integer
print(type(a))
b = 3.25 #float
print(type(b))
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))
f = True
print(type(f))
g=2+3j
print(type(g))
a=3
b=3.0
# f-literal
name="Harsha"
age = 25
#input method
print(type(name))
print(type(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)
a,b,c=18,19,20
print(a,b,c)
a=30
b=20
a,b=b,a
Multiline comment
'''a=4
b=7
#operators
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
name="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):
# if statement
age = 17
#if else
age = 18
else:
a, b, c = 10, 9, 22
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
#print()
for i in range(5):
print(i)
#range function
a= range(5)
print(type(a))
print(i)
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]
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])
print(len(list_3))
# negative indexing
print(list_3[-1])
print(my_list[1])
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
for i in my_list:
print(i)
my_list.append("Mango")
a=(1,2,3)
list_a = list(a)
list_a.append(4)
a= tuple(list_a)
print(a)
l=[1,2,3,4,4,4,4]
set1=set(l)
l = list(set1)
print(l)
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
print(my_dict)
for i in my_dict.keys():
print(i)
for i in my_dict.values():
print(i)
print(i,j)
my_dict = {}
for _ in range(n):
my_dict[key] = value
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))
def greet():
print("good morning")
g = greet()
def greet():
print("good morning")
g = greet()
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))
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))
def var_args_end(a,*b):
print(var_args(1,2,3,4,5,6,7))
def var_args_start(*a,b):
print(var_args_start(1,2,3,4,5,6,b=7))
def greet(name):
#print(greet("harsha"))
def func_as_param(func,name):
result = func(name)
return result
print(func_as_param(greet,"yesuratnam"))
def outer_function():
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
def inner_function():
inner_function()
outer_function()
def show_info(**kwargs):
print(f"{key}: {value}")
"""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]
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
"""num = [1, 2, 3, 4, 5, 6]
cubes = []
for n in num:
cubes.append(n ** 3)
nums = [1, 2, 3, 4, 5]
print(cubes)
nums = [1, 2, 3, 4, 5]
total = 0
total += num
print(total)
nums = [1, 2, 3, 4, 5]
print(list_sum)
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()
file1.write("hello world")
print(file12.readlines())
print(file12.readlines())
print(file_binary.read())
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
# os module
import os
print(os.getcwd())
os.chdir(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas")
os.listdir()
os.mkdir("new_folder_11")
#os.rename("new_folder_11","old_folder_11")
os.makedirs("folder11/folder21/folder31")
os.rmdir("new_folder")
os.removedirs("folder1/folder2/folder3")
print(os.path.exists("example.txt"))
print(os.path.isfile("example.txt"))
print(os.path.isdir("my_folder"))
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
# Exception handling
print(x/y)
f=open("harsha123.txt")
print(f.read())"""
file13.writelines(list13)
file13.seek(0)
content = file13.read()
print(content)
file13.close()
# try-except blocks
try:
print(a/b)
except Exception:
print(e)
try:
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
print(a/b)
except Exception :
print(10/2)
try:
print(a/b)
except ZeroDivisionError :
print(a/2)
try:
print(a/b)
except ValueError :
print(a/2)
finally:
try:
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
print(a/b)
except ZeroDivisionError :
print(a/2)
else:
finally:
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
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
import re
pattern1=re.compile("Python")
print(type(pattern1))
print(match.start(),'=============',match.group())
import re
import re
text = 'a78b@9ckuio'
print(match.group())
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
import re
"""import re
"""import re
"""import re
"""import re
"""import re
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
"""import re
import re
def is_valid_mobile(number):
pattern = r'^[6-9]\d{9}$'
if re.fullmatch(pattern, number):
else:
# Test cases
print(is_valid_mobile("9876543210")) # Valid
print(is_valid_mobile("1234567890")) # Invalid
"""
Validates each number (must start with 6–9 and be exactly 10 digits)
"""
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
import re
def is_valid_mobile(number):
pattern = r'^[6-9]\d{9}$'
# File names
input_file = 'input.txt'
output_file = 'valid_numbers.txt'
# Read from input file and write valid numbers to output file
number = line.strip()
if is_valid_mobile(number):
outfile.write(number + '\n')
import re
def is_valid_email(email):
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
emails = [
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
"missingatsign.com",
"hello@domain"
import mysql.connector
# Connect to DB
conn = mysql.connector.connect(
host="localhost",
user="root",
password="Yellowparrot@143",
database="mysql"
cursor = conn.cursor()
rows = cursor.fetchall()
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
#executemany()- is used to execute the same SQL statement multiple times with different values.
conn.commit()
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
rows = cursor.fetchall()
print("All rows:")
print(row)
rows = cursor.fetchmany(2)
print(row)
cursor.close()
conn.close()
import mysql.connector
try:
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()
conn.commit()
# Retrieve data
rows = cursor.fetchall()
print("Student Records:")
print(row)
except Error as e:
finally:
cursor.close()
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
conn.close()
print("Connection closed")
class A:
#object creation
#object_name=class_name()
a=A()
b=A()
c=A()
#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):
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
e = Employee("Harsha",20000)
d = Employee("Pavani",30000)
class Employee:
def __init__(self,ename,salary):
self.ename=ename
self.salary = salary
@classmethod
@staticmethod
def caluculate_sum(a,b):
return a+b
e = Employee("Harsha",20000)
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
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:
self.__age = age
def get_name(self):
return self.__name
if new_name:
self.__name = new_name
else:
def get_age(self):
return self.__age
if new_age > 0:
self.__age = new_age
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
else:
s = Student("Alice", 20)
print(s.get_name()) # Alice
s.set_name("Bob")
print(s.get_name()) # Bob
# Invalid update
print(s.get_age()) # 20 (unchanged)
class Employee:
def __init__(self):
def show_info(self):
print("Name:", self.name)
print("Department:", self._department)
class student:
e=Employee()
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
def print_name(self):
print(e.name)
class BankAccount:
def get_balance(self):
return self.__balance
if amount >= 0:
self.__balance = amount
else:
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
def get_owner(self):
return self.__owner
if name:
self.__owner = name
else:
print(acc.name)
print(acc._BankAccount__owner)
print(acc.get_owner()) # Alice
print(acc.get_balance()) # 10000
acc.set_balance(12000)
print(acc.get_balance()) # 12000
acc.set_owner("Bob")
print(acc.get_owner()) # Bob
# Invalid update
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
class Animal:
def sound(self):
class Dog(Animal):
def bark(self):
print("Dog barks")
d = Dog()
d.sound() # Inherited
d.bark()
class Grand_father:
def grand_father_method(self):
class Father(Grand_father):
def father_method(self):
class Child(Father):
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
def child_method(self):
c = Child()
c.grand_father_method()
c.father_method()
c.child_method()
class A:
def show(self):
print("Class A")
class B:
def show(self):
print("Class B")
pass
obj = C()
obj.show()
print(C.mro())
class Vehicle:
def start(self):
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
class Car(Vehicle):
def start(self):
my_car = Car()
my_car.start()
and an Employee class that adds more attributes but still wants to reuse the initialization logic from
Person."""
class Person:
self.name = name
self.age = age
print("Person initialized")
class Employee(Person):
self.employee_id = employee_id
print("Employee initialized")
# Accessing attributes
print("Name:", e.name)
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
print("Age:", e.age)
class Animal:
def speak(self):
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()
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
class Point:
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
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
class Vehicle(ABC):
@abstractmethod
def start(self):
pass
@abstractmethod
def stop(self):
pass
class Car(Vehicle):
def start(self):
print("Car started")
def stop(self):
print("Car stopped")
# v = Vehicle() # Error
my_car = Car()
my_car.start()
my_car.stop()
#Multi threading
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
import threading
def display():
t1 = Thread(target=display)
# In the above example though you created a thread but didn't start it so you see whole program is
running on main thread
def display():
t1 = Thread(target=display)
print("******")
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):
#create object and start the thread (no need to mention target in this way)
t=MyDemo()
t.start()
for x in range(10):
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)
begintime = time.time()
get_double_of_numbers(numbers)
get_square_of_numbers(numbers)
endtime=time.time()
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)
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()
# generators
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))
import time
def count_down(num):
while num>0:
yield num
num-=1
values = count_down(5)
for x in values:
print(x)
time.sleep(3)
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:
num=num-1
yield fact
print(list(fact(5)))
def fact(num):
result = 1
i=1
result *= i
yield result
i += 1
print(list(fact(5)))
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(num)
class CountDown:
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
import logging
logging.basicConfig(level=logging.DEBUG)
logging.warning("This is a warning")
logging.error("This is an error")
logging.critical("This is critical")
import logging
logging.root.removeHandler(handler)
logging.basicConfig(
level=logging.INFO,
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',
level=logging.WARNING,
format='%(levelname)s:%(message)s'
# logging in functions
try:
return a / b
except ZeroDivisionError:
divide(5, 0)
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
Df
#slicing
df.head(5)
df1 = pd.DataFrame(dict1)
df1
df.tail(5)
df.describe()
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
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"]
df["total"]=100
df.drop(columns="total")
df.drop(columns="total", inplace=True)
df.duplicated()
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
d.drop_duplicates()
# Simple condition
d.loc[d["age"]==23]
# compound condition
import pandas as pd
d2 = pd.read_csv(r"C:\Users\Lohitaksh\OneDrive\Desktop\brahmas\pandas_example_missing.csv")
df2 = pd.DataFrame(d2)
df2.dropna()
df2.fillna(80)
df2.dropna(inplace=True)
# Numpy array
import numpy as np
a = np.array(10)
print(a)
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
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
t = np.array([[10,20],[30,40]])
print(t)
t = np.array([[[10,20],[30,40]], [[50,60],[70,80]]])
print(t)
a= [10,20,30]
print(as_a)
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)
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
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)
print(np.frombuffer(s, dtype="S1"))
a=[10,20,30,40]
# line chart
plt.plot(x, y, marker='o')
plt.title("population in crores")
plt.xlabel("year")
plt.ylabel("population")
plt.show()
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
# Bar chart
plt.title("Bar Chart")
plt.xlabel("Categories")
plt.ylabel("Values")
plt.show()
# Histograms
data = [10, 20, 20, 30, 30, 30, 40, 40, 50, 60]
plt.title("Histogram")
plt.xlabel("Value Range")
plt.ylabel("Frequency")
plt.show()
# scatter plot
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
plt.title("Pie Chart")
plt.show()
#http requests
import requests
response = requests.get('https://api.github.com')
WWW.BRAHMASACADEMY.IN
PYTHON ALL CODES TOPIC WISE BRAHMAS ACADEMY
import pickle
# Save to a file
pickle.dump(data, file)
# unpickling
import pickle
loaded_data = pickle.load(file)
print(loaded_data)
WWW.BRAHMASACADEMY.IN
PYTHON INTERVIEW QUESTIONS
WWW.BRAHMASACADEMY.IN