Training Topics
Tuesday, July 12, 2022 9:48 PM
1. Python Fundamentals
2. String & Collection
3. Modularity
4. Classes & Objects
5. Operations with files
6. Decorators
7. Multithreading
8. Unit Testing
9. Handling databases
10. Numpy, Pandas, Visualization using Matplotlib
Python Page 1
Setup
Tuesday, July 12, 2022 9:51 PM
1. Download Python3
2. Install Python3 ; Ensure that you check to add python as PATH variable
3. Download VisualStudio /Pycharm IDE
4. To open visual studio at any location
Open cmd
code .
5. Download the extension for Python in Visual Studio
6. Test the enviroment
Python Page 2
Python fundamentals
Tuesday, July 12, 2022 9:52 PM
Python
- object oriented scripting language
- very readable - just like plain English
- interpreted at run time
- interactive
compiler vs interpreter
Eg. java classes
app.java => Hello World
compile -> app.class (bytecode)
java bytecode can be run n number of times without requiring re-compilation
app.py => print ("Hello")
python app.py
entire code in python is interepreted in the run time. Internally python also generates bytecode, but we
do not use it programatically
whitespaces
- In python scope is managed by indentation using whitespaces
- one tab or 4 spacetabs
zen of python
- good practices
- to print zen
import this
Python Page 3
Variables and Values
Tuesday, July 12, 2022 9:59 PM
• Value ==> actual data
"Welcome to training"
100
• Variable ==> name location which holds the value or point to the value
• x = 100
Here x is variable and 100 is value
name = "John Doe"
Here, name is variable and John Doe is value
variables naming convention:
• start variables with small case
• all the new words seperated by underscore eg. top_marks, first_name
• have meaningful names
keywords
• words already known to python interpreter
• can not be used as variable name
• complete list
• Statements
○ A statement is an instruction that the Python interpreter can execute.
x=3
print(x)
• Expressions
○ An expression is a combination of values, variables, operators, and calls to functions.
○ Expression needs to be evaluated
x+2
Statement vs Expressions
Read more here
Operators & Operands
• +, -, * , / ==> operators
• 100+200
+ ==> operator
Python Page 4
+ ==> operator
100, 200 ==> Operands
Operator precedence
1. parenthesis
2. exponentiation
3. division and multiplication
4. addition and subtraction
Division & multiplication has same precedence. They are evaluated left to right
eg. first division is done because of left to right rule
eg. first multiplication would be done because of left to right rule
Logical operators
and
or
not
Comparison operators
==
!=
>
>=
<
<=
Data types
• int
• string
• boolean
○ True,False
○ Case sensitive
○ Should start with capital letters else would not be identified as boolean
○ boolean expressions
▪ 200==200
▪ 10=!100
• float
Python Page 5
• float
Python Page 6
Strings
Tuesday, July 12, 2022 10:23 PM
• immutable objects - can't be changed
• valid strings
first_name = "John" #valid
last_name = 'Doe' #valid
full_name = "John Doe' #error
full_name = "John said 'His full name is John Doe'" #valid
• String concatenation
○ adds two strings
print("John" +"Doe") # valid
>>John Doe
multiply operator with string
• used for repetition
print ("Hello " * 3)
output ==> Hello Hello Hello
formatted strings
• simplify complex strings
• starts with f
Python Page 7
input()
• receives input from user
• always returns string
Type Conversion
• To convert data type from one type to another
int()
float()
str()
bool()
Python Page 8
Escape character
• Use escape character - backslash(/) to ignore special character
String functions:
Python Page 9
Python Page 10
Python Page 11
Decision statements
Tuesday, July 12, 2022 10:50 PM
Decision statements
1. if
2. if else
3. if elif
4. if elif else
if condition:
## if condition is true, this would be executed
else:
## if condition is false, this would be executed
1. if
weather_condition="hot"
if weather_condition == "hot":
print("Drink lots of water")
print("Have a nice day")
2. if and else
Python Page 12
3. if and elif
4. if, elif and else
Python Page 13
Python Page 14
Loops
Tuesday, July 12, 2022 10:52 PM
iterate over a collection of values
• for loops
• while loops
range()
• used to create sequence of integer
• start is inclusive and end is inclusive
range([start], stop, [step])
range(stop)
range(5)
[0,1,2,3,4]
#start point(inclusive) and end point (exclusive)
range([start], stop)
range(5,10)
[5,6,7,8,9]
#start(inclusive) , end (exclusive) , steps
range([start], stop, [step])
range(5,10,2)
[5,7,9]
Python Page 15
fruits=["kiwis","oranges","bananas","apples"]
for fruit in fruits:
print(fruit)
# nested for loop
for x in range (1,7):
for y in range(1,7):
output = f"{x},{y}"
print(output)
Python Page 16
Collections
Tuesday, July 12, 2022 10:52 PM
• Collections ==> data structures to store a bunch of elements
Different collections in python:
• List
• Dictionary
• Tuples
• Set
List
• mutable collection - can modify the list and elements
• indexed
• negative index allowed
• use square brackets to create list
numbers = []
Slicing
numbers [startpoint(inclusive):endpoint(exclusive)]
Python Page 17
2D List
- Data Science & Machine Learning
[
1 2 3
4 5 6
7 8 9
]
- matrix = [
[1,2,3],
[4,5,6],
[7,8,9]
]
- matrix[0][2]
Python Page 18
for row in matrix:
for item in row:
print(item)
Methods/Functions
numbers = [5, 3, 8, 9]
numbers.append(20)
numbers.insert(0,10)
numbers.remove(5)
numbers.clear()
numbers.pop()
numbers.index(5)
numbers.index(50)
50 in numbers # safe
numbers.count(5)
numbers.sort()
None # absence of value
numbers.reverse()
numbers.copy()
Python Page 19
Remove duplicates from a list
numbers = [3,3,4,5,8,8]
uniques = []
for number in numbers:
if number not in uniques:
uniques.append(number)
Tuples
- can't modify (add or remove)
- numbers=()
- numbers=(10,20,30)
Python Page 20
Unpacking
Python Page 21
Unpacking
Dictionaries
employee
name
email
phone
employees = {}
Python Page 22
Python Page 23
Python Page 24
Set
- unordered
- all the items are unique
- set is modifiable ( we can add/remove values in set)
- elements in set is not modifiable
- a list, a set, a dictionary can not be part of set
- Pop method removes random element in the set
input("Enter the number: ")
4567
Four Five Six Seven
1234
One two three four
Python Page 25
Python Page 26
Functions
Tuesday, July 12, 2022 11:54 AM
- Reusable chunks of code
- Function with no return type and no parameters
def greet_trainee():
print("Hello there!!")
print("Welcome to Python training")
print("Enter")
greet_trainee()
print("Exit")
## Required positional arguments
def greet_trainee(first_name, last_name):
print(f"Hello {first_name} {last_name}!!")
print("Welcome to Python training")
print("Enter")
print(greet_trainee("John", "Doe"))
print("Exit")
## keyword arguments
def greet_trainee(first_name, last_name):
print(f"Hello {first_name} {last_name}!!")
print("Welcome to Python training")
print("Enter")
print(greet_trainee(last_name="Doe",first_name="John"))
print("Exit")
keyword arguments always follow positional arguments and not vice-versa
## return statements
def square(number):
return number*number
output = square(9)
print(type(output))
print(output)
## default arguments
def greet_trainee(first_name, last_name, age=30, salary=1000, org="ACN"):
print(f"Hello {first_name} {last_name} {age} {salary} {org}!!")
print("Welcome to Python training")
print("Enter")
print(greet_trainee("John","Doe"))
print(greet_trainee("John","Doe",22))
print(greet_trainee("John","Doe",22, 2000))
print(greet_trainee("John","Doe",22, 2000, "Accenture"))
print("Exit")
Python Page 27
print("Exit")
## variable length arguments
def sum(*input_values):
result = 0
# input_values = 1,2,3,4
for element in input_values:
result =result + element
return result
print(sum(1))
print(sum(1,2))
print(sum(1,2,3))
print(sum(1,2,3,4,5,9))
## variable length keyword arguments
def cart_items(**products):
for product in products.items():
print(product)
cart_items(fruits="apples", color="yellow", pen="Parker")
Python Page 28
lambda
Tuesday, July 12, 2022 12:44 PM
# lambdas
# functions with no name or anonymous functions
# 2x +3
def f(x):
return 2*x+3
print(f(2))
# lambda arguments : expression
a = lambda x : 2*x+3
print(a(2))
lambda arguments : expression
lambda : "Hello There"
def result(f_name, l_name):
return f_name.strip().title() + " " + l_name.strip().title()
print(result(" mary", "jane "))
## lambdas with two variables
full_name = lambda fn,ln : fn.strip().title() + " " + ln.strip().title()
print(full_name(" jane"," mary "))
Python Page 29
Module
Tuesday, July 12, 2022 1:02 PM
Module - a python file
related codes
organize code (classes, functions)
Package - related modules
organize module
How to import module
1. import <<name of the module>>
2. from <<name of the module>> import <<function name>>
# all the functions of the module are available
import greet
## only the functions mentioned would be available
from sample.python import greetings
greet.greet_trainee("Mary", "Jane")
greetings()
Docstring
• Writing documentation
• """"""
• Method_name.__doc__
Python Package
• __init__.py
Python Page 30
Classes & Object
Wednesday, July 13, 2022 11:03 AM
• Class - blueprint/template of an object
• Object - instance of class
• Classes and object are used to model real-world entities. Eg. employee, cart, Person
Class syntax:
class <ClassName>:
statement1
statement2
function1()
function2()
• Class names start with capital letter. eg. Person, Manager, Associate
• In case of multiple words, capitalize first letter of each word. eg. ShippingCart, PointOfSale
Eg. of syntax
• Line 1 defines the class with "class Person:"
• Line 2 defines a class variable
• Line 3 defines a method
• self is a special keyword which represent current instance/object.
○ when line 9 executes, walks() is called upon p1 object; "self" value at line 4&5 woul be p1
Constructors:
• Method which is called at the time of creating an object
p = Person()
Person() implicitly call the constructor __init__(self) to create Person object
• use constructors to add instance variables to class
Classes and Objects Page 31
OOPS Concept:
• Object-oriented programming system
○ Inheritance
○ Polymorphism
○ Encapsulation
○ Abstraction
Inheritance
• parent-child relationship
• child inherits methods and attributes from their parent
• improves code reusability
• multiple inheritance is allowed in python
Syntax of creating parent and child class
class <ParentClass>:
statement1
statement2
statement3
class <ChildClass>(<ParentClass>):
stmt1
stmt2
○ Line 1 creates Person class
○ Line 12 creates Employee class
○ Line 12 also makes Person class parent of Employee
○ Line 13: Empty classes gives error in python. Use pass keyword to make empty classes.
○ After execution, we can see Employee has inherited it's parent's methods and attributes
Classes and Objects Page 32
Method Overriding
• The child class can override parent's method implementation.
• Use the same method signature(method name and parameters) to do so.
• Below screenshot shows an example of method overriding
• Line 9: Employee walks() is overriding parent's walks()
Classes and Objects Page 33
More examples of inheritance
Classes and Objects Page 34
Operator Overloading
1+2
>3
__add__(1,2)
__mul__(1,2)
__div__(2,2)
print(10+21)
print(int.__add__(10,21))
print("10"+"21")
print(str.__add__("10","21"))
Example of Operator Overloading
1. Overloaded add function
2. Overloaded str function used to display
class Student:
def __init__(self, m1, m2):
self.m1 = m1
self.m2 = m2
def __add__(self, other):
m3 = self.m1 + other.m1
m4 = self.m2 + other.m2
return Student(m3,m4)
def __str__(self):
return f"[Student: m1={self.m1}, m2={self.m2}]"
Classes and Objects Page 35
return f"[Student: m1={self.m1}, m2={self.m2}]"
s1 = Student(m1=90, m2=80)
s2 = Student(m1=70, m2=98)
s3 = s1+s2
print(s3)
print(s3.m1)
print(s3.m2)
# dunder - double underscore
Encapsulation
○ Data Hiding
○ Make instance variables private and provide getters and setters for them
○ python does not have any explicit access specifier/modifier keywords( public, private,
protected)
○ use underscores to make variables/method private or protected
def walks(): --> public method
def _walks(): --> protected method
def __walks(): --> private method
Classes and Objects Page 36
Example of private instance variables & getters and setters method
class Person:
def __init__(self):
# make your instance variables private
self.__name = "John"
self.__age = 20
# getter method
def get_name(self):
return self.__name
# setter method
def set_name(self, name):
self.__name = name
def get_age(self):
return self.__age
def set_age(self, age):
if age < 0:
print("Invalid Age")
else:
self.__age = age
def walks(self):
print(f"{self.name} of age {self._age} walks")
self._talks()
def _talks(self):
print(f"{self.name} of age {self._age} talks")
def __str__(self):
return f"[Person: name = {self.__name}, age = {self.__age}]"
p1 = Person()
p1.set__name("Mary")
p1.set__age(25)
print(p1)
Classes and Objects Page 37
# overloaded methods
def add(a, b):
return a + b
def add(a, b, c):
return a + b + c
def add(a, b, c, d):
return a + b + c + d
add(1,2)
add(1,2,3)
add(1,2,3,4)
Classes and Objects Page 38
Exceptions
Tuesday, July 12, 2022 1:03 PM
Exceptions are errors that disruptthe normal flow of execution.
try:
age = int(input("Enter the age: "))
print(age)
except ValueError:
print("Invalid value")
print("Hello")
Example: try and except
# appropriate exception handler
class Person:
def __init__(self):
# make your instance variables private
self.__name = "John"
self.__age = 20
# setter method
def set__name(self, name):
self.__name = name
def set__age(self, age):
try:
if age < 0:
raise ValueError("Age should not be a negative number")
else:
self.__age = age
# appropriate exception handler
except ValueError as error:
print(error)
def __str__(self):
return f"[Person: name = {self.__name}, age = {self.__age}]"
p1 = Person()
p1.set__name("Mary")
print("Start")
p1.set__age(-10)
print(p1)
print("Bye")
app
Multi except block
app
Classes and Objects Page 39
app
def set__age(self, age):
try:
if age < 0:
raise ValueError("Age should not be a negative number")
else:
self.__age = age
x = 10 / 0
# appropriate exception handler
except ValueError as e:
print(e)
except ZeroDivisionError as error:
print("Please do not divide by 0")
finally block
- always executed
def set__age(self, age):
try:
if age < 0:
raise ValueError("Age should not be a negative number")
else:
self.__age = age
x = 10 / 0
# appropriate exception handler
except ValueError as e:
print(e)
except ZeroDivisionError as error:
print("Please do not divide by 0")
finally:
print("I'll always be there")
def set__age(self, age):
try:
self.__age = age
# appropriate exception handler
except ValueError as e:
print(e)
except ZeroDivisionError as error:
print("Please do not divide by 0")
finally:
print("I'll always be there")
Custom Exception
# Example of creating a custom exception
class InvalidAge(Exception):
def __init__(self):
print("Invalid age")
class Person:
Classes and Objects Page 40
class Person:
def __init__(self, name):
self.name = name
self.age = 10
def set_age(self, age):
try:
if age > 0:
self.age = age
else:
# throwing custom exception
raise InvalidAge()
# handling the custom exception
except InvalidAge as error:
print(error)
p1 = Person("John")
p1.set_age(-10)
print("Bye")
Classes and Objects Page 41
I/O with files
Thursday, July 14, 2022 11:34 AM
from pathlib import Path
path = Path("shipping")
# checks if directory exists
print(path.exists())
path = Path("ecommerce")
if not path.exists():
# creates the directory
path.mkdir()
else:
# deletes the directory
path.rmdir()
# glob() - search for files & directories
path = Path()
print(path.glob("*.*"))
for file in path.glob('*.*'):
print(file)
Read and write with text file
app
Write in csv file
import csv
# writing data in csv file
# csv file mentioned should exist
csvfile = open("employee.csv", "w", newline='')
obj = csv.writer(csvfile)
employee_details =[('John',50, 5000),('Mary',45, 4000), ('Dean',25, 2000),('Sam', 15, 500)]
obj.writerows(employee_details)
# for row in employee_details:
# obj.writerow(row)
csvfile.close()
read data in csv file
employee.csv
John,50,5000
Classes and Objects Page 42
John,50,5000
Mary,45,4000
Dean,25,2000
Sam,15,500
import csv
# read data in csv file
# csv file mentioned should exist
csvfile = open("employee.csv", "r", newline='')
obj = csv.reader(csvfile)
for row in obj:
print(row)
Reading data in dictionary format
app
Classes and Objects Page 43
Decorators
Thursday, July 14, 2022 12:22 PM
def division_decorator(func):
def inner_method(a, b):
print("Running decorator")
if a < b:
a, b = b, a
return func(a, b)
return inner_method
@division_decorator
def division(a, b):
return a / b
print(division(14, 7))
print(division(7, 14))
Classes and Objects Page 44
Unit test
Thursday, July 14, 2022 12:34 PM
Expected Output vs Actual Output
## Below is not a unit test.
def sum(a, b):
return a + b
# 1,2 = 3
# inputs - a=1, b=2
# expected output = 3
expected_output = 3
actual_output = sum(1, 2)
if expected_output == actual_output:
print("Pass")
else:
print("fail")
Actual Test
import unittest
def sum(a, b):
return a + b
class AppTest(unittest.TestCase):
def test_sum(self):
expected_output = 30 # 10 +20
actual_output = sum(10, 20)
self.assertEqual(actual_output, expected_output)
self.assertEqual(sum(10, 10), 20)
self.assertTrue(sum(50, 50) == 100)
self.assertGreater(sum(10,10),10)
self.assertGreaterEqual(sum(10,10),20)
if __name__ == '__main__':
unittest.main()
Classes and Objects Page 45
Handling of databases
Thursday, July 14, 2022 12:51 PM
sqlite3
Download sqlite3 DB browser : https://download.sqlitebrowser.org/DB.Browser.for.SQLite-3.12.2-
win64.msi
**Note: Python_DB is in the same folder as current project.
In case of a different path, provide absolute path to connect
import sqlite3
conn = sqlite3.connect('Python_DB.db')
cursor = conn.cursor()
cursor.execute("insert into employee(emp_id, emp_name, emp_salary) values (1004,'Dean',1000)")
conn.commit()
cursor.execute("update employee set emp_salary=6000 where emp_id=1002")
conn.commit()
cursor.execute("delete from employee where emp_id=1001")
conn.commit()
cursor.execute("select * from Employee")
data = cursor.fetchall()
print(data)
Classes and Objects Page 46
Multithreading
Friday, July 15, 2022 9:26 AM
Simple threading example:
from threading import Thread
from time import sleep
class Hello(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
for i in range(20):
#sleep(1)
print(f"{self.name}: {i}")
# create a thread
t1 = Hello("t1")
t2 = Hello("t2")
# start a thread
t1.start()
t2.start()
t1.join()
t2.join()
print("Done with the program")
Synchronization
import threading
from threading import Thread
from time import sleep
class Hello(Thread):
def __init__(self, name):
Thread.__init__(self)
self.name = name
def run(self):
thread_lock.acquire()
for i in range(10):
#sleep(1)
print(f"{self.name}: {i}")
thread_lock.release()
Classes and Objects Page 47
thread_lock.release()
thread_lock = threading.Lock()
# create a thread
t1 = Hello("t1")
t2 = Hello("t2")
# start a thread
t1.start()
t2.start()
t1.join()
t2.join()
print("Done with the program")
Classes and Objects Page 48
Data Analysis & Visualization
Friday, July 15, 2022 9:52 AM
• numpy
○ scientific computing
○ numerical and statistical analysis
• pandas
○ data analysis
○ data science
○ reads any file format and creates an object in the memory
• matplotlib
○ data visualization module for python
○ quick analysis of data
Setup
Open command prompt as admin
pip3 install --upgrade pip
if above gives error
pip install --upgrade pip
## at the time of training : version of pip 22.1.2
Install jupyter notebook
pip install jupyter
Start jupyter notebook
jupyter notebook
Please execute below commands
pip install numpy
pip install pandas
pip install openpyxl
pip install matplotlib
pip install seaborn
Data Analysis And Visualization Page 49
numpy hands-on
Friday, July 15, 2022 10:50 AM
Output would be seen in below file. Open with a browser
numpy_han
dson
.py file
numpy_han
dson
# ndim: number of array dimensions
x = np.array([1, 2, 3])
x.ndim
x = np.zeros([2,3,2])
print(x)
x.ndim
Data Analysis And Visualization Page 50
pandas hands-on
Friday, July 15, 2022 11:27 AM
sample_data.csv
Name, LOC, Proj, Salary
Tom, DDC, ACV, 2000
Harry, BDC, PQR, 9000
Henry, PDC, QWE, 1999
Rohit, PQR, TRY, 5000
Mohit, QWD, DDC, 2000
Chris, GTH, MPI, 3000
sample_dat
a
sample
sample
training_da
ta
.html for pandas handson (with output)
pandas_ha
ndson
.py file for pandas handson
pandas_ha
ndson
Data Analysis And Visualization Page 51
matplotlib
Friday, July 15, 2022 11:56 AM
student
matplotlib_
handson
matplotlib_
handson
Data Analysis And Visualization Page 52