0% found this document useful (0 votes)
9 views22 pages

Data Set - Machine Learning

The document discusses the fundamentals of machine learning, including its various approaches such as supervised, unsupervised, and reinforcement learning. It emphasizes the importance of datasets, data types, and preprocessing techniques for effective machine learning. Additionally, it highlights applications of machine learning across different fields, including medical diagnosis, speech recognition, and business intelligence.

Uploaded by

womoxa2171
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views22 pages

Data Set - Machine Learning

The document discusses the fundamentals of machine learning, including its various approaches such as supervised, unsupervised, and reinforcement learning. It emphasizes the importance of datasets, data types, and preprocessing techniques for effective machine learning. Additionally, it highlights applications of machine learning across different fields, including medical diagnosis, speech recognition, and business intelligence.

Uploaded by

womoxa2171
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Notes

Machine Learning

observations unseen by the machine during training. Huge data collection and storage technologies
have altered the landscape of scientific data analysis, which includes natural resources, prediction
of floods, astronomy, biology and etc. Machine learning is present in all those examples.

Figure1: Block Diagram of a learning machine

1.2 Data set


Data set is the collection of data used for machine learning. Basically, the dataset is divdided into
three categories. They are training data, testing Data and validation Data. Here, the training data is
considered for initial training purpose. Testing data is used for checking the trained machine.
Validation data is used for tuning the trained machine with the help of important
[Link] data is the data used to train an algorithm or machine learning model, is
depicted in the given figure 1.
Table 1 The data table

The above representation as given in Table 1, depicts the input as N instances, s(1), s(2), … S(N),
each is an example of the concept to be learned. Each instances provides the input to the machine
learning algorithm, and is categorized by its values mentioned as y, as in the last column. The data
can be understood in more elaborated, as given below.
Four types of data are explained here, as it is often be handled in the process of dataset preparation
or preprocessing. The data types are as given below.

 Numerical Data
 Categorical Data
 Time Series Data
 Text Data

Numerical Data
Numerical data is a datatype expressed in numbers. This further classified as continuous and
discontinuous data as in Figure 2.

2 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 01: Introduction to Machine Learning

Figure 2 Numerical Data

Categorical Data
Categorical data is a collection of information that is divided into groups. They are further divided
into two types such as ordinal and nominal.

Ordinal Data
Ordinal data has ranking / ordering. Ordinal features are sorted or ordered as in the figure 3.
Size of T-Shirt - S, M, L, XL.
Convert string values into integer as per order like XL > L > M > S.

Figure 3 Ordinal Data

Nominal Data

 Nominal features are not ordered as in figure 4. Nominal data has No ranking / order.
 Colourof T-Shirt: Red, Green, Blue.
 Assign numeric value to each feature.
 0 -> Red, 1 -> Green, 2 -> Blue

Figure 4Nominal Data

Time Series Data


A Time Series is a sequence of data points that occur in successive order over some period of time
as in Figure 5.

LOVELY PROFESSIONAL UNIVERSITY 3


Notes

Machine Learning

Figure 5Time Series Data

Text Data
Text data usually consists of documents, which can represent words, sentences or even paragraphs.
Usually, digital information can be categorized into two classes. They are structured and
unstructured. Studies have recently revealed that more than 70 percent of all the data available for
corporations today is unstructured. But, structured data fits into a fixed format or data table, what
we discussed in Table 1 above.
Preprocessing is the process of fixing or removing incorrect, corrupted, incorrectly formatted,
duplicated, or incomplete data within a dataset. Depicted in Figure 6. This is mainly focusing on
dealing with missing data and handling categorical data.

Figure 6Steps of Data Cleaning


Missing values can be handled through the simplest method called Imputation method. And, we
should note that Removal of entire row/column may lose too much valuable data. Hence, we
should avoid at maximum effort for the removal of rows and columns. Also, different interpolation
techniques can be used to estimate the missing values like mean / median / mode imputation. This
will increase the efficiency of data set. Sample model is shown in Figure 7.

4 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 01: Introduction to Machine Learning

Figure 7 Machine Learning Model


Machine learning can be done in one of three approaches, that is, Supervised, Unsupervised and
Reinforcement. These approaches are discussed below. Any method that incorporates information
from experience in the design of a machine employs learning.

1.3 Supervised Learning


Machines are trained using well-labelled training data as in Figure 8. The data provided for training
should be very much correct without any false data as the machine solely depending on the given
data for its training. Means, the machine is designed by exploiting the a priori known information
in the form of “direct” training examples consisting of observed values of system states / input
vectors and the response / output to each states.

Figure 8Supervised Machine Learning


The supervisor has given in the form of given output / response. There are two types of tasks for
which this supervisor can be used. They are classification / pattern recognition problems and the
other one is regression / numeric prediction problems.

1.4 Unsupervised Learning


This approach of leaning will be used when the output / response is not available in the training
data. This type of problem, uses only the set of feature vectors. This unsupervised learning has to
unravel the underlying similarities in the training data for learning.
Two different types of learning tasks frequently appear in the real world applications of
unsupervised learning. They are, cluster analysis and association analysis. The cluster analysis is
employed to create groups or clusters of similar records on the basis of many measurements made
for these records / feature vectors. A primary issue in clustering is that of defining the similarity
between the feature vectors. It has many applications which includes big data analytics, remote
sensing, image segmentation, image and speech processing and many more. Association analysis
used unsupervised to discover patterns in the data where no target is specified earlier. It is up to
human interpretation to make sense of the patterns. The common area of application is known as
market basket analysis, which studies customer’s purchase patterns for products that are bought
together. This application is widely encountered in online recommender systems, where customers
considering buying a product are shown other products that are often bought along with the
desired products.

LOVELY PROFESSIONAL UNIVERSITY 5


Notes

Machine Learning

Figure 9Unsupervised Machine Learning

1.5 Reinforcement Learning


Reinforcement learning is founded on the concept tha if an action is followed by a satisfactory state
of affairs, or by an improved state of affairs according to some properly defined way, then the
inclination to produce that action becomes stronger. That is known as reinforced. This idea can be
extended to permit the action choices to be dependent on state information, which then brings in
the aspect of feedback.
A reinforcement learning system, is a system that via interaction with its environment enhances its
performance by obtaining feedback in the form of a scalar reward or penalty (a reinforcement
signal), that is indicative of the suitability of the response. The learning is not instructed with
regard to what action has to be taken. Instead it is expected to find out which actions produce the
maximum reward by trying them.
The actions may influence not only the immediate reward but also the next situation, and through
that all subsequent rewards. The two aspects – trial and error search – and cumulative reward are
the two significant distinguishing attributes of reinforcement learning. Even though the early
performance may fail to be up to the mark, with adequate interaction with the environment, it will
ultimately learn an effective strategy for maximizing cumulative reward.
The reinforcement learning problem covers tasks such as learning to control a mobile robot,
learning to optimize operations in factories and learning to play board games. Reinforcement
algorithms are related to dynamic programming algorithms frequently used to solve optimization
problems.

Figure 10Reinforcement Machine Learning

6 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 01: Introduction to Machine Learning

1.6 Applications of Machine Learning


 Machine vision: in this field where pattern recognition has been applied with major successes.
A machine vision system captures images through a camera and analyzes these to be able to
describe the image. A machine vision system is applicable in the manufacturing industry, for
automating the assembly line or for automated visual inspection. Therefore, the images have
to be analyzed online, and a pattern recognition system has to categorize the objects into the
defect or non-defect category. A robot arm can then put the objects in the right place.
 Biometric Recognition: It has been made clear by decades of research in pattern recognition
that the level of visual understanding and recognition that human exhibit cannot be matched
by computer algorithms. Biometric recognition includes finger print identification, face
recognition, gesture recognition and etc.
 Handwriting Recognition: It is the area with major consequences in automation and
information handling. This problem focuses on handwritten documents. We know, the
commercially available detector i.e., Optical Character Recognition (OCR). The typical
application of handwritten recognition is processing the handwritten cheques given the bank
customers. Another application can be an automatic postal mail sorting machines for postal
code identification in post offices.
 Medical Diagnosis: This also uses pattern recognition. Doctors make use of it, while making
diagnostic decisions. The doctor, of course, makes the ultimate diagnosis. Computer aided
diagnosis has been applied to and is of interest for, a range of medical data. They may be, like
X-Rays, computer tomographic images, ultrasound images, electro cardiograms (ECGs) and
Electro encephalograms (EEGs).
 Drug Design: This is usually based on a long and expensive process involving complex
chemical experiments to check whether or not a particular chemical compound could be a
good candidature for a specific drug, which would be a positive result involving further
chemical experiments. For several years, a new scheme based on computational simulations
has been emerging. The general idea is to access the feasibility of a chemical compound for the
synthesis of the drug with a predictive model based on a database of previous experiments.
 Speech Recognition: Speech is the most natural means by which humans share, convey and
exchange information. This area has been well researched so far. Intelligent machines that
recognize spoken information that can be used in numerous applications. For example, to help
control machines by talking to them, entering data into a computer via a microphone. Speech
recognition can enhance our ability to communicate with deaf and dumb.
 Text Mining: This concerns identification of patterns in text. The procedure involves analysis
of text for extraction of useful information for specific [Link] way, information
available on the web and on corporate intranets, digital libraries and news wires is spread or
propagated, is overwhelming. Integration of this information into the decision making
process, at a fast pace, is essential in order to help business stay competitive in today’s market.
Text mining has reached the industrial world and is helping to exploit knowledge that is often
beyond human consumption. Typical jobs for mining text databases are classification of
documents into predefined classes, grouping together of similar documents and identifying
documents that fulfill the criteria / specifications of a query.
 Natural Language Processing: Language is obviously a critical component of how people
communicate and how information is stored in the business world and beyond. The goal of
Natural language processing is to analyze, understand, and generate language that humans
use naturally, so that eventually a computer will naturally be able to interpret what the other

LOVELY PROFESSIONAL UNIVERSITY 7


Notes

Machine Learning

person is saying. Spell checking, grammar checking, translation are the other applications of
NLP and etc.,
 Fault diagnostic: Preventive upkeep of motors and generators and other electro-mechanical
devices, can delay malfunctions. Otherwise the deviceswill interrupt industrial
[Link], typical defects or flaws include misalignment of shaft, mechanical
slackening, defective bearings, and unbalanced pumps. Diagnostic of faults are performed
using machine learning algorithms, which is extremely helpful in this field.
 Business intelligence: Business intelligence technologies offer not only historical and current
information but also predictive views of business applications. It is essential for businesses to
be able to comprehend the commercial control of their organization, in term of customer base,
market, supply and resources, and competition. In the absence of data mining, many
businesses may be unable to effectively perform market analysis, compare customer feedback
on similar products, find the strength and weaknesses of their competitors, retain extremely
valuable customers, and arrive at intelligent business decisions.

Summary
In this unit, the concepts of machine learningare discussed along with the different approaches of
machine learning. Each approach is discussed in detail with examples. The differences in each of
the approaches would be better understood. Data set is very important for machine learning.
Hence, it is necessary to understand about the basic data types, which is also explored thoroughly.
This will help to convert or process the obtained data. But, there was also lot of challenges in
processing the data set. This also covered in the name of preprocessing and data cleaning. The
major tasks of preprocessing and the possible ways of data cleaning were also discussed. The
terminology – feature engineering was highlighted as it was related to data cleaning.

Keywords
 Dataset
 Preprocessing
 Datacleaning
 Supervised learning
 Unsupervised learning
 Reinforcement learning

Self Assessment
1. Machine learning approach, which build a model based on sample data, is known as
_______.
A. Supervised
B. Unsupervised
C. Reinforcement
D. None of the above

2. _________ approach uses the rewarding method for machine learning.


A. Supervised
B. Unsupervised
C. Reinforcement

8 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 01: Introduction to Machine Learning

D. None of the above

3. Which of the following dataset is used for supervised machine learning?


A. Training dataset
B. Testing dataset
C. Validation dataset
D. All the above

4. _________ machine learning approach uses unlabelled data for learning.


A. Supervised
B. Unsupervised
C. Reinforcement
D. None of the above

5. The two class problems are otherwise called _________.


A. Clustering
B. Binary Classification
C. Multiclass Classification
D. None of the above

6. Justify the statement. “Preprocessing is the process of converting raw data into data which
will be suitable for machine learning”.
A. True
B. False

7. Preprocessing is actually the combination of data cleaning and __________.


A. Data integration
B. Data transformation
C. Data reduction
D. All of the above

8. Supervised machine learning approachuses the ______ dataset.


A. Labelled Dataset
B. Unlabelled Dataset
C. Both Labelled and Unlabelled
D. None of the above

9. Imputation method is used for _____________.


A. Removing rows
B. Removing columns
C. Filling the missing values
D. None of the above

10. _________ is the process of changing the format, structure or values of data.
A. Data integration
B. Data cleaning

LOVELY PROFESSIONAL UNIVERSITY 9


Notes

Machine Learning

C. Data transformation
D. Data Preprocessing

Answers for Self Assessment


1. A 2. C 3. D 4. B 5. B

6. A 7. D 8. A 9. C 10. C

Review Questions
1. Explain the different types of data.
2. Differentiatenominal and ordinal data types.
3. Give examples for categorical data.
4. List out the methods used for filling the missing values.
5. Identify the machine learning algorithms for each machine learning approaches.

Further Readings
 MadanGopal, Applied Machine Learning, McGraw Hill Education, India, 2018.
 S. N. Sivanandam, S.N. Deepa, Principles Of Soft Computing, Wiley Publications,
Second Edition, 2011.
 Rajasekaran, S., Pai, G. A. Vijayalakshmi, Neural Networks, Fuzzy Logic and Genetic
Algorithm Synthesis And Applications, Prentice Hall of India, 2013.
 N. P. Padhy, S. P. Simon, Soft Computing With Matlab Programming, Oxford
University Press, 2015.

Web Links

 [Link]
 [Link]
 [Link]
3a5e293a5114

10 LOVELY PROFESSIONAL UNIVERSITY


Notes
Dr. VDevendran, Lovely Professional University Unit 02: Python Basics

Unit 02: Python Basics


CONTENTS
Objectives
Introduction
2.1 What is Python?
2.2 Basics of Programming
2.3 IF Statement
2.4 IF – ELSE Statement
2.5 For Loop
2.6 While Loop
2.7 Unconditional Statements
2.8 Functions
2.9 Recursive Function
2.10 Other Packages
Summary
Keywords
Self Assessment
Answers for Self Assessment
Review Questions
Further readings

Objectives
1. To understand the online tools used for python such as JupyterLab and Google Colab.
2. To understandthe fundamentals of programming such as Variables, keywords, Data types,
Expression, Statements, Operator and Operator Precedence.
3. To differentiatethe conditional and unconditional statements from simple if, if-else, nested if, for
loop, while loop, break and continue.
4. To understand the use of function and recursion which will bediscussed with examples.
5. To know the packages in python along with their purposes.

Introduction
In this unit, we try to introduce you the very popular programming language called Python. We
know that there are many programming languages such as C, C++, which were already existed and
used for decades. Here, we will try to understand the merits of python language over others.
Moreover, we will be writing a simple python programand try to execute using an online tool.
Programs can be experimented to understandthe conditional, unconditional statements along with
functions and recursion. Function declaration, calling of functions, parameters can be well
understood from the given examples. Let us begin with what is python.

2.1 What is Python?


The python language is founded and written by Guido van Rossum, who was born in the
Netherlands. His First version (0.9.0) of python was released on February 20, 1991. Presently the

LOVELY PROFESSIONAL UNIVERSITY 11


Notes
Notes
Machine Learning

current version of python is 3.9.7. There are many reasons for its popularity. It is readable like an
English statement having simple syntaxes. Python is a general-purpose open source language.
Python is portable language, so that it runs on many Unix variants including Linux and mac OS,
and on Windows. Python is also an interpreted language, interactive language and object-oriented
programming language. Python codes are executed comparatively little faster.

Figure 1 Founder of Python Language

The language offers multiple ready made libraries such as NumPy, SciPy, MatplotLib, Scikit-Learn
and frameworks which will support the initial phase of development. These are all the reasons
made Python very popular among programming community.

Who are using python?


There are many MNC companies were started using python for their development. Here are the
few such companies and their works are given for better understanding of python language. We
will start with Google company. Google uses Python for web search systems, YouTube video
sharing service is largely written in Python. Dropbox company’s storage service codes both its
server and desktop client software primarily in [Link] Online, a massive multiplayer online
game(MMOG) by CCP Games, uses Python. The widespread BitTorrent peer-to-peer file sharing
system began its life as a Python program. iRobot uses Python to develop commercial and military
robotic [Link] have documented the role of Python in their software infrastructures. Intel,
Cisco, Hewlett-Packard, Seagate, Qualcomm, and IBM use Python for hardware [Link]
Chase, UBS, Getco, and Citadel apply Python to financial market [Link], Los Alamos,
Fermilab, JPL, and others use Python for scientific programming tasks. Now, let us understand,
why we are importance to the python language.

Online Tools
Jupyter Notebook and Google Colab are the popular online tools for programming in python. Let
us first discuss the Jupyter. You will get the access in this link: [Link] Once you
have visited the page, it will look like the figure 2 given below.

Figure 2 Home page of Jupyter

12 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 02: Python Basics

Now please select the first blue color button “Try Classic Notebook”. The page will be looking like
like the figure 3 given below.

Figure 3 The page of Jupyter Classic Notebook


Then, you need to create a new python notebook from the file menu. The page will be looking like
the following figure 4.

Figure 4 New Python Notebook


Now, we are ready to go with our first program. Simple print statements is tested in the above
notebook, just outputting the message “Welcome”.

Python Installation
Python softwares and the installation manual can be downloaded from the link
[Link] You will be shown the opt version with respect to your
system configuration and operating system. Latest version will be Python 3.9.7 as shown in the
figure.

LOVELY PROFESSIONAL UNIVERSITY 13


Notes
Notes
Machine Learning

Figure 5 Python Downloads

Just a click is enough to download. And the procedures are simple for the installation.

2.2 Basics of Programming


The basics start with the simple detail that how to store some information in the program, how to
do some mathematical operations and how to display them in the monitor. The following are very
important for programming. Let us see one by one.

Variables
Variable is a name that refers to a value that may be changed in the [Link] is no command
to declare a variable in python.

Figure 6 Use of Variables


In the above figure, two variables were declared namely a and b having the values 100 (numeric
value) and “Mangolia” (string value) [Link] data type of the variable will be same asof
the data type of the assigned value. Those values are also displayed using the print statement.

Datatype
Variables can store different types of data. They are Numeric Data Types, Boolean Data Type, Set
Data Type, Dictionary and Sequence Data Types as shown in the figure. Let us start with Numeric
Data Types, where only the numbers are involved, whichis again divided into three categories such
as integer (without decimals), float (with decimals)and complex [Link] data will be
storing True or False [Link] will be studied in the coming units in detail.

14 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 02: Python Basics

Figure 7Python Data Types

Keywords
There are some predefined and reserved words have special meaning to python. Those words are
called Keywords. These keywords can not be used as name for the variable / identifier, not to be
used as function names. These are otherwise called as system defined variable. There are more 30
keywords used in python. Few keywords are like, and, or, not, if, elif, else, for, while, break, return,
True, False, continue, in, is, import and etc.

Expression
An expression is a combination of values, variables and operators. This can be understood from an
example given in the following figure. There are three variables a, b and c. The variables are known
as operands. Operators are used in between to perform some operations using the operands. In this
case, plus (+) operator, multiplication (*) operators are used. Final result is stored in the variable
result.

Figure 8Statement of Expression

Let us have an example for an expression. Let a = 10, b=5, c = 3. What will be the output of the
above expression?The output is 25 as shown in the figure.

Figure 9Example of Expression

Statements

LOVELY PROFESSIONAL UNIVERSITY 15


Notes
Notes
Machine Learning

Statements are the instructions given in the source code for [Link] outcome of the program
is depending upon how all the statements are arranged for execution. The statements are executed
in a sequential order starting from the first statement in program. There are three types of
statements in python. They are Assignment statements, Conditional Statements and Looping
Statements, which are discussed below.

Assignment statements
The statements that are used to copy a value into the variable is called assignment statements. The
equal sign (=) is used for copying the value. Hence, the operator (=) is called assignment operator.
The target of an assignment statement is written on the left side of the equal sign (=). The value
what is to be assigned will be in the right side of the equal sign (=).
For example, a = 100 is the assignment statement. Here the value 100 is assigned to the variable a.
And, we have one more example like this. x, y = 50, 100 is also the assignment statement, where the
value 50 is assigned to variable x and the value 100 is assigned to variable y.

Conditional statements
Any statementthat outputs the Boolean value (True / False) is called conditional statement as given
in the figure. Framing of conditions is the key element in controlling the flow of execution. Let us
have an example of conditional statement.

Example 1 : ( a < b )

Example 2 : ( marks >= 75 )


Above two examples will be giving either True or False as the output. Hence, they are called
conditional statements.

Figure 10 Flow of Control

Looping statements
The looping statement(s) are a statementor a block of statements that are used to execute repeatedly
until a specified condition is satisfied. When the condition is True, it executes and when the
condition is False, it stops the [Link] the execution is not getting stopped, then the looping
statement will become infinite [Link] are different looping statements are available such as
while loop and for loop.

Operator
The operators are used to perform some mathematical operations on the values and the variables.
There are few standard symbols available in python. Let us have a look on list of operators and
their usages. According to their usages, all the operators are grouped in different categories such as
arithmetic operators, Relational Operators and logical operators.

Arithmetic Operators

Operator Description Syntax

+ Addition x+y

- Subtraction x-y

16 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 02: Python Basics

/ Division (float) x/y

// Division (floor) x // y

% Modulus x%y

** Power x ** y

Table 1 Arithmetic Operators

Relational Operators
These operators are used to compare the values or variables. The output of relational operators will
be either True or False.

Operator Description Syntax

> Greater than x>y

< Less than x<y

== Equal to x=y

!= Not equal to x != y

>= Greater than or equal to x >= y

<= Less than or equal to x <= y

Table 2 Relational Operators

Logical operators
Logical operators are used to combine two or more conditional statements. The operators are
Logical AND, Logical OR and Logical NOT.

Operator Description Syntax

and Logical AND x and y

or Logical OR x or y

not Logical NOT not x

Table 3 Logical Operators


The logical AND operator outputs the value True if all the conditions are True. But, Logical OR
operator outputs the value True if anyone the condition has the value True. Logical NOT operator
reverse the actual output of the condition such as converts as False if the actual value is True and
vice versa.

Assignment operators
These are used to assign the values to the variable. This operator was already discussed in the topic
of Assignment Statements. Here, let us have the list of other operators used for assignments
operation.

Operator Description Syntax

= Assign value to left side operand x = 100

+= This is simplification of a = a + b a += b

LOVELY PROFESSIONAL UNIVERSITY 17


Notes
Notes
Machine Learning

-= This is simplification of a = a - b a -= b

*= This is simplification of a = a * b a *= b

/= This is simplification of a = a / b a /= b

%= This is simplification of a = a % b a %= b

//= This is simplification of a = a // b a //= b

Table 4 Assignment Operators

Operator Precedence
It is understood that an expression is having one or more operators and operands having simple or
complex mathematical operations. Two operands are needed for an operator to perform the
specified operation. Hence, some order of preference or priority is required to select the operators
to compute the expression. This is called as operator precedence. It can be understood from a
simple expression as shown in the figure.

Figure 11Example of Operator Precedence

In the above figure, the expression first computes the multiplication operator and then the result of
the multiplication is used for the next computation of addition operator. Here, multiplication
operator is having the higher priority than the addition operator. Similarly, there are many other
operators are available as we know. It is important to know their precedence so that we can use
them correctly as per our requirements in the expression. Following figure is trying to give you the
clear picture of precedence; the higher priority starts from top and reaching the lowest priority in
the bottom.

Figure 12 Priority Structure of Operators Precedence

18 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 02: Python Basics

2.3 IF Statement
The flow of execution in a program can be controlled using the proper conditions. Here, is the
simple conditional statement called if statement. This is used to execute a block of statements if the
condition is True and to execute the next statements if the condition is False. Hence, the flow of
execution lies in the decision making as in the figure.

Figure 13 Working with simple IF Statement


Here is an example depicting the simple if statement. The example says it gives the output as
“Eligible for final examination” if the attendance is greater than equal to 75 percentages, otherwise
do nothing and proceeds with the further instructions.

attendance = 90
if (attendance>= 75):
print (“Eligible for final examination”)
Here the variable attendance is having 90. Hence, condition is satisfied and the print statement is
executed successfully. Let us have the same example with the attendance value as 65.

attendance = 65
if (attendance>= 75):
print (“Eligible for final examination”)
What will be the output? Of course, it doesn’t print anything as there are no statements given when
the condition becomes False. This can be solved in the next type of conditional statement.

2.4 IF – ELSE Statement


Previously, the simple if statement is discussed. That is having only one part means that we are
giving the instructions where the condition is True. Here in the if-else statement, we are going to
give the statements for both the sections. One block of statements will be executed when the
condition is true and another block of statements will be executed when the condition is False.
Anyway, at a time, only one block is executed for [Link] figure shown below is explaining the
concepts clearly.

LOVELY PROFESSIONAL UNIVERSITY 19


Notes
Notes
Machine Learning

Figure 14 Working with IF Else Statement

If the condition (if expression) is False, the control is going to false block and reaches the end.
Similarly, if the condition is false, the control is going to true block and reaches the end. Let us
discuss this using an example.
x=6
y=8
if (x>y):
print (“x is greater than y”)
else:
print (“y is greater than x”)
Here, let the variables x and y has the values 6 and 8 respectively. Now, concentrate onthe if
statement and find out the value of condition. (x > y)  ( 6 > 8 ) False. The control goes to the
False Part and outputs “y is greater than x”. In case, if we change the values as x= 8 and y=6. What
will be the output?
x = 86
y = 70
if (x>y):
print (“ x is greater than y”)
else:
print (“y is greater than x”)
yes, we will get the output as “x is greater than y” as the condition becomes True and True Part has
been executed.

2.5 For Loop


We know that this is one of the looping statements. For loop helps us to execute a particular block
of statements repeatedly for a certain number of times. The figure clearly picturize the style of
execution. Number of times can be controlled through the variable. Starting values and Ending
Values are the keys for the control. Use of the variable, can be effectively managed by incrementing
or decrementing the values according to our requirements.

20 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 02: Python Basics

Figure 15 Working with for Loop

On every successful execution of the statement, it goes back to the condition after
increments/decrement the variable and checks the condition still satisfied or not. If satisfied, it
continues to execute the statement again and repeat the same till the condition is failed. Let us have
an example.
for t in range (5):
print (t)
The above example is having the variable t. The initial value will be 0 in this case. The last value
will be 4. Before explaining this, let us take care of what is range function.
This function will create the sequence of numbers in a given range starting from 0 by default. In
this, having range (5) will give values from 0 to [Link] is making the sequence of numbers easy.
Now, let us focus on the output of the for loop statement given above. Here, print (t) is executed
five times.

Output:
0
1
2
3
4

2.6 While Loop


This is also the control statement, whichis used to execute a set of statements till the given condition
is True. On the completion of every execution, it checks for the condition is True or Not. If the
condition fails or the condition is False, the looping is terminated and goes to the successive
statements. The following figure explains the flow of execution.

LOVELY PROFESSIONAL UNIVERSITY 21


Notes
Notes
Machine Learning

Figure 16Flow chart of While Loop

Let me explain you from a simple example [Link] variable used is number having initial value
as 0. Here, the program aims to execute a block of statement till the variable number is not equal to
8, It means it never knows how many times it is going to execute the block of statement. We need to
manage this condition as per our requirements. Here, the task is simple.

Figure 17Example of While Loop

Initially, the value of number is 0. The condition (0 not equal to 8) is True. It executes the block of
statements first time. Now, the value of number is increased by 1 and it becomes number = 1. Now,
it checks the condition again. The condition (1 not equal to 8) is True. It executes the block of
statements second time and it goes on till the condition is True. Stops otherwise.

2.7 Unconditional Statements


The statements, which are not using any condition to controlthe flow of execution, are called as
unconditional statements. There are two unconditional statements used in python, i.e., break and
continue. We discuss these in detail.

Break statement
This statement is used to stop the current execution. There is no need to give any condition for this
break statement. This statement is used whenever you need to stop or whenever you find any
exceptions during the execution. The usage of break statement is understood from an example
given below.
x = 100
while ( x < 600) :
print (x)
if ( x == 300) :
break
x = x + 100
There is a variable x in the example having the initial value as [Link]-loop executes till the value
of x is less than 600. On every execution, the value of x is incremented by 100. But, as there is a
break statement, planned to be executed exactly when x = 300. Hence, it stops the current execution
at that point and never continues the loop further.

Continue Statement
This statement is used to continue to the next iteration (loop) without executing further statements
in the current iteration (loop). There is no need to give any condition for these continue statement.
This statement is used whenever you need to avoid the further statements and want to execute the
next iteration. The usages of continue statement is understood from an example given below.
x = 100
while (x< 600):
print (x)
if (x == 300):
continue

22 LOVELY PROFESSIONAL UNIVERSITY


Notes
Unit 02: Python Basics

x = x + 100
There is a variable x in the example having the initial value as 100. While-loop executes till the
value of x is less than 600. On every execution, the value of x is incremented by 100. But, as there is
a continue statement, planned to be executed exactly when x = 300. Hence, it stops the current
execution at that point and continues to the next iteration(loop). Means, once the continue
statement is executed, further statementsi.e., increment will not be executed and the value of x
remains as 300. So, the loop will further become infinite loop as the condition will not become False
at any case, as there is no increment of value of x.

2.8 Functions
Function is a block of statements, whichis executed only when it is called. Function is given a
specific name. We can use that name whenever we want to call that function. Function can be
divided into twotypes. They are system-defined function and user-defined function. Let us focus
more on the user-defined function. Declaration of function and calling of functions are discussed
here. The following figure represents the usage of passing a value (x) to the function (f) and getting
the output. Function is called by sending the value of x. Function is using the value of x and
performing the computation. The result is sent back as the final output.

Figure 18Block diagram of a function

We know that a function that you define yourself in a program is known as user defined function.
The function definition and declaration is well understood from the example given below. We are
defining a function using the keyword “def”. The name of the function is “fahr_to_celsius”. This
function accepts only one parameter i.e., temp. The computed value is returned from the function
using the keyword “return” as given in the figure. This function does the converting the
temperature into Fahrenheit.

Figure 19 Example of Function definition

Here is one more example, which accepts two parameters a and b. Addition of giventwo numbers
is performed in the function. The function name is my_fun. We are not returning anything from the
[Link] is noreturn statementexist in the function.

Figure 20 Example of Function with two parameters

LOVELY PROFESSIONAL UNIVERSITY 23

You might also like