You are on page 1of 177

Introduction to

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.

• Coding helps us to become confident problem solver.

• How will you learn to code


This year, we are hosting a series of courses in our Regenesys locations along with our
friends. This introduction and advanced coding courses in python will teach you the
basics and advanced concepts of python .
Why do we need to learn python
• Machine Learning
• Data Science
Technical description of python

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.

Used in many domains Clear syntax

Can execute a variety


Powerful in Data
of complex
Analytics
computations
Jupyter Language kernels

o The Jupyter Notebook App is a o Language kernels are


server-client application that programs designed to
enables you to edit your code read and execute code
through a web browser. in a specific
programming
language, like Python
Installation of &

Instal for Windows

Instal for Mac-OS

Refer to the links above for full installation of python and anaconda
package
Jupyter Workbook

Note that you


don't get a kernel
error when
opening the
Jupyter
notebook .
Cell to type the code

• 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

Here you give some values to x and print x.


concatenate with + or neighbors Assigning values:

word = 'hi' + x size = 20


a = b = c = 3
subscripting of strings
'Hello'[2] à '1' Numbers
integer, float
slice: 'Hello'[1:2] à 'el'
complex numbers: abs(z)
word[-1] à last character Strings
len(word) à 5 'hello world','it\'s hot'
"bye world"
Basic programming

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

Identifiers in python are user-defined names to represent programmable entity


like variables, functions, classes, modules or any other objects.
But there are a few rules that we need to follow while defining an identifier. They
are:
üYou can use a sequence of letters (lowercase (a to z) or uppercase (A to Z)). You
can also mix up digits (0 to 9) or an underscore (_) while defining an identifier.
üYou can’t use digits to begin an identifier name.
üYou should not use Reserved Keywords to define an identifier.
üOther than underscore (_) you are not allowed to use any other special
characters.
# Taking input from the user
name = input("Enter your name: ")

# Output
print("Welcome," + name)

# Taking input from the user as integer


num = int(input("Enter a number: "))

add = num + 1

# Output
print(add)

Exercise

Write a program to input a number from the user and find its square.
Loops and iterations

Iteration is the ability to for letter in 'Regenesys':


execute a certain code print(letter)
repeatedly.
cities = ['Johannesburg ', 'Capetown','Durban']
For loop for city in cities:
print ('Current city :', city)
for iterating_var in
sequence: statements(s) print ("Good bye!")

cities = ['Johannesburg', 'Capetown','Durban']


for index in range(len(cities)):
print ('Current city :', cities[index])
Activity
Write the output.

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

# Prints out 0,1,2,3,4 for letter in 'Durban':


if letter == 'b':
count = 0 pass
while True: print ('This is pass block')
print(count) print ( 'Current Letter :'+letter)
count += 1
if count >= 5:
break

# Prints out only odd numbers - 1,3,5,7,9


for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)
The Range Function
Types of range() function
range(0, 10) range(5,10) range(50,1000,100)
for seq in range(10):
print(seq) for seq in range(5,10): for seq in
print(seq) range(50,1000,100):
list(range(10))
print(seq)
for seq in range(-
len(list(range(10)))
5,0):
print(seq)
list(range(0, 10, 3))
if (condition): # Executes this block if # condition is true

Python if Statement Syntax else:


# Executes this block if # condition is false

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 "

print ("var1[0]: ", var1[0])


print ("var2[1:5]: ", var2[4:13])

var1 = 'Hello regenesys students!'


print ("Updated String :- ", var1[:6] + 'welcome')
# Iterating through a string # Python code to split string in substring manner
count = 0
for letter in 'Regenesys': # Input initialisation
if(letter == 'e'): Input = "Regenesys_for_learning_is_best"
count += 1
print(count,'letters found') # Split initialise
split_string = Input.split('_')

# Output list initialise


Output = []

# 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:

Input : [9, 12, 17, 1, 3, 4, 28, 23]


Output : Even lists: [12, 4, 28]
Odd lists: [17, 9, 1,3, 23]
Lists and Dictionaries
Lists are mutable, and hence, they can Dictionary in Python on the other hand is
be altered even after their creation. an unordered collection of data values,
used to store data values like a map, which
A single list may contain DataTypes like unlike other Data Types that hold only
Integers, Strings, as well as Objects single value as an element,

Dictionary holds key:value pair


Lists
prices = [7.35, 1.99, 5.5, 1.66]
prices.append(2.49)
prices.insert(2, 11.49)
prices del prices[1]
prices.sort()
print(prices)
prices.sort(reverse=True)
print(prices)
Dictionaries
# Creating a Dictionary
# with Integer Keys
Dict = {1: Regenesys', 2: 'For', 3: 'South Africa'}
print("Dictionary with the use of Integer Keys: ")
print(Dict)

player = { 'firstName': 'Tom','lastName':'john','nbaDebutYear':'2020'}


player['firstName']
player['lastName']
player['nbaDebutYear']
Try it out and write the output

letters = ['a', 'b', 'c', 'd', 'e']


slice = letters[1:4]
print (slice)
print letters
Mini Project

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

Input :list1 :Apples, Mangoes, Pears


List2: Grapes,Pomegranates
Concatenated List :Apples ,Mangoes,Pears,Grapes ,Pomegrantes
List3 :Apples ,Pears,Grapes

Output
Apples :present in list
Pears:present in list
Grapes :Present in list
What are functions and why do we need them .

A function is a self-contained Syntax


block of code that encapsulates
a specific task or related group
def function_name(parameters):
of tasks..
statement(s)
Functions help break our
program into more modest and
return
organised chunks. As our
program develops bigger and
Session 2 bigger, functions make it more def myfunction():
coordinated and reasonable. s = '-- Inside myfunction()'
print(s)
Moreover, it keeps away from
redundancy and makes the code print('Before calling f()')
reusable. myfunction()
print('After calling f()')
Working of a function

Session 2
There are three types of # Define a function 'plus()'
functions in Python: def plus(a,b):
return a + b

Built-in functions like min() to # Create a 'Summation' class


get the minimum value, print() to class Summation(object):
print the output. def sum(self, a, b):
self.contents = a + b
User-Defined Functions (UDFs), return self.contents
which are functions that are
created by developers .

Anonymous functions, which are


Session 2 also called lambda functions sumInstance = Summation()
because they are not declared with sumInstance.sum(1,2)
the standard def keyword.
def square(x): square(2)
return x*x

User-Defined Functions (UDFs)


The four steps to defining a function in Python are the following:

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

The abs() returns the absolute value of a number.


A negative value’s absolute is that value is positive.

abs(-7)

chr() Built In function returns the character in python for an ASCII value.

Session 2 chr(65)

dict(), as we have seen it, creates a python dictionary.

dict([(1,2),(3,4)])
Examples of Built-in functions

round() rounds off a float to the given number of digit round(3.777,2)

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

Python lambda expression allows us to define a lambda [arg1,arg2,..]:[expression]


function anonymously. It is worthwhile to note
that it is an expression, not a statement.

That is, it returns a value; it has an implicit


return statement. The following is the Python
syntax of a lambda expression in Python.

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)

# Class variables can be accessed using class


# name also
print(Student.stream)
# Class for Computer Science Student
class Student:
we can create
# Class Variable
# instance variables inside methods stream = 'computer science'

# The init method or constructor


def __init__(self, roll):

# Instance Variable
self.roll = roll

# Adds an instance variable


def setAddress(self, address):
self.address = address

# Retrieves instance variable


def getAddress(self):
Session 2 return self.address

# 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

# A member method that changes


we tried to access # __hiddenVariable
hidden variable outside def add(self, increment):
the class using object self.__hiddenVariable += increment
and it threw an print (self.__hiddenVariable)
exception.
# Driver code
myObject = MyClass()
myObject.add(2)
myObject.add(5)
Session 2
# This line causes error
print (myObject.__hiddenVariable)
Printing objects gives us class Test:
information about objects def __init__(self, a, b):
we are working with. self.a = a
self.b = b

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

# Driver program to test the functionality


# Creating objects of CSStudent class
a = Student("ron", 1)
b = Student("tony", 2)

print ("Initially")
print ("a.stream =", a.stream )
print ("b.stream =", b.stream )

# This thing doesn't change class(static) variable


Session 2 # Instead creates instance variable for the object
# 'a' that shadows class member.
a.stream = "ece"

print ("\nAfter changing a.stream")


print ("a.stream =", a.stream )
print ("b.stream =", b.stream )
We should change class variables # Class for Computer Science Student
using class names only. class Student:
stream = 'computer science' # Class Variable
def __init__(self, name, roll):
self.name = name
self.roll = roll

# New object for further implementation


a = Student("check", 3)
print( "a.stream =", a.stream)

# Correct way to change the value of class variable


Student.stream = "ecs"
print( "\nClass variable changes to ecs")

# New object for further implementation


b = Student("chloe", 4)
Session 2
print( "\nValue of variable steam for each object")
print ("a.stream =", a.stream)
print( "b.stream =", b.stream)
Python Inheritance Method Overloading &
Method Overriding

What is Inheritance in Python? the relationship from person to a student


is termed ‘Specialization’.

every student is a person, this is called


Generalization.
Person

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

Multilevel Inheritance in Python


When one class inherits from another, which in turn inherits from another,
it is multilevel python inheritance.

Hybrid Inheritance in Python Hierarchical Inheritance in Python


Hybrid Python inheritance is a When more than one class inherits from a
Session 2 combination of any two kinds of class, it is hierarchical Python inheritance.
inheritance.
Single Inheritance in Python

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()

With inheritance, the class Vehicle:


super() function in python def start(self):
allows us to call a method print("Starting engine")
from the parent class. def stop(self):
print("Stopping engine")
class TwoWheeler(Vehicle):
def say(self):
super().start()
print("I have two wheels")
super().stop()
Pulsar=TwoWheeler()
Pulsar.say()
Session 2
Python Override Method

A subclass may change the class A:


functionality of a Python def sayhi(self):
method in the superclass. It
does so by redefining it. print("I'm in A")
class B(A):
def sayhi(self):

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

Session 2 You can also have one


except block handle multiple
exceptions
Some code may raises try:
a TypeError. print("1")
print("2")
except:
print("3")

try: So we have Finally Block in Python


print(1/0) Optionally, you may include a finally
except: exception block after the last except block.
raise The code under this block executes in all
except: circumstances.
print("Raised exception caught")
finally:
Session 2 print("Okay")
print("Bye")
The Python exception message is printed after the finally
block executes.

Raise Keyword in Python


Sometimes, you may want to deal with a situation by
raising a certain exception

Assertions in Python It takes an expression as an


argument and raises a python
Session 2 exception if the expression has a
False Boolean value.
Data Preprocessing using Python

Data Preprocessing is the process of making Steps in Data Preprocessing:


data suitable for use while training a machine
learning model. 1. Importing the libraries
2. Importing the dataset
The dataset initially provided for training might 3. Taking care of missing data
not be in a 4. Encoding categorical data
ready-to-use state, for e.g. it might not be 5. Normalizing the data
formatted properly, or may contain missing or 6. Splitting the data into test and train
null values.

Solving all these problems using various methods is called Data Preprocessing,
Step 1: Importing the libraries.

NumPy:- it is a library matplotlib:- this library Pandas:- pandas


that allows us to work helps in plotting graphs allows us to import
with arrays and as and charts, which are our dataset and
most machine learning very useful while also creates a
models work on arrays showing the result of matrix of features
NumPy makes it easier your model containing the
dependent and
independent
variable.
Step 2: Importing the dataset.

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

It also contains a null value in the fifth row.


Step 2: Importing the dataset

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

The independent variable is the columns


that we are going to use to predict
the dependent variable,
Step 3: Handling the missing values

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.

The dataset is very small and we cannot


just ignore those rows.

So we use another method, in which we


take the mean of the entire column and
replace the missing values with that mean.
Step 3: Handling the missing values

We will only select the column with numerical data,


as the mean can only be calculated on numerical data

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

We have two categorical columns, the country column,


the purchased column

OneHot Encoding

In the country column, we have three different categories:


France, Germany, Spain.
Label France as 0, Germany as 1, and Spain as 2
Step 4: Encoding categorical data

OneHot Encoding

Turn the country column into three separate columns,


each column consists of 0s and 1s.

Therefore each country will have a unique vector/code and no correlation between the vectors and outcome can
be formed

To perform this encoding use OneHotEncoder and ColumnTransformer class from


the ScikitLearn library.

The ColumnTransformer class allows us to select the column to apply encoding on and
leave the other columns untouched.
Step 4: Encoding categorical data

The ColumnTransformer class


allows us to select the column to
apply encoding on and leave the
other columns untouched.
Step 4: Encoding categorical data

Each country has got a unique vector or code,


for example,
France is 1 0 0,
Spain 0 0 1,
Germany 0 1 0.
use LabelEncoder class from the same ScikitLearn library
for label encoding .
Label Encoding

In the last column, i.e. the purchased column, the


data is in binary form meaning that there are only
two outcomes either Yes or No.

Therefore here we need to perform Label Encoding.


Step 4: Encoding categorical data

use 'data.iloc[:,-1]'

to select the index of the column we


are transforming.

our data will look like this


Step 4: Encoding categorical data

The purchased column has been successfully transformed.


Step 5: Normalizing the dataset

Feature scaling is bringing all When we normalize the dataset it


of the features on the dataset to the same brings the value of all the features
scale, between 0 and 1 so that all the columns
are in the same range, and thus there is
This is necessary while training a machine no dominant feature.
learning model.

Because in some cases the dominant Normalize the dataset we


features become so dominant that the use MinMaxScaler class from the
other ordinary features are not even same ScikitLearn library.
considered by the model
Step 5: Normalizing the dataset

This is the output after normalizing

All the values in the dataset are now between 0


and 1, so there are no dominant features, and all
features will be considered equally.
Step 6: Splitting the dataset

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

We are going to go with an 80-20%


split between the train-test data. So
80% training and 20% testing data.

test_size = 0.2 signifies that we have


selected 20% of data as testing data
The NumPy ndarray:
A Multidimensional Array Object

Arrays enable you to perform An ndarray is a generic


mathematical operations on whole multidimensional container for
blocks of data using similar syntax homogeneous data; that is, all of the
to the equivalent operations elements must be the same type.
between scalar elements

arr = np.arange(10)
The NumPy ndarray: A Multidimensional Array Object

Applications Numpy Arrays

NumPy is used in various applications A Numpy array is a collection of homogeneous


such as: values (all of the same data type) and is indexed
by a tuple of nonnegative integers.
Matrix Computations
Numerical Analysis The number of dimensions (count of rows) is
Image processing the rank of the array.
Signal processing
Linear algebra The shape of an array is a tuple of integers,
A plethora of others which indicates the size of the array along each
dimension.
# Creating a 1-D array import numpy as nparr = np.array([8, 9, 10])
print(arr)
print(type(arr))

Checking Array Dimensions and Shape

#Checking the dimensions of the


arrayprint(arr.ndim)
# Checking shape of the
arrayprint(arr.shape)
Pandas Series

Pandas Series is a one-dimensional labeled Pandas Series is a one-dimensional labeled array


array capable of holding data of any type capable of holding data of any type (integer, string,
(integer, string, float, python objects, etc.). float, python objects, etc.).

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

In the real world, a Pandas Series will be created # import pandas as pd


by loading the datasets from existing storage, import pandas as pd
storage can be SQL Database, CSV file, and Excel
file. # import numpy as np
import numpy as np
Pandas Series can be created from the lists,
dictionary, and from a scalar value etc. Series can # simple array
be created in different ways, here are some ways data = np.array([‘r','e',‘g',‘e',‘n'])
by which we create a series
ser = pd.Series(data)
print(ser)
Pandas dataframe.reindex() function conform DataFrame to new index with optional filling logic,
placing NA/NaN in locations having no value in the previous index.

A new object is produced unless the new index is equivalent to the current one and copy=False

# import numpy and pandas module


import pandas as pd
import numpy as np

column =['a', 'b', 'c', 'd', 'e']


index =['A', 'B', 'C', 'D', 'E']

# create a dataframe of random values of array


df1 = pd.DataFrame(np.random.rand(5, 5),
columns = column, index = index)

colum =['a', 'b', 'c', 'g', 'h']

# create the new index for columns


print(df1.reindex(colum, axis ='columns', fill_value ='data missing'))
Use reindex() function to reindex the In the output,
dataframe. new indexes are populated with NaN values,
we can fill in the missing values using the
By default values in the new index that do not parameter, fill_value
have corresponding records in the dataframe
are assigned NaN.

We have NaN values in the new columns after reindexing,


we can take care of the missing values at the time of reindexing.
By passing an argument fill_value to the function.
Pandas Dataframe.rank()

Pandas is one of those packages # sorting w.r.t team name


and makes importing and data.sort_values("Team", inplace = True)
analyzing data much easier.
# creating a rank column and passing the returned rank series
Pandas Dataframe.rank() # change method to 'min' to rank by minimum
method returns a rank of every data["Rank"] = data["Team"].rank(method ='average')
respective index of a series
passed. # display
data
The rank is returned on the basis
of position after sorting.
What is Data Visualization?

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.

Python’s popular data analysis library, pandas,


provides several different options for visualizing your
data with .plot().

Even if you’re at the beginning of your pandas journey,

you’ll soon be creating basic plots that will yield


valuable insights into your data.
Plotting libraries

Matplotlib: low level, provides lots of freedom


Pandas Visualization: easy to use interface, built on Matplotlib
Seaborn: high-level interface, great default styles
Plotly: can create interactive plots
Plotting libraries: Step 1

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:

"Median" is the median earnings of full-time, year-round workers.


"P25th" is the 25th percentile of earnings.
"P75th" is the 75th percentile of earnings.
"Rank" is the major’s rank by median earnings.

Let’s start with a plot displaying these columns.


Plotting libraries: Step 1

.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

If you don’t provide a parameter to .plot(),


then it creates a line plot with the index
on the x-axis and all the numeric columns on the y-axis

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

Analyze Categorical Data


Grouping
A basic usage of categories is grouping and aggregation. You can use .groupby() to
determine how popular each of the categories in the college major dataset are:
Mini
Project
The Tuple Data Structure

In Python, a tuple is an immutable sequence of values

Immutable means

Session 4 Tuples are immutable which means you cannot update or change the
values of tuple elements
The Tuple

Each value in the tuple is an element or item


Elements can be any Python data type

School = ("Regenesys", 2021)

Session 4

tuple name a string an integer


Creating Tuples

You can declare a tuple by


tup1 = ()
To cast a list as a tuple, you use tuple()
List1 = [6, 17,21]
Tuple1 = tuple(List1 )
print(type(Tuple1 ))
Session 4
Creating Tuples

numbers = (1, 2, 3, 4)
print (numbers)
(1, 2, 3, 4)

countries= ('Germany', ‘South Africa', 'India', 'Nigeria')


print (countries)
Session 4
Creating Tuples

List1 = [1, 2, 3, 4]
Tuple1 = tuple(List1)
print (Tuple1)

Str1 = 'South Africa'


Session 4 Tuple2 = tuple(Str1)
print (Tuple2)
Tuple Indexing

Elements within a tuple are indexed

countries= ('Germany', 'South Africa', 'India', 'Nigeria')


print (countries[0])
print (countries[3])
print (countries[-1])

Session 4
Slicing a Tuple

Like other sequences, tuples can be sliced


Slicing a tuple creates a new tuple. It does not change the original tuple.

countries= (‘Germany’, ‘South Africa‘, ‘India', ‘Nigeria')


print (countries[1:4])

Session 4
Operations on Tuples

Membership tests (using the in keyword)

Comparison

Iteration

Concatenation and repetition


Session 4
Functions

The min() ,len() ,max() functions


Membership Tests (in)

In Python, the in keyword is used to test if a value is present in the sequence.


Returns True or False

a = [1, 2, 3, 4, 5]
print(5 in a)
print(10 in a)
True
False
Session 4
Comparison

In Python , The comparison operator, == is used, to do tuple comparison


Returns True or False

tuple1, tuple2 = (1, 'Badminton'), (2, 'Football')


tuple3 = (3, 'cricket')
print (tuple1==tuple2)
Session 4 print (tuple2==tuple3)
Iteration

teams = ((1, 'Badminton'),(2, 'Cricket'), (5, 'Football'),(7, 'Volleyball'))

for (index, name) in teams:


print(index, name)

Session 4
Concatenation (+)

The + operator the concatenation of two tuples

a = (1, 2, 3)
b = (4, 5, 6)
c = a + b
print (a, b, c)

Session 4
Repetition (*)

The * operator returns a new tuple that repeats the tuple.

a = (1, 2, 3)
b = (4, 5, 6)
print (a*2, b)

Session 4
Functions

The method len() returns the number of elements in the tuple.

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

# Returns the minimum and maximum


# elements of a sequence as a tuple
def min_max(t):
return min(t), max(t)

seq = [8, 79, 43, 71, 2, 84]


Session 4 print (min_max(seq))

string ='The new tuple is'


print (min_max(string))
myMin, myMax = min_max(string)
# Frozensets
# initialize A and B
Frozenset operations A = frozenset([1, 2, 3, 4])
B = frozenset([3, 4, 5, 6])

# 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 Regular Expression (RegEx)


is a sequence of characters that defines a search pattern.

^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

Expression String Matched?

abs No match

alias Match

^a...s$ Alias No match


Session 4
An abacus No match
Python has a module named re to work with regex.

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.

The method returns a match object if the search is successful.


If not, it returns None.
Session 4
• [] - Square brackets

[] - Square brackets

Square brackets specifies a set of characters you wish to match.

Expression String Matched?

a 1 match

ac 2 matches
Session 4 [abc]
Hey Jude No match

abc de ca 5 matches
[ ] - Square brackets

Complement (invert) the character set by using caret ^ symbol


at the start of a square-bracket.
[^abc] means any character except a or b or c.
[^0-9] means any non-digit character.

Session 4
. - Period
A period matches any single character (except newline '\n').

Session 4
Program to extract numbers from a string

Import re

string = 'hello 12 hi 89. joe 34'


pattern = '\d+'

Session 4 result = re.findall(pattern, string)


print(result)
re.split()

Import re

string = 'Twelve:12 Eighty nine:89.'


pattern = '\d+'

Session 4 result = re.split(pattern, string)


print(result)
re.sub()

# Program to remove all whitespaces


import re

# multiline string
string = 'abc 12\
de 23 \n f45 6'

# matches all whitespace characters


pattern = '\s+'
Session 4
# empty string
replace = ''

new_string = re.sub(pattern, replace, string)


print(new_string)2
# Program to remove all whitespaces

# Program to remove all whitespaces


import re

# multiline string
string = 'abc 12\
de 23 \n f45 6'

# matches all whitespace characters


pattern = '\s+'
Session 4 # empty string
replace = ''

new_string = re.subn(pattern, replace, string)


print(new_string)

# Output: ('abc12de23f456', 4)
re.search()

import re

string = "Python is fun"

# check if 'Python' is at the beginning


match = re.search('\APython', string)

if match:
print("pattern found inside the string")
else:
Session 4 print("pattern not found")
Match object

import re

string = '39801 356, 2102 1111'

# Three digit number followed by space followed by two digit


number
pattern = '(\d{3}) (\d{2})'

# match variable contains a Match object.


match = re.search(pattern, string)
Session 4
if match:
print(match.group())
else:
print("pattern not found")
Match object

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

If you are working in a large software application where


they process a large number of data, then we cannot
expect those data to be stored in a variable as the
variables are volatile in nature.

Hence when are you about to handle such situations, the


role of files will come into the picture.

As files are non-volatile in nature, the data will be stored


permanently in a secondary device like Hard Disk and
using python we will handle these files in our applications.
Project : Files

How normal people will handle the files.

If we want to read the data from a file or write the data


into a file, then, first of all, we will open the file or will
create a new file if the file does not exist and then perform
the normal read/write operations, save the file and close it.
Types Of File in Python

There are two types of files in Python and each of them


are explained below in detail with examples for your
easy understanding.
They are:

Text file Binary file


Example:

• Document files: .pdf, .doc, .xls etc.


• Image files: .png, .jpg, .gif, .bmp etc.
• Video files: .mp4, .3gp, .mkv, .avi etc.
• Audio files: .mp3, .wav, .mka, .aac etc.
• Database files: .mdb, .accde, .frm, .sqlite etc.
• Archive files: .zip, .rar, .iso, .7z etc.
• Executable files: .exe, .dll, .class etc.
All binary files follow a specific format. We can open some binary files in the normal
text editor but we can’t read the content present inside the file. That’s because all the
binary files will be encoded in the binary format, which can be understood only by a
computer or machine.

For handling such binary files we need a specific type of software to


open it.

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

Most importantly there are 4 types of operations that


can be handled by Python on files:

Open
Read
Write
Close

Other operations include:

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.

file_object = open(file_name, mode)

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

Your task is to create an area calculator of the following


shapes using OOP Concepts:

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.

The __str__() method is a “magic method” just as __init__(). It allows


you to modify the way an instance will print.

The self.__class__.__name__ hidden attribute refers to the name of


the class. If you were working with a Triangle class, that attribute would
be “Triangle.
Rectangle Class

Since we implemented the formula of area of the Rectangle, we could


create a simple Rectangle class that does nothing but inherit from
the Shape class.

To apply inheritance in Python, you’ll create a class as usual and


surround the superclass you want to inherit from by parenthesis.
Square Class

We can take an excellent approach to polymorphism with


the Square class.

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.

We can do this by modifying the init method, accepting only a side as a


parameter, and passing that side value to the constructor of
the Rectangle class.
As you can see, the super function passes the side parameter twice to the superclass. In other
words, it’s passing side both as side1 and side2 to the previously defined constructor.
Circle Class

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 only need the length of a side of a regular hexagon to calculate its


area. It’s similar to the Square class, where we only pass an argument to
the constructor.
However, the formula is quite different, and it implies the use of a square
root. That’s why you’ll use the sqrt() function from the math module.
Project: Image to pencil sketch

This is going to be interesting. We will be writing the code step by


step with the explanation.

We will use the OpenCV library for this project. Install it using pip
install opencv-python command.

Step 1: Find an image that you want to convert to a pencil sketch.

We are going to use a dog image. You can choose whatever you
want.

Step 2: Read the image in RBG format and then convert it to a


grayscale image. Now, the image is turned into a classic black and
white photo.
Project: Image to pencil sketch

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.

Step 4: Finally create the pencil sketch by mixing the grayscale


image with the inverted blurry image. This is done by dividing the
grayscale image by the inverted blurry image

We now got our pencil_sketch. So, display it using OpenCV.


Text to speech in python

pip install gTTS

pyttsx is a cross-platform text to speech library which is platform independent. The


major advantage of using this library for text-to-speech conversion is that it works
offline. However, pyttsx supports only Python 2.x. Hence, we will see pyttsx3 which is
modified to work on both Python 2.x and Python 3.x with the same code.
Usage –
First we need to import the library and then initialise it
using !"!#$% function. This function may take 2 arguments.
!"!#$&'!()'*+,) -#'!"./0&)12.01334%
drivername : [Name of available driver] sapi5 on Windows
| nsss on MacOS
debug: to enable or disable debug output

After initialisation, we will make the program speak the text


using -+5$% function. This method may also take 2 arguments.
-+5$#)6#02"!73&)/0"+,)0-#'!".%
text : Any text you wish to hear.
name : To set a name for this speech. (optional)

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?

It works offline, unlike other text-to-speech libraries. Rather than


saving the text as audio file, pyttsx actually speaks it there. This
makes it more reliable to use for voice-based projects.
Project YouTube video downloader

Download the YouTube videos which you like by coding this project.
Project: Automatic Password generator

Having a weak password is not good for a system that demands


high confidentiality and security of user credentials. It turns out
that people find it difficult to make up a strong password that is
strong enough to prevent unauthorized users from memorizing it.

Mixture of numbers, alphabets, and other symbols found on the


computer keyboard to form a 12-character password which is
unpredictable and cannot easily be memorized.

The components of the password are represented in the form of


arrays.
Project: Automatic Password generator

Use the random method to select at least one character from each
array of characters.

Since the 12-character password is required, so fill the rest of the


length of the password left with randomly selected characters from
an array formed from the combination of all the characters needed
in the final password. Anytime the password is generated, shuffle
the password using random.shuffle() to ensure that the final
password does not follow a particular pattern.
Project: Automatic Password generator

Step 1

set maximum length of password needed


This can be changed to suit your password length
Declare arrays of the character that we need in password
Represent chars to enable easy string concatenation
Project: Automatic Password generator

Step 2

Combines all the character arrays above to form one array.

Step 3

Randomly select at least one character from each character set above

Step 4

combine the character randomly selected above


# at this stage, the password contains only 4 characters but
# we want a 12-character password
Project: Automatic Password generator

Step 5

We fill the rest of the password length by selecting randomly from the combined list of character
above.

Step 6

Convert temporary password into array and shuffle to


prevent it from having a consistent pattern
where the beginning of the password is predictable

Step 7

traverse the temporary password array and append the chars


# to form the password

Last step :print out password


Project: Correct /Incorrect password validation

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.

Conditions for a valid password are:

Should have at least one number.


Should have at least one uppercase and one lowercase character.
Should have at least one special symbol.
Should be between 6 to 20 characters long.
Project: Count Down with a timer

Step 1

Import the time module.

Step 2

Define the countdown func.

Step 3

Input time in seconds.

Step 4

Function call
Project: Chatbot_buddy

There are broadly two variants of chatbots, Rule-based and Self-learning.

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.

#Pairs is a list of patterns and responses.

Reflections is a dictionary file that contains a set of input values and


corresponding output values.

For example, if the string input was “I am buddy”, then the output would be
“you are buddy”.
Project: Chatbot_buddy

Print a default message, and finish chatbot:

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:

If the integer (x) is divisible by 3, the output must be replaced by “Fizz”.

If the integer (x) is divisible by 5, the output must be replaced by “Buzz”.

If the integer (x) is divisible by 3 and 5, the output should be replaced by


“FizzBuzz”.
Snake ,water,gun game
Snake Water Gun is one of the famous two-player game played by many
people. It is a hand game in which the player randomly chooses any of
the three forms i.e. snake, water, and gun. Here, we are going to
implement this game using python.

This python project is to build a game for a single player that plays with
the computer

Following are the rules of the game:

Snake vs. Water: Snake drinks the water hence wins.


Water vs. Gun: The gun will drown in water, hence a point for water
Gun vs. Snake: Gun will kill the snake and win.

In situations where both players choose the same object, the result will
be a draw.
Project :Face Detection

Face detection using Haar cascades is a machine learning based


approach where a cascade function is trained with a set of input data.
OpenCV already contains many pre-trained classifiers for face, eyes,
smiles, etc..

You need to download the trained classifier XML


file (haarcascade_frontalface_default.xml), which is available
in OpenCv’s GitHub repository. Save it to your working location.

Link to download

https://raw.githubusercontent.com/opencv/opencv/master/data/haarca
scades/haarcascade_frontalface_default.xml
Steps

Load the cascade

Read the input image

Convert into grayscale

Detect faces

Draw rectangle around the faces

Display the output


Project Fidget Spinner

Fidget spinners are advertised to increase concentration


and attention to academic tasks. Past research
suggests that hyperactive movements, such as fidgeting,
improve performance on attention tasks in children with
attention-deficit/hyperactivity disorder (ADHD).
1. Change the spinner pattern.
2. Respond to mouse clicks.
3. Change its acceleration.
4. Make it go forwards and backwards
Payroll calculator

Dearness Allowance (DA) = Basic pay × DA %/100 House Rent


Allowance (HRA)= Basic pay × HRA%/100 Total salary = Basic
pay + DA + Medical + HRA + conveyance Net salary = Total
salary – Professional tax – Provident fund

Payroll calculations usually constitute 4 main components – Basic


pay, Allowances, Deductions, and IT Declarations.
Titanic Dataset: Handling Missing values

Popular strategies to handle missing values in the dataset


1.Deleting Rows with missing values.
2.Impute missing values for continuous variable.
3.Impute missing values for categorical variable.
4.Other Imputation Methods.
5.Using Algorithms that support missing values.
6.Prediction of missing values.
Outlier detection on Adult dataset

Outliers are data values that differ greatly from


the majority of a set of data. These values fall
outside of an overall trend that is present in the
data.
print calendar of the month as per the user input.

Built -in-function: calendar is a function module


allows to calculate weekdays as per the user input
and return the output.

You might also like