5.1 Python Workbook
5.1 Python Workbook
5.1 Python Workbook
Coding in python
Presented by, Laika Satish
Why do we need Coding
• Code controls our computerized world. Each website, mobile phone application,
computer program, and even robots and devices depends on code to work. This makes
coders the modellers and manufacturers of the computerized age.
High level
Interpreted Language
Open source
Easy to use and learn
Used for GUI
Uses of python
Python can also be used
in web development Easy to use
using django.
Refer to the links above for full installation of python and anaconda
package
Jupyter Workbook
• You can create a new file and upload it in your working directory.
• You can also save your file in the current working directory
Looking at the output
a,b = 0, 1
# multiple assignment
a,b = b, a+b
Print a,b
Will this statement give you an error.
Try to rectify the error.
Try a,b instead of print(a,b)
Try the following codes
Comparison operators ==,!=,<,>,<=,>=
1 a = 2 1 a = 2
a=5 //is an integer 2 2
B=4.7 //float 3 b = 4 3 b = 4
C=true //boolean 4 4
print (‘Regenesys’ + 'South Africa') 5 print(a != b) 5 print(a > b)
Print(1+2)
Y=6**3
Y==65 1 a = 2 1 a = 10
Y=65 2 2
Y=a+b 3 b = 4 3 b = 10
"Regenesys"[3] 4 4
5 print(a < b) 5 print(a >= b)
Token
Tokens are the smallest unit of the
program. There are following
tokens in Python:
Reserved words or Keywords
Identifiers
Literals
Operators
Boolean Literals:
A Boolean literal can
have any of the two
values: True or False.
Collection literals: String Literals: Numeric Literals: Special literals:
There are four different A string literal is a Numeric Literals are Python contains
literal collections List sequence of characters immutable one special literal
literals, Tuple literals, surrounded by quotes. A (unchangeable). Numeric i.e. None. We use
Dict literals, and Set character literal is a single literals can belong to 3 it to specify to
literals. character surrounded by different numerical types that field that is
single or double quotes. Integer, Float, and not created.
Complex.
Identifiers
# Output
print("Welcome," + name)
add = num + 1
# Output
print(add)
Exercise
Write a program to input a number from the user and find its square.
Loops and iterations
a = 9
b = 12
c = 3
x = a - b / 3 + c * 2 - 1
y = a - b / (3 + c) * (2 - 1)
z = a - (b / (3 + c) * 2) - 1
print("X = ", x)
print("Y = ", y)
print("Z = ", z)
Iteration is the ability to execute a
certain code repeatedly.
while loop
Loops and iterations
while expression: # Take user input
statement(s) usernumber = 2
count = 0
# Condition of the while loop while (count < 3):
while usernumber < 5 :
count = count + 1
# Find the mod of 2
if usernumber%2 == 0: print(“Welcome to Regenesys")
print("The number "+str(usernumber)+" is even")
else:
print("The number "+str(usernumber)+" is odd") # Single statement while block
count = 0
# Increment 'number' by 1 while (count == 0):
usernumber = usernumber+1 print("Welcome to Regenesys")
"break" and "continue“, Pass statements
i = 5
if condition: if (i == 5):
# Statements to execute if # condition is true
if (i < 20):
print ("i is smaller than 20")
i = 10
if (i < 15): if (i < 10):
print ("10 is less than 15") print ("i is smaller than 10 too")
else:
print ("i is greater than 20")
String operations
var1 = 'Hello lala!'
var2 = "welcome to coding in Python "
# Iteration
for a in range(len(split_string)):
temp = split_string[:a + 1]
temp = "_".join(temp)
Output.append(temp)
# print output
print(Output)
Activity
Split the Even and Odd elements into two different lists
Fill a list with the mix of odd and even numbers and based on whether the
element is even or odd, split into two different lists.
Examples:
Take 2 Lists ,concatenate them ,Take a third list which may be a subset of the
concatenated lists .Check for each element in List 3 whether the item is present
in the concatenated lists
Output
Apples :present in list
Pears:present in list
Grapes :Present in list
What are functions and why do we need them .
Session 2
There are three types of # Define a function 'plus()'
functions in Python: def plus(a,b):
return a + b
Use the keyword def to declare the function and the function name.
Add parameters to the function within the round brackets
Add your code that the function needs to execute.
Write a return statement the function needs to output.
Session 2
Session 2
Examples of Built-in functions
abs(-7)
chr() Built In function returns the character in python for an ASCII value.
Session 2 chr(65)
dict([(1,2),(3,4)])
Examples of Built-in functions
The slice object is used to slice a given sequence (string, bytes, tuple, list or range) or any
object which supports sequence protocol
Session 2
Python Lambda Expression
Session 2
Classes in object oriented programming
A class is a blueprint for objects- one # A simple example class
class for any number of objects of that class Test:
type
# A sample method
def fun(self):
To define a class in python print("Hello and welcome to regenesys")
programming, we use the ‘class’
keyword. This is like we use ‘def’ to # Driver code
define a function in python. obj = Test()
obj.fun()
To access the members of a Python
Session 2 class, we use the dot operator
The __init__ method run as soon class Person:
as an object of a class is
instantiated. # init method or constructor
The method is useful to do any def __init__(self, name):
initialization you want to do with self.name = name
your object.
# Sample Method
def say_hi(self):
print('Hello, my name is', self.name)
p = Person('Duke')
p.say_hi()
Session 2
class Student:
# Class Variable
stream = 'computer science'
Instance variables are variables whose value is # The init method or constructor
assigned inside a constructor or method with def __init__(self, roll):
self.
# Instance Variable
Class variables are variables whose value is self.roll = roll
assigned in class.
# Objects of CSStudent class
x = Student(101)
y = Student(102)
print(x.stream)
Session 2 print(y.stream)
print(x.roll)
# Instance Variable
self.roll = roll
# Driver Code
a = Student(101)
a.setAddress("durban, South Africa")
print(a.getAddress())
In Python, we use double underscore class MyClass:
(Or __) before the attributes name and
those attributes will not be directly # Hidden member of MyClass
visible outside __hiddenVariable = 0
def __repr__(self):
return "Test a:%s b:%s" % (self.a, self.b)
def __str__(self):
return "From str method of Test: a is %s," \
"b is %s" % (self.a, self.b)
# Driver Code
t = Test(1234, 5678)
print(t) # This calls __str__()
Session 2
print([t]) # This calls __repr__()
Changing Class Members in Python
# Class for Computer Science Student
class Student:
stream = 'computer' # Class Variable
def __init__(self, name, roll):
self.name = name
self.roll = roll
print ("Initially")
print ("a.stream =", a.stream )
print ("b.stream =", b.stream )
Session 2
Student
Here, Person can be class Person:
called any of the pass
following: class Student(Person):
Super Class pass
Parent Class issubclass(Student,Person)
Base Class
Student here is: Here, class Student inherits from class Person.
Sub Class Here, since we only want to focus on the python
Child Class syntax, we use the ‘pass’ statement in the bodies of
Derived Class the classes.
Also, we use the function issubclass() to confirm
that student is a subclass of person.
Session 2
Types of Inheritance in Python
Single Inheritance in Python Python Multiple Inheritance
A single Python inheritance is Multiple Python inheritance are when a
when a single class inherits from class inherits from multiple base classes.
a class
x=0
class car:
def __init__(self):
global x
x+=1
print("I'm a car")
class bmw(car):
def __init__(self):
super().__init__()
global x
x+=2
Session 2 print("I'm bmw")
x
Python Multiple Inheritance
class Color:
pass
class Fruit:
pass
class Orange(Color,Fruit):
pass
issubclass(Orange,Color) and issubclass(Orange,Fruit)
Session 2
Multilevel Inheritance in Python Hierarchical Inheritance in Python
class A: class A:
x=1 pass
class B(A): class B(A):
pass pass
class C(B): class C(A):
pass pass
cobj=C() issubclass(B,A) and
cobj.x issubclass(C,A)
Session 2
Hybrid Inheritance in Python
class A:
x=1
class B(A):
pass
class C(A):
pass
class D(B,C):
pass
dobj=D()
dobj.x
Session 2
Python Inheritance Super Function – Super()
print("I'm in B")
bobj=B()
bobj.sayhi()
Session 2
Exception If part of your code might throw an
Handling in exception, put it in a try block.
Python
The try:
try/except for i in range(3):
blocks print(3/i)
except:
print("You divided by 0")
print(‘This prints because the exception was handled’)
When an exception is thrown in a try block, the interpreter looks for the
Session 2 except block following it. It will not execute the rest of the code in the try
block.
It is possible to have a,b=1,0
multiple except blocks try:
for one try block. print(a/b)
print("This won't be printed")
print('10'+10)
except TypeError:
print("You added values of incompatible
types")
except ZeroDivisionError:
print("You divided by 0")
Session 2
When the interpreter encounters an try:
exception, it checks the except blocks print('10'+10)
associated with that try block. print(1/0)
except (TypeError,ZeroDivisionError):
print("Invalid input")
Python Multiple
Exception in one
Except
Solving all these problems using various methods is called Data Preprocessing,
Step 1: Importing the libraries.
Simple dataset that contains information about Use the read_csv function from the
customers who have purchased a particular product pandas library.
from a company. Now we’ll show the imported data.
It contains various information about the customers The data imported using the read_csv function
like their age, salary, country, etc. is in a Data Frame format,
It also shows whether a particular customer has We’ll later convert it into NumPy
purchased the product or not. arrays to train the model
In any dataset used for machine learning, In our dataset, the country, age, and salary column are
there are two types of variables: the independent variable and will be used to predict
the purchased column which is the dependent variable.
Independent variable
Dependent variable
In the dataset we have two missing values one in To perform this process we will
the Salary column in the 5th Row and another in use SimpleImputer class from the ScikitLearn library
the Age column of the 7th row.
missing_values = np.nan” means that we are replacing missing values and “strategy = ‘mean’ ”
means that we are replacing the missing value with the mean of that column.
Step 4: Encoding categorical data
OneHot Encoding
OneHot Encoding
Therefore each country will have a unique vector/code and no correlation between the vectors and outcome can
be formed
The ColumnTransformer class allows us to select the column to apply encoding on and
leave the other columns untouched.
Step 4: Encoding categorical data
use 'data.iloc[:,-1]'
Before we begin training our model there is one final step So it is necessary that we
to go, which is splitting of the testing and training convert the data to arrays.
dataset.
We do that while separating the
The last (purchased) column is the dependent variable and dependent and independent
the rest are independent variables, so we’ll store the variables by adding .values while
dependent variable in ‘y’ and the independent variables in storing data in ‘X’ and ‘y’.
‘X’.
Step 6: Splitting the dataset
Step 6: Splitting the dataset
arr = np.arange(10)
The NumPy ndarray: A Multidimensional Array Object
The axis labels are collectively called index. The axis labels are collectively called index. Pandas
Pandas Series is nothing but a column in an Series is nothing but a column in an excel sheet.
excel sheet.
Creating a Pandas Series
A new object is produced unless the new index is equivalent to the current one and copy=False
Data visualization is the process of representing Charts and graphs can make it easier for
data visually. humans to interpret large quantities of
information
These representations typically take the form of
graphs or charts ,
which are used by humans to interpret and draw
useful insights from data.
What is Data Visualization?
Data visualization makes it possible for Whether you’re just getting to know a dataset or
us to perceive trends in data as well as preparing to publish your findings,
to understand how data are related. visualization is an essential tool.
call read_csv(), you create a DataFrame, which is the main data structure used in pandas.
Your dataset contains some columns related to the earnings of graduates in each major:
.plot() returns a line graph containing data from every row in the DataFrame.
The x-axis values represent the rank of each institution,
and the "P25th", "Median", and "P75th" values are plotted on the y-axis.
Looking at the plot in your code book , you can make the following observations:
The median income decreases as rank decreases. This is expected because the rank is
determined by the median income.
Some majors have large gaps between the 25th and 75th percentiles. People with these
degrees may earn significantly less or significantly more than the median income.
Other majors have very small gaps between the 25th and 75th percentiles. People with
these degrees earn salaries very close to the median income.
Plotting libraries: Step 1
First, you import the matplotlib.pyplot module and rename it to plt. Then you call plot() and
pass the DataFrame object’s "Rank" column as the first argument and the "P75th" column as the
second argument.
The result is a line graph that plots the 75th percentile on the y-axis against the rank on the x-axis:
Plotting libraries
Step 1
.plot() is a wrapper for pyplot.plot(), and the result is a graph identical to the one you produced with
Matplotlib:
You can use both pyplot.plot() and df.plot() to produce the same graph from columns of
a DataFrame object. However, if you already have a DataFrame instance, then df.plot() offers cleaner
syntax than pyplot.plot().
Step2
You have a Series object, you can create a plot for it. A histogram is a good way to visualize
how values are distributed across a dataset. Histograms group values into bins and display a
count of the data points whose values are in a particular bin.
Step3
To sort by the "Median" column, use .sort_values() and
provide the name of the column you want to sort by as well as the direction ascending=False.
To get the top five items of your list, use .head().
Step4
DataFrame containing only the top five most lucrative majors. As a next step, you can create a
bar plot that shows only the majors with these top five median salaries:
Step5
Check for Correlation
A quick glance at this figure shows that there’s no significant correlation between the earnings and
unemployment rate.
While a scatter plot is an excellent tool for getting a first impression about possible correlation,
it certainly isn’t definitive proof of a connection.
For an overview of the correlations between different columns,
you can use .corr().
Step6
Immutable means
Session 4 Tuples are immutable which means you cannot update or change the
values of tuple elements
The Tuple
Session 4
numbers = (1, 2, 3, 4)
print (numbers)
(1, 2, 3, 4)
List1 = [1, 2, 3, 4]
Tuple1 = tuple(List1)
print (Tuple1)
Session 4
Slicing a Tuple
Session 4
Operations on Tuples
Comparison
Iteration
a = [1, 2, 3, 4, 5]
print(5 in a)
print(10 in a)
True
False
Session 4
Comparison
Session 4
Concatenation (+)
a = (1, 2, 3)
b = (4, 5, 6)
c = a + b
print (a, b, c)
Session 4
Repetition (*)
a = (1, 2, 3)
b = (4, 5, 6)
print (a*2, b)
Session 4
Functions
tuple1 = ()
print(len(tuple1))
tupleA = ("Regenesys", "is", "the", "best")
Session 4 print(len(tupleA))
min() and max() Functions
max(tuple)
Returns item from the tuple with max value
min(tuple)
Returns item from the tuple with min value
myTuple = tuple('Regenesys')
Session 4 print (myTuple)
print(min(myTuple))
print(max(myTuple))
Example: min_max.py
# copying a frozenset
C = A.copy()
print(C)
# union
print(A.union(B))
# intersection
print(A.intersection(B))
Session 4 # difference
print(A.difference(B))
# symmetric_difference
print(A.symmetric_difference(B))
# Frozensets
# initialize A, B and C
Frozenset operations
A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])
C = frozenset([5, 6])
# isdisjoint() method
print(A.isdisjoint(C))
# issubset() method
Session 4 print(C.issubset(B))
# issuperset() method
print(B.issuperset(C))
Python RegEx
^a...s$
Session 4
The above code defines a RegEx pattern.
The pattern is: any five letter string starting with a and ending with s.
Python RegEx
abs No match
alias Match
import re
pattern = '^a...s$'
test_string = 'alias'
result = re.match(pattern, test_string)
Session 4 if result:
print("Search successful.")
else:
print("Search unsuccessful.")
We used re.match() function to search pattern within the test string.
[] - Square brackets
a 1 match
ac 2 matches
Session 4 [abc]
Hey Jude No match
abc de ca 5 matches
[ ] - Square brackets
Session 4
. - Period
A period matches any single character (except newline '\n').
Session 4
Program to extract numbers from a string
Import re
Import re
# multiline string
string = 'abc 12\
de 23 \n f45 6'
# multiline string
string = 'abc 12\
de 23 \n f45 6'
# Output: ('abc12de23f456', 4)
re.search()
import re
if match:
print("pattern found inside the string")
else:
Session 4 print("pattern not found")
Match object
import re
match.group(1)
match.group(2)
match.group(1, 2)
Session 4 match.groups()
Our pattern (\d{3}) (\d{2}) has two subgroups (\d{3}) and (\d{2}).
Match object
match.start()
match.end()
match.span()
Session 4
Projects in python
Presented by, Laika Satish
Project : Files
For Example, You need Microsoft word software to open .doc binary
files. Likewise, you need a pdf reader software to open .pdf binary
files and you need a photo editor software to read the image files and
so on
Text files in Python
Text files don’t have any specific encoding and it can be opened in
normal text editor itself.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
Text files in Python
Text files don’t have any specific encoding and it can be opened in
normal text editor itself.
Example:
Web standards: html, XML, CSS, JSON etc.
Source code: c, app, js, py, java etc.
Documents: txt, tex, RTF etc.
Tabular data: csv, tsv etc.
Configuration: ini, cfg, reg etc.
Python File Handling Operations
Open
Read
Write
Close
Rename
Delete
Python Create and Open a File
Python has an in-built function called open() to open a file.
It takes a minimum of one argument as mentioned in the below syntax.
The open method returns a file object which is used to access the write,
read and other in-built methods.
Here, file_name is the name of the file or the location of the file that you
want to open,
file_name should have the file extension included as well. Which means in
test.txt – the term test is the name of the file and .txt is the extension of
the file.
The mode in the open function syntax will tell Python as what operation
you want to do on a file.
‘r’ – Read Mode: Read mode is used only to read data from the file.
‘w’ – Write Mode: This mode is used when you want to write data into the
file or modify it. Remember write mode overwrites the data present in the
file.
‘a’ – Append Mode: Append mode is used to append data to the file.
Remember data will be appended at the end of the file pointer.
‘r+’ – Read or Write Mode: This mode is used when we want to write or
read the data from the same file.
‘a+’ – Append or Read Mode: This mode is used when we want to read
data from the file or append the data into the same file.
Python Write to File
In order to write data into a file, we must open the file in write mode.
We need to be very careful while writing data into the file as it overwrites
the content present inside the file that you are writing, and all the
previous data will be erased.
We have two methods for writing data into a file as shown below.
write(string)
writelines(list)
Project :Geometric Figure Calculator
Square
Rectangle
Triangle
Circle
Hexagon
You can analyze the common characteristics and find out that all of these are 2D
shapes. Therefore, the best option is to create a class Shape with a
method get_area() from which each shape will inherit.
Note: All the methods should be verbs. That’s because this method is
named get_area() and not area().
In the __init__ method, we’re requesting two
parameters, side1 and side2. These will remain as instance attributes.
The get_area() function returns the area of the shape. In this case, it’s
using the formula of area of a rectangle since it’ll be easier to implement
with other shapes.
Remember that a square is just a rectangle whose four sides are all equal.
That means we can use the same formula to get the area.
You can find the circle area with the formula πr², where r is the circle’s
radius. That means we have to modify the get_area() method to
implement that formula.
Note: We can import the approximate value of π from the math module
The code above defines the Circle class, which uses a different
constructor and get_area() methods.
Although Circle inherits from the Shape class, you can redefine every
single method and attribute it to your liking.
Regular Hexagon Class
We will use the OpenCV library for this project. Install it using pip
install opencv-python command.
We are going to use a dog image. You can choose whatever you
want.
Step 3: Invert the grayscale image also called the negative image,
this will be our inverted grayscale image. Inversion is basically used
to enhance details.
Finally, to run the speech we use '2"8"&9+!#$% All the -+5$% texts
won’t be said unless the interpreter encounters '2"8"&9+!#$%.
Why pyttsx?
Download the YouTube videos which you like by coding this project.
Project: Automatic Password generator
Use the random method to select at least one character from each
array of characters.
Step 1
Step 2
Step 3
Randomly select at least one character from each character set above
Step 4
Step 5
We fill the rest of the password length by selecting randomly from the combined list of character
above.
Step 6
Step 7
Let’s take a password as a combination of alphanumeric characters along with special characters, and
check whether the password is valid or not with the help of few conditions.
Step 1
Step 2
Step 3
Step 4
Function call
Project: Chatbot_buddy
A rule-based bot uses some rules on which it is trained, while a self-learning bot
uses some machine-learning-based approach to chat.
We will use a simple and quick chatbot in python using a rule-based approach
Project: Chatbot_buddy
Create the chatbots list of recognizable patterns and it’s a response to those
patterns. To do this we will create a variable called pairs.
For example, if the string input was “I am buddy”, then the output would be
“you are buddy”.
Project: Chatbot_buddy
Start a conversation
Text translation from one language to another is increasingly becoming common
for various websites as they cater to an international audience.
The python package called translate helps us do this is called translate.
FizzBuzz game
The FizzBuzz algorithm comes from a children’s game. This algorithm has been
one of the favourite coding interview questions for a very long time. In this
problem, you are given a range of integers and you need to produce output
according to the rules mentioned below:
This python project is to build a game for a single player that plays with
the computer
In situations where both players choose the same object, the result will
be a draw.
Project :Face Detection
Link to download
https://raw.githubusercontent.com/opencv/opencv/master/data/haarca
scades/haarcascade_frontalface_default.xml
Steps
Detect faces