Part 1 and 2
Python
Python is a high level interpreted programming language known for its
dynamic Typing , Simplicity and versatility .
This is series to learn python programming
Content library :
Python syntax
OOP concept
Pandas library
Connecting with various sources like Database ,s3 ADLS , No sql
databases etc
API
Logging/Exception
File handing
Programming
Industrial Project
Variables:
Variables are the one that can vary. They are stored in the RAM in
computer.
Example : X=10
#location of RAM for X variable
Print(id(x))
Naming convention :
1) Can use a alphabet , underscore
2) Number can be used but not at starting : 1_length(Wrong),
length_1(Right)
3) Python is case sensitive .
4) Break , pass , if keywords can not be used in variables .
Basic Data Types in Python:
In python to print the multipline you can use ‘’’(triple quotes)
We can also use f styring if we want to give any variable inside the print
statement
Print(f “cost of bricks per unit is {brick_cost_per_piece}”)
OR
Print(“cost of brick per unit is {} {}
{}” .format(bricks_cost_per_unit,length_of_land, breadth_of_land))
Logger:
To identify the error coming from which line , This will also print but with
more information.
Pip install loguru
From loguru import logger
Logger .info(“f “cost of bricks per unit is {brick_cost_per_piece}”)
Part 3
Operations : Operations that we are going to perform on a number like
sum , multiply and divide .
Total_area_of_land=length*breadth
[Link](f”Total area of my land is {Total_area_of_land}”)
Concatenation :
a=”ram”
b=”shyam”
print(a+b) # ramshyam
Taking User Input :
from loguru import logger
length_of_land=float(input("please enter length of your land "))
breadth_of_land=float(input("please enter breadth of your land "))
area_of_land= length_of_land*breadth_of_land
[Link](f"Total area of land is {area_of_land}")
List in Python
We will cover the below topics in List :
List is a collection of same or different datatypes.
Example : Mistri_total=[“ram pyare”,” Bhushan”]
List1=[“Ramesh”, 1,12.5]
Empty_list=[]
We can keep on adding values in the empty list as per the condition.
To add values to list :
1)Mistri_total.append(“ramu”)
To avoid using append again and again list offeres .extend function also
like below :
Mistri_total =[“ram pyare”,” Bhushan”]
Mistri_new=[“shamu”, “bablu”]
2) Mistri_total.extend(mistri_new)
Also to insert at a particular location use insert .
3) [Link](1,“ramu”)
4) list 3 = list1+list2
Multidimesional List:
Labour_with_cost=[[“Mahesh”,500],[“Ramesh”, 400],[“Suresh”,300]
Features of List :
1) It can have duplicate values
2) It is mutable in nature : Meaning it can change .
3) It can store multiple datatypes.
List is a datatype or data structure ?
List is both data type and data structure : In Python we can consider it as
datastructure as we are collecting data in a structure .
Accessing the list
1) Using colon(:)
from loguru import logger
total_mistri=["Rampyare","bhushan","shyamu", 100, 200, 300]
print(total_mistri[1:3]) #prit from a length list
print(total_mistri[::-1]) # print list in reverse
2) Using length Method:
print(len(total_mistri))
3) Using Insert Method and Append mentod both
# # We want to add Ramu who has a wage of 500
total_mistri=["Rampyare","bhushan","shyamu", 100, 200, 300]
total_mistri.insert(4,"Ramu")
total_mistri.append("500")
print(total_mistri)
Append always add at the end whereas for insert we need to tell the
index
4) Pop Method : It is used to delete the element in list
total_mistri=["Rampyare","bhushan","shyamu", 100, 200, 300]
total_mistri.pop() #removes the last element, you can also give
index
print(total_mistri)
wage=total_mitri.pop() #It also returns the removed value
if wage>100
print(“costly mistri”)
5) Remove Method :
total_mistri=["Rampyare","bhushan","shyamu", 100, 200, 300]
total_mistri.remove(200) # removes element by Value
print(total_mistri)
6) Split Method:
#split method
hash_code="xyz-abc-51b-986-541-a21"
hash_code.split("-")
api_endpoint="[Link]
oauth2/v2.0/authorize"
new_api_list=api_endpoint.split("/")
print(new_api_list)
print(new_api_list[-2])
For Loop and while loop : Easy and not covered
List Comprehension :
Syntax (when there is only if :
New_list_variable_name = [Output for loop if condition]
Syantax (When there is if and else both)
New_list_variable_name =[output if condition else output for loop]
Dictionaries in Python:
Dictinoaries are the key value pairs used in pyhton and mainly used when
using no sql databses . Api responses in json format.
Dictionary is similar to json. Example :
labour_with_cost={"Ramesh":400 , "shyam": 500 , "Rahul":800 , "Suresh":
900}
To iterate dictionary we can use .items function:
for key,value in labour_with_cost.items():
if(value>400):
print(key)
Methods to access dictionary:
Get() : Get method is used to access the values in the dictionary
print(labour_with_cost.get("Ramesh"))
you can also use
print(labour_with_cost["Ramesh"]) but this will give error if the key is not
present
Keys and Values method
print(labour_with_cost.keys())
print(labour_with_cost.values())
Items Method :
It return the tuple of key value pairs from dictionary
print(labour_with_cost.items())
Add elements to the dictionary and add two dictionaries:
labour_with_cost.update({"manish":70})
print(labour_with_cost)
new_dic={"somesh":500,"palu":400}
final_dic={**labour_with_cost,**new_dic} // add two dictionaries
print(final_dic)
In Method in Python: In method is used to traverse through a
string and take count :
name="siddhant gupta"
letter_count={}
for char in name :
if char in letter_count:
letter_count[char]+=1
else :
letter_count[char] =1
print(letter_count)
Tuple :
Tuple is ordered and immutable opposite to list .
Mentioned by the opended and closed braces.()
Eg : data =(1,2,True,”manish”)
Set :
Set is unordered and immutable , can not contain duplicate values.
For example :
Set1={1,2,3,2,7,8}
Create an empty set :
Set_variable =set()
Set Methods:
print(set_variable.union(new_set_variable))
print(set_variable.intersection(new_set_variable))
print(set_variable.isdisjoint(new_set_variable))
String In Python :
To print the ASCII value if a character:
print(ord("a"))
print(ord("z"))
print(ord("A"))
print(ord("Z"))
print([Link]("r"))
print([Link]())
print([Link]())
print([Link]("siddhant","manish"))
print(a)
name ="ramu singh "
print(len(name))
print(len([Link]()))
print([Link]())
list1 = [Link](" ")
print(list1)
Join In Python (.Join)
This method is used to concatenate strings. This is an alternative to + and
concat method.
Final_result=”_”.join(names)
Here _ is separator and names is a list
Function in python :
Functional programming is where we write functions using keyword def
and then when we move to OOP concept , we move to modular
programming.
Types of arguments in the Python
1) Positional Arguments
2) Arbitary Arguments- args , kwargs
3) Default Argument
*ARGS:
Arbitrary arguments are used when we don’t have any limit of the number
of arguments .* is used for packing and unpacking of the arguments
Example :
def sum(*cost):
res =0 #here in * cost whatever values are
passed will turn to tuple
for num in cost:
res+=num
return res
**KWARGS
Key word arguments
Def generic_logging(**kwargs): # here kwargs
becomes dictionary
For key,value in [Link]():
Print([Link])
Calling:
Generic_logging(status=”success”, ststus_code=200, message =”Ran
successfully”)
Generic_logging(status=”FAILED”, status_code=500, error=”table not
found”)
Exception handling in python
Python Exception Handling handles errors that occur during the execution
of a program. Exception handling allows to respond to the error, instead of
crashing the running program.
Raise an Exception
We Raise an exception in Python using the raise keyword followed by an
instance of the exception class that we want to trigger.
Eg :
from loguru import logger
def final_cart_amount(*args,discount=0.1):
try:
result=0
for amount in args:
result+=amount
return(result-(result*discount))
except TypeError :
[Link]("Please provide the amount in integer")
raise Exception("Value provided is not integer")
except Exception as e:
[Link]("cannot process the cart amount")
raise e
try:
final_amount_paid=final_cart_amount(100,500,100,300,"500",discount=0.
5)
[Link](f"total amount to be paid : {final_amount_paid}")
except Exception as e:
[Link](e)
[Link]("Entry in database done , Job ran sucessfully")
Configuration file in python:
It is where we keep those variables whose values keeps on changing with
time.
.ini file or .conf gile or .properties file :
Rules: Here we have different sections where we keep key value pairs for
each [Link] the values inside the config file will default be saved in
string format.
[section1]
Key1: Value1
Key2: Value2
[Section2]
Key1: Value1
Key2: Value2
AES Encryption In Python:
Advanced Encryption Standard : Here like important passwords are
encrypted from plain text to cipher text.
There are different types of encryption like AES-128, AES-192, AES-256 .
Eg: The password is Admin123 , then it is passed to AES , there
CBC(cipher block chain) converts to the cipher text encrypted password
which is kept in the config.
Also for this there is an encryption key which we keep at the OS LEVEL not
in the config file.
Databse connection in Python :
from loguru import logger
import [Link]
connection=[Link](host="localhost",
user="root",
password="sid@1408")
[Link](f"{connection}")
cursor=[Link]()
[Link]("select * from home_builder.labours_table")
result=[Link]()
[Link](f"{result}")
insert_query="INSERT INTO lbours_table (name,role,eages) VALUES (%s,
%s,%s)"
[Link](insert_query,('Rahul','labour',700))
[Link]() # we need to commit in order to
do CRUD operations(create, update , delete ,insert)
[Link]("Entry done in database")
Classes in python:
Class MySqlConnection:
Def__init__(self,config):
[Link]=config
[Link]=None
Mysql_db_connection=MySqlConnection(config)
Here , self is nothing but object of the class .
Object Oriented Programming:
Instance variable vs class variable:
Class variable : Here total_count is class variable
class labour:
total_count=0 # class variable
def __init__(self,first_name,last_name,wage):
[Link]=first_name # instance variable
[Link]=last_name
[Link]=wage # if we write self.__wage it will become a
private variable
labour.total_count+=1
manish_obj= labour("Ramesh","Babu" ,15000)
ramesh_obj= labour("Rajesh","Singh", 400)
suresh_obj= labour("suresh","sahoo", 300)
print(labour.total_count)
Singleton Design Pattern :
This pattern is used where we have to use the same object again and
again.
Eg where we have to use the DB pattern . ehere with every object we
need not to create a new connection again and again.
Generator and yield also tried to do same thing .
Recursion In python:
class Solution:
def printNos(self,n):
if n==0:
return
[Link](n-1)
print(n , end=" ")