0% found this document useful (0 votes)
29 views

null

I love you ideots kelamma Juliet nam Preeti chocolate
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)
29 views

null

I love you ideots kelamma Juliet nam Preeti chocolate
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
You are on page 1/ 77

Govt of Karnataka

Dept. Of Collegiate And Technical Education


GOVT POLYTECHNIC RABAKAVI-BANAHATTI
DEPARTMENT OF SCIENCE

20SC02P- STATISTICAL AND ANALYTICAL

Name of Student:

Branch:

Sem:

Register Number:

Sl No Content

1 UNIT-1 STATISTICAL DATA COLLECTION AND TYPES

2 UNIT-2 SUMMARIZATION OF DATA

UNIT-3 MEASURE OF LOCATION AND DISPERSION


3
UNIT-4
INTRODUCTION TO PYTHON PROGRAMMING
4
5 EXPT
SYNTAX AND CODES
SL
Practical outcomes/Practical exercises ACHIVED/
NO NOT ACHIVED
Prepareaquestionnaire(closedend)containing25 questions for a
1 specified problem statement: for example
experience of an individual in a restaurant.
Prepare a Google form for a specified problem statement to collect the
2 dataset. (for example questionnaire to
conduct online quiz)
Sendoutasurvey onyour problem statementto number of 50
3 (By Google forms) and collect the data.

Remove duplicate or irrelevant observations. Remove unwanted


observations from the dataset provided, including duplicate
4
observations or irrelevant
observations.
In Microsoft Excel spread sheet draw the frequency
5 distribution table for the given data (data set should contain
minimum 50 data).
In Microsoft Excel spread sheet drawtherelative frequency
6 distribution table for the given data (data set should contain
minimum 50 data).
Using Microsoft Excel spread sheet plot bar graph for the data collected
from 100 people( for example, conduct a survey on the favorite fruit
7 of a person in your locality(restricting to 5 to 6 fruits). Explain the bar
graph
with minimum 30 words.
Using Microsoft Excel spread sheet plot pie chart for the data collected
from 50 people( for example, conduct a survey on the smokers with
8
respect to their ages in your
locality.Explainthepiechartwithminimum30words.
Using Microsoft Excel spread sheet draw a line graph for the given
9
dataset.
Using Microsoft Excel spread sheet draw frequency polygonand
frequency curveforthe datacollectedfrom 50 people. (For example,
marks obtained by the students inyourclassin5subjectsinprevious
10
examination).
Explain your observations from the graph in minimum 30
words.
Using Microsoft Excel spread sheet construct a box plot for the given
dataset. (For example dataset can be the number of passengers in a flat
11
form at different time in a
day).
UsingMicrosoftExcelspreadsheet construct a leaf plot for the given
12 dataset. Explain the graph with minimum 30
words.
Using Microsoft Excel spread sheet find the Mean, Mode and Median for the
13 data (univariate data) given and also
represent them in a Histogram.
Generate a 50 random data sample (even and odd
14 number dataset) using Microsoft Excel spread sheet and determine
the range and Quartiles.
Collectthecurrent yieldofacropfrom50different persons (problem
statement can be changed according to priorities of the tutor) in your
locality and determine mean deviation and Quartile deviation in
15
Microsoft excel spread sheet and brief your inference with less
than 30 words.

Collect the data of any 2 livestock population from 50 different houses in


your locality (problem statement can be changed according to priorities of
the tutor) and determine standard deviation for both the two
16
separately in Microsoft excel spread sheet and brief
your inference with less than 30 words.

Collect the data of two wheeler (with a rider and a pillion) crossing a
busy junction in your locality in the peak hours (problem statement
can be changed according to priorities of the tutor) and determine the
17
variance of the data in Microsoft excel spread sheet and
brief your inference with less than 30 words.

Using Microsoft Excel spread sheet draw a Skewness graph and


18 kurtosis graph for randomly generated dataset.
Write a pythonprogram to add 2 integers and 2 strings and print the
20
result.
Write a python program to find the sum of first 10 natural
21
numbers.
Write a python program to find whether the number is odd or even.
22
Write a pythonprogram to find the variance and standard
23
deviation for the given data..
Writea pythonprogram to displaystudent marksfrom the record.
24
Writeapythonprogramtocreatealabeledbargraph using matpoltlib.
25
pyplot.
Writeapythonprogramtocreatealabeledpiechart
26 using matpoltlib. pyplot.

Student sign Staff incharge sign


UNIT 1

STATISTICAL DATA COLLECTION AND TYPES

Data is a collection of information gathered by observations, measurements, research or


analysis.
Purpose :-
• to find a solution to the research problem.
• to conclude an answer to the relevant question
• to make assumptions about future probabilities and trends.
• used for a specific purpose such as a survey or analysis.
Classification of Data
It is divided into two categories namely,
• Primary Data or primary data collection methods
• Secondary Data or Secondary data collection methods

Primary data or raw data is a type of information that is obtained directly from the first-
hand source through experiments, surveys, or observations.
The primary data is further classified into two types, They are
• Qualitative Data
• Quantitative Data

If the data is classified on the basis of the qualitative characteristics or attributes is

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 1


called qualitative data.
It does not involve any mathematical calculations. This includes interviews,
questionnaires, observations, case studies survey focus group discussion etc.
Data collection tools
There are several methods to collect this type of data. They are also called data
collection tools.
1. Questionnaires
2. Survey
3. Interviews
4. Focus group discussion.
Questionnaires
This is the process of collecting data through an instrument consisting of a series of
questions and prompts to receive a response from individuals
The following features:
• Short and simple
• Should follow a logical sequence
• Provide adequate space for answers
• Avoid technical terms
• Should have good physical appearance such as colour, quality of the paper to attract the
attention of the respondent
Survey
A survey is a process of data gathering involving a variety of data collection methods,
including a questionnaire.
Questionnaires are a list of questions either an open ended (Questions in which the
respondent answers in his own words or close - ended (Question in which respondent selects
one or more options from pre-determined set of responses for which the respondent give
answers).
Enumerator goes to the respondents, asks them the questions from the Performa in the
order listed, and records the responses in the space provided Questionnaire is the most
commonly used method in survey.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 2


Interviews
The Interview Method of collecting data involves presentation of oral-verbal stimuli and
reply in terms of oral – verbal responses.
It is achieved in two ways, such as
• Personal Interview – In this method, a person known as an interviewer is required to ask
questions face to face to the other person.
• Telephonic Interview – In this method, an interviewer obtains information by contacting
people on the telephone to ask the questions or views orally.

Focus group discussion


The opposite of quantitative research which involves numerical based data, this data
collection method focuses more on qualitative research. This research involves asking open-
ended questions to a group of individuals usually ranging from 6-10 people, to provide
feedback.

Quantitative Data:
These can be measured and not simply observed. They can be numerically represented and
calculations can be performed on them.
It is also known as numerical data which represents the numerical value i.e., how much, how
often, how many.
It is based on mathematical calculations using various formats like close ended
questions, correlation and regression methods, mean, median or mode measures.
This method is cheaper than qualitative data collection methods.
This can be classified as quantitative.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 3


➢ Discrete Data
These are data that can take only certain specific values rather than a range of
values. Discrete information contains only a finite number of possible values.
These can represented using charts.
Example: data on the blood group of a certain population.
➢ Continuous Data:
It has an infinite number of probable values that can be selected within a given
specific range.
Example: Temperature range, the height and weights of the students of your school.

Continuous data can be tabulated in what is called a frequency distribution. They


can be graphically represented using histograms.

Secondary data is data is the data which has been already collected and analysed by
someone other than the actual user.
The secondary data includes magazines, newspapers, books, journals etc.
Example: Government publications ,Historical and statistical documents, Business

documents, Technical and trade journals, Diaries • Letters • Unpublished


biographies etc.

EXPERIMENT -1
AIM: To prepare a close/open ended hand written questionnaire containing 25 questions.
PURPOSE: A questionnaire can be helpful for collecting data and analyse it.
STRUCTURE:
• • Interpretation of the language should be same for all the questions. It means language should be
concise.

• Language should be clear and straight forward.

• Questions should not be long, as it bores the respondents.

• Avoid phrases and expressions that are abstract.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 4


• Questions and statements of leading character-ones that put replies into the mouth of the respondent should
be guarded against.

• Units of questions should be precisely stated or defined in order to ensure proper orientation of respondent.

• Subjective words such as ‘bad’, ‘good’, ‘fair’ and the like do not lend themselves either to quantitative or
qualitative and as such should be avoided.

• No single question should deal with more than one issue and as such the principle of one question, one
issue should be followed.

• Vocabulary employed in the questions should be appropriate to the background of the respondents.

• Questions should be so worded that ego of the respondents is not injured in any way.

• Complex questions that require the respondent to go through several steps of reasoning before answering
are undesirable and as such should be avoided.

• Questions on controversial issues should be broken down into components.

TOPIC:
1)

2)

3)

4)

5)

6)

7)

8)

9)

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 5


10)

11)

12)

13)

14)

15)

16)

17)

18)

19)

20)

21)

22)

23)

24)

25)

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 6


EXPERIMENT -2
AIM: To transform a questionnaire into a Google form for a well-defined problem statement.
PURPOSE: A questionnaire in the form of Google forms helps to gather data by online survey.
STEPS INVOVLED: The reference questionnaire in experiment 1 is taken to be transformed into Google
form. The following are the steps involved in creating the Google form.
• Login into your email
• Click on Google apps icon
• Click on My Drive
• Click on New
• Click on Google forms for a blank form
• Enter the title and form description
• Start entering the closed ended questions

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 7


178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 8
EXPERIMENT -3
AIM: Send out a survey for a well-defined problem statement and collect the dataset in the spreadsheet
(.csv file)
PURPOSE: Data in spreadsheet (.csv file) is very useful to analyze the dataset and interpretation.
STEPS INVOVLED: The reference questionnaire in experiment 1 is taken to be transformed into Google
form and sent for online survey. The following are the steps involved in sending Google forms for online
survey and download the responses in spreadsheet (.csv file).
• Gather the email ID’s of the respondents

• Click on the send, enter the recipient’s email ID, click on dialogue box and send.

➢ Click on responses and download the .csv file

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 9


It is the process of detecting and correcting corrupt or inaccurate records from a
record set, table, or database and refers to identifying incomplete, incorrect, inaccurate or
irrelevant parts of the data and then replacing, modifying, or deleting the dirty or coarse data.

1) Using the PROPER function in Excel, text is arrange for proper


The code executes this task. Is =PROPER(CELL)

2) Using the TRIM function in Excel the data in a column can be arranged according to one’s priority and
remove unwanted space between words

The code executes this task. Is =TRIM(CELL)

3) The logical test (IF) is used to fill the missing values in those cells.

The code below executes this task.

=IF(logical_test, [value_if_true], [value_if_false])

4) Duplicate values happen when the same value or set of values appear in the data.

The following are the steps involved in removing duplicates in the data set.

Select the entire data vertically and horizontally as well

Click on DATA tab, Then click on remove duplicates button

5) To remove blanks

Select Data, HOME > FIND&SELECT > GO TO SPECIAL > BLANK

6) To replace unwanted data in huge way is

Select Data, HOME > FIND&SELECT > REPLACE > FIND AND REPLACE > REPLACE ALL

7) To arrange number in Ascending or Descending order or Sort text in A-Z or Z-A

Select Data, HOME > SORT & FILTER …

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 10


EXPERIMENT - 4
AIM: Remove unwanted observations from the dataset (spreadsheet) provided, including duplicate
observations or irrelevant observations.
PURPOSE: Data cleaning is very important process in maintaining the quality of the dataset and conduct an
efficient hypothesis testing.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 11


UNIT 2

SUMMARIZATION OF DATA
Statistics have majorly categorized into two types:

1. Descriptive statistics

2. Inferential statistics

Descriptive statistics is a way to organize, represent and describe a collection


of data using tables, graphs, and summary measures.

Data tabulation
Tabulation is a process of systematic arrangement of the classified data in
rows and columns, in the form of table.

The frequency ( f ) of a particular data value is the number of times the


data value occurs.

A frequency table is constructed by arranging collected data values in


Ascending order of magnitude with their corresponding frequencies.

In general
We use the following steps to construct a frequency table:
Step 1:
Construct a table with three columns. Then in the first column, write
down all of the data values in ascending order of magnitude.
Step 2:
To complete the second column, go through the list of data values and
place one tally mark at the appropriate place in the second column for every data
value.
Step 3:
Count the number of tally marks for each data value and write it
in the third column.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 12


Example

The marks awarded for an assignment set for a Year 8 class of 20


students were as follows:
6 7 5 7 7 8 7 6 9 7
4 10 6 8 8 9 5 6 4 8
The finished frequency table is as follows:

Class Intervals (or Groups)

When the set of data values are spread out, it is difficult to set up a
frequency table. So we group the data into class intervals (or groups) to help us
organize, interpret and analyze the data.

Ideally, we should have between five and ten rows in a frequency table.

Example: The number of calls from motorists per day for roadside service was
recorded for the month of December 2003. The results were as follows:

Set up a frequency table for this set of data values.

Solution:To construct a frequency table, we proceed as follows:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 13


Step 1: Construct a table with three columns, and then write the data groups
or class intervals in the first column.

Step 2: Go through the list of data values. Place a tally mark against the
corresponding class interval in the second column.

Step 3: Count the number of tally marks for each group and write it in the
third column.

The finished frequency table is as follows:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 14


EXPERIMENT -5
AIM: In Microsoft Excel spread sheet draw the frequency distribution table for the given data
(data set should contain minimum 50 data).
PURPOSE: Tabulation makes the data brief. Therefore, it can be easily presented in the form
of graphs.

The data set consists of 50 student marks in Mathematics in a class. Marks Scored

Using COUNTIFS function the data can tabulated.


Enter the code =COUNTIFS(A3:A52,">=1",A3:A52,"<=5") and press enter as shown in the
figure below

Similarly this can be done with other ranges also.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 15


The final frequency distribution table is as shown.

SCORE RANGE FREQUENCY

TOTAL

Relative frequency distribution


A relative frequency distribution is a type of frequency distribution want to know
the percentages.

How you do this:

1. Count the total number of items. In this chart the total is 40.

2. Divide the count (the frequency) by the total number.

For example, 1/40 = 0.025 or 3/40= 0.075 and so on…

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 16


. EXPERIMENT -6
AIM: To prepare Microsoft excel spread sheet to draw the relative frequency distribution table for the data.
PURPOSE: The data in excel spread sheet will be helpful for collecting data set and finding relative
frequency distribution in charts.
STEPS INVOLVED:
Step1: Tabulate the data which has been gathered.
Step2: Divide frequency of each range by total to determine relative frequency

SCORE RANGE FREQUENCY Relative Frequency

INTERFACE:

Cumulative Relative Frequency

To find the cumulative relative frequency, follow the steps above to create a
relative frequency distribution table. As a final step, add up the relative
frequencies in another column.

Steps with Example

The first entry in the column is the same as the first entry in the rel.freq column (0.29).

Next, I added the first and second entries to get 0.29 + 0.50 = 0.79.

Next, I added the first, second and third entries to get 0.29 + 0.50 + 0.14 = 0.93.

Finally, I added the first, second, third and fourth entries to get 0.29 + 0.50 + 0.14 + 0.07 = 1

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 17


SCORE FREQUENCY Relative Cummulative
RANGE Frequency Frequency

The pictorial representations of a grouped data, in the form of vertical or


horizontal rectangular bars, where the lengths of the bars are equivalent to the measure of
data, are known as bar graphs or bar charts.

The bars drawn are of uniform width, and the variable quantity is represented on one of
the axes. The number of values on the x-axis of a bar graph or the y-axis of a column
graph is called the scale.

It is used to compare and understanding certain quantities.

The frequency distribution tables can be easily represented using bar charts which
simplify the calculations of data.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 18


Types of Bar Charts

The types of bar charts are as follows:

1. Vertical bar chart

2. Horizontal bar chart

Vertical Bar Graphs

When the grouped data are represented vertically in a graph or chart with the help
of bars.

The data is represented along the y-axis of the graph, and the height of the bars
shows the values.

Horizontal Bar Graphs

When the grouped data are represented horizontally in a chart with the help of
bars.

The data is depicted here along the x-axis of the graph, and the length of the
bars denote the values.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 19


Note:

Apart from the vertical and horizontal bar graph, the two different types of bar charts are

• Grouped Bar Graph


• Stacked Bar Graph
Grouped Bar Graph

Grouped bar graph is also called the clustered bar graph, which is used to represent the
discrete value for more than one object that shares the same category.

Stacked Bar Graph

Stacked bar graph is also called the composite bar chart, which divides the
aggregate into different parts. In this type of bar graph, each part can be
represented using different colors.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 20


Uses of Bar Graphs
Bar graphs are used to match things between different groups or to trace changes over
time. Yet, when trying to estimate change over time, bar graphs are most suitable when
the changes are bigger.

Bar charts possess a discrete domain of divisions and are normally scaled so that all the
data can fit on the graph. When there is no regular order of the divisions being matched,
bars on the chart may be organized in any order. Bar charts organized from the highest to
the lowest number are called Pareto charts.

EXPERIMENT -7
AIM: To conduct survey on favorite fruit of 100 persons using excel spread sheet and to plot bar graph for
the collected data.
PURPOSE: Bar graphs have been in widespread use everywhere from textbooks to newspapers, most
audiences understand how to read a bar graph and can grasp the information the graph conveys.
STEPS INVOLVED:
Step1: Tabulate the data collected.
Step2: Select the entire tabulated data as shown in the figure. Using formula
=COUNTIF(RANGE,”FRUIT”) and similarly for other fruits
Step 3: Click on insert tab > chart : Modify the chart by adding tittle name, axis tittles and format data labels.

Survey on favorite fruits of a


person
25 23
19 18 18
20
Cont of fruits

15 12
10
10
5
0
apple orrange banana sapota grapes kiwi
Fruits

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 21


The “pie chart” also is known as “circle chart”, that
divides the circular statistical graphic into sectors or slices in order to
illustrate the numerical problems. Each sector denotes a proportionate part
of the whole. To find out the composition of something, Pie-chart works
the best at that time. In most of the cases, pie charts replace some other
graphs like the bar graph, line plots, histograms etc.

Formula

Each segment and sectors of a pie chart forms all the data is equal to 360°.

The total value of the pie is always 100%.

To work out with the percentage for a pie chart, follow the steps given below:

• Categorize the data


• Calculate the total
• Divide the categories
• Convert into percentages
Finally, calculate the degrees Therefore, the pie chart formula is given as
(Given Data/Total value of Data) × 360°
How to Create a Pie Chart?

Imagine a teacher surveys her class on the basis of their favourite Sports:

Football Hockey Cricket Basketball Badminton


10 5 5 10 10
The data above can be represented by a pie-chart as following and by
using the circle graph formula, i.e. the pie chart formula given below.
It makes the size of portion easy to understand.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 22


Step 1: First, Enter the data into the table.

Football Hockey Cricket Basketball Badminton

10 5 5 10 10
Step 2: Add all the values in the table to get the total.

I.e. Total students are 40 in this case.

Step 3: Next, divide each value by the total and multiply by 100 to get a per cent:

Football Hockey Cricket Basketball Badmint on

(10/40) × 100 (5/ 40) × 100 (5/40) ×100 (10/ 40)×100 (10/40)×
=25% =12.5% =12.5% =25% 100
=25%

Step 4: Next to know how many degrees for each “pie sector” we need, we will take a
full circle of 360° and follow the calculations below:

The central angle of each component = (Value of each component/sum of values of all the
components)✕360°

Football Hockey Cricket Basketball Badminton

(10/ 40)× 360° (5 / 40) × 360° (5/40) × 360° (10/ 40)× 360° (10/ 40) × 360°
=90° =45° =45° =90° =90°
Now you can draw a pie chart.

Step 5: Draw a circle and use the protractor to measure the degree of each sector.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 23


EXPERIMENT - 8
AIM: Using Microsoft Excel spread sheet plot pie chart for the data collected from 50 people
( for example, conduct a survey on the smokers with respect to their ages in your locality.
PURPOSE: A pie chart presents data as a simple and easy-to-understand picture. It can be an effective
communication tool for even an uninformed audience, because it represents data visually as a fractional
part of a whole. Readers or audiences see a data comparison at a glance, enabling them to make an
immediate analysis or to understand information quickly.
STEPS INVOLVED:
Step1: Tabulate the collected data as shown below.
Step2: Select the entire tabulated data and Click on insert >> pie-chart.
Step3: Select pie chart of your choice and label the chart.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 24


A line graph shows how values change.

Line graphs can also be used to show how functions change.

A function is just an equation that gives you a unique output for every input. For
Example: y = – 4/5x + 3 is a function because you’ll get a unique value for

y when you put in any number for x.

The most usual type of data you’ll find on a line graph is how something
changes over time. A line graph that shows changes over time is sometimes
called a Timeplot.

A Dow Jones Timeplot from the Wall Street Journal shows how the
stock market changes over time.

Why use a Line Graph?

• You have a function. Line graphs are good at showing specific data values, meaning
that if you have one variable (x) you can easily find the other (y).
• You want to show trends. For example, how your investments change over time or
how food prices have increased over time.
• You want to make predictions. A line graph can be extrapolated beyond the
data at hand. They enable you to make predictions about the results of data.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 25


EXPERIMENT - 9
AIM: Using Microsoft Excel spread sheet draw a line graph for the given dataset.

PURPOSE: A line graph, also known as a line chart, is a type of chart used to visualize the
value of something over time.

STEPS INVOLVED:

Step 1: Put each category and the associated value on one line

Step 2: Add projected sales along with actual sales here

Step 3: highlight the data you want in the graph

Step 4: Then, open the Insert tab in the Ribbon. In the Charts group, click the Insert Line or
Area Chart Button:

Step 5: From the resulting menu, click the 2D line button:

Step 6: line graph will appear

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 26


A frequency polygon is almost identical to a histogram, which is used to
compare sets of data or to display a cumulative frequency distribution. It uses a line graph
to represent quantitative data.

Frequency polygons are a visually substantial method of representing


quantitative data and its frequencies. Let us discuss how to represent a frequency polygon.

Steps to Draw Frequency Polygon

To draw frequency polygons, first we need to draw histogram and


then follow the below steps:

Step 1- Choose the class interval and mark the values on the horizontal axes

Step 2- Mark the mid value of each interval on the horizontal axes.

Step 3- Mark the frequency of the class on the vertical axes.

Step 4- Corresponding to the frequency of each class interval, mark a point

at the height in the middle of the class interval

Step 5- Connect these points using the line segment.

Step 6- The obtained representation is a frequency polygon. Let us consider

an example to understand this in a better way.

Example 1: In a batch of 400 students, the height of students is given in the


following table. Represent it through a frequency polygon.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 27


Solution: Following steps are to be followed to construct a histogram from the
given data:

• The heights are represented on the horizontal axes on a suitable scale as


shown.
• The number of students is represented on the vertical axes on
a suitable scale as shown.
• Now rectangular bars of widths equal to the class- size and
the length of the bars corresponding to a frequency of the
class interval is drawn.
ABCDEF represents the given data graphically in form of frequency polygon as:

Frequency polygons can also be drawn independently without drawing


histograms. For this, the midpoints of the class intervals known as class marks are
used to plot the points.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 28


EXPERIMENT - 10
AIM: To prepare Microsoft excel spread sheet and to draw frequency polygon and
frequency curve for the data.

PURPOSE: Frequency polygons are a graphical device for understanding the shapes
of distributions. They serve the same purpose as histograms, but are especially
helpful for comparing sets of data.

STEPS INVOLVED:

Step1: Tabulate the given data

Step2: Select the entire data, Click on insert tab>>insert bar chart>> click on the bar

graph>> select format data series>> make gap width 0 to obtain the Histogram

Step3: Once the histogram is constructed join the midpoints of each bar by hand,

through a straight line to develop frequency polygon and smooth curve to

develop frequency curve.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 29


A histogram is a plot that show the underlying frequency distribution
(shape) of a set of continuous data.

Notice that, unlike a bar chart, there are no "gaps" between the bars
(although some bars might be "absent" reflecting no frequencies). This is
because a histogram represents a continuous data set, and as such, there
are no gaps in the data (although you will have to decide whether you
round up or round down scores on the boundaries of bins).

To construct a histogram from a continuous variable you first need


to split the data into intervals, called bins.

Choosing the correct bin width There is no right or wrong answer as to how wide a bin

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 30


should be, but there are rules of thumb. You need to make sure that the bins are not too
small or too large. This have either much smaller or larger bins, as shown below:

Histograms are based on area, not height of bars

What is the difference between a bar chart and a histogram?

The major difference is that a histogram is only used to plot the frequency
of score occurrences in a continuous data set that has been divided into
classes, called bins. Bar charts, on the other hand, can be used for a great
deal of other types of variables including ordinal

A boxplot, also called a box and whisker plot, is a way to show the spread
and centers of a data set. Measures of spread include the interquartile
range and the mean of the data set. Measures of center include the mean
or average and median (the middle of a data set).

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 31


The box and whiskers chart shows you how your data is spread out.

Five pieces of information (the “five number summary“) are generally included in
the chart:

• The minimum (the smallest number in the data set). The


minimum is shown at the far left of the chart, at the end of
the left “whisker.”
• First quartile, Q1, is the far left of the box (or the far right of the left
whisker).
• The median is shown as a line in the center of the box.
• Third quartile, Q3, shown at the far right of the box (at the far left of the
right whisker).
• The maximum (the largest number in the data set), shown
at the far right of the box. Back to Top

EXPERIMENT - 11
AIM: To Using Microsoft Excel spread sheet construct a box plot for the given dataset.
PURPOSE: Box plot is usually helpful in explanatory data. It indicates the spread out of data based
on 5 number summary namely minimum, Q1 (Quartile 1), Median, Q3 (Quartile 3), and Maximum.
Sample problem:
Make a box and whiskers chart in Excel for the following data set:
25, 145, 145, 148, 178, 178, 198, 201, 222, 210, 565, 589, 485,
333, 358, 158, 257.
STEPS INVOLVED:
Step 1: Type your data into one column in an Excel worksheet.
For this example, type your data into cells A1:A11.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 32


Step 2: Click an empty cell type “MIN, Q1, MED, Q3 and MAX” in a
single column. In the next column over, type formulas for MIN, Q1, MED
and MAX. The formulas are:
Minimum =MIN(A1:A17)

Q1 =QUARTILE(A1:A17,1)

Median or Q2 =MED(A1:A17)

Q3 =QUARTILE(A1:A17,3)

Maximum = MAX(A1:A17)

Step 3: Subtract each value in the previous column from


the next value. In other words, subtract the Min from Q1, the
Q1 from the Med, the Med from Q3 and Q3 from the Max.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 33


Step 4: Highlight the column of differences you calculated in
Step 3, then click “Insert,” then click “Bar” and then click
“Stacked Bar.”

Step 5: Click the graph and then click the “Switch Row/Column” button.

Step 6: Select the left-hand blue box, right-click and then click
“Format Data Series.”

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 34


Step 7: Click “Fill,” then click the “No Fill” radio button and then click
“Close.”
Step 8: Add the whisker to the left-hand side using the following method:
1. Click the left-hand red box.

2. Select the “Layout” tab, then click “Error Bars“. Next, click “More

Error Bar Options.”


3. Click “Error Bars with Standard Error.”

4. Select the “Layout” tab again, then click “Error Bars”

and then click “More Error Bar Options.”


5. Click “Mins” and then type the difference between

Q1 and the Min into the “Fixed Value” box. For this
sample problem, that value is 133.
6. Click “Close.”

7. Remove the red color (fill) using the technique

outlined in Steps 7 and 8 above.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 35


*A stem-and-leaf display (also known as a stemplot) is a diagram designed
to allow you to quickly assess the distribution of a given dataset. Basically,
the plot splits two-digit numbers in half:

Example:32 is split into 3 (stem) and 2 (leaf).


Stems – The first digit
Leaves – The second
digit

EXPERIMENT - 12
AIM: Using Microsoft Excel spread sheet construct a stem and leaf plot for the given dataset.
PURPOSE: A stem-and-leaf display (also known as a stemplot) is a diagram designed to allow you
to quickly assess the distribution of a given dataset. It indicates the recurrence of data.
STEPS INVOLVED:

Use the following steps to create a stem-and-leaf plot in Excel.

Step 1: Enter the data.


Enter the data values in a single column:

Step 2: Identify the minimum and maximum values.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 36


Step 3: Manually enter the “stems” based on the minimum and maximum

values.

Step 4: Calculate the “leaves” for the first row.


The following calculation shows how to compute the leaves for the
first row. Don’t be intimidated by the length of the formula – it’s
actually very simple, just repetitive.

Once you finish typing the formula and click Enter, you will get the following result:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 37


Step 5: Repeat the calculation for each row.
To repeat this calculation for each row, simply click on cell D7, hover over
the bottom-right hand corner of the cell until a tiny + appears, then double-
click. This will copy the formula to the rest of the rows in the Stem-and-
Leaf plot:

To double check that your results are correct, you can verify three numbers:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 38


UNIT-3,

MEASURE OF LOCATION AND DISPERSION

Central tendency refers to the centre of the distribution of the data and
which generally can be described using different measures like mean,
median and the mode.

Based on the properties of the data, the measures of central tendency are
selected.

The mean represents the average value of the dataset. It can be calculated as the
sum of all the values in the dataset divided by the number of values

Median is the middle value of the dataset in which the dataset is arranged in the
ascending order or in descending order.

➢ When the dataset contains an even number of values, then the median value
of the dataset can be found by taking the mean of the middle two values.

• Consider the given dataset with the odd nmber of observations arranged in
descending order –23, 21, 18, 16, 15, 13, 12, 10, 9, 7, 6, 5, and 2

Here 12 is the middle or median number that has 6 values above

it and 6 values below it.

• Now, consider another example with an even number of observations that


are arranged in descending order – 40, 38, 35, 33, 32, 30, 29, 27, 26, 24, 23,
22, 19,and 17

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 39


When you look at the given dataset, the two middle values obtained are

27 and 29.
Now, find out the mean value for these two numbers.
i.e.,(27+29)/2 =28

Therefore, the median for the given data distribution is 28.

The mode represents the frequently occurring value in the dataset. Sometimes the
dataset may contain multiple modes and in some cases, it does not contain any
mode at all.

➢ Consider the given dataset 5, 4, 2, 3, 2, 1, 5, 4, 5

Since the mode represents the most common value. Hence, the most frequently repeated
value in the given dataset is 5.

Definition: The difference between the lowest and highest values.

• In {4, 6, 9, 3, 7} the lowest value is 3, and the highest is 9,

so the range is 9 − 3 = 6.

EXPERIMENT - 13
AIM: Using Microsoft Excel spread sheet find the Mean, Mode and Median for the data (univariate data)
given and also represent them in a Histogram.
PURPOSE: The central tendencies Mean, Mode and Median help us understand that has already taken
place and predict future values as well.
STEPS INVOLVED:
Step 1: Tabulate the collected data as shown below

Step 2: Select the data and enter the syntax for Mean, Mode and Median

Step 3: Press enter to obtain the Mean or Average, Mode and Median

Step 4: Plot the Histogram with the instruction given in previous examples.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 40


EXPERIMENT - 14
AIM: To generate a 50 random data sample (even and odd number dataset) using Microsoft Excel
spread sheet and determine the Range and Quartiles.
PURPOSE: The quartiles are especially useful when working with data that isn't symmetrically
distributed, or a data set that has outliers.
STEPS INVOLVED:

Step 1: Consider the odd number and even number data set as shown below

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 41


Step 2: To obtain the quartiles the syntax are as follows: range and interquartile range to be found
using the formula: Maximum-Minimum and Q3-Q1.

Step 3: The end result obtained is

Same instructions to be followed for odd number set.

The Mean Deviation is defined as the arithmetic mean of the deviations


measured either from mean or from the median. All these deviations are
counted as positive to avoid the difficulty arising from the property that the sum
of deviations of observations from their mean is zero.

Quartile deviation defined as the difference between the third and first quartiles,
and half of this range is called the semi-interquartile range (SIQD) or

simply quartile deviation


𝑄3 −𝑄1
QD = 2

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 42


EXPERIMENT - 15
AIM: To determine the mean deviation and quartile deviation for the data collected.
PURPOSE: The Mean deviation is an important descriptive statistic that is not frequently
encountered in mathematical statistics. This is essentially because while mean deviation has a natural
intuitive definition as the "mean deviation from the mean," the introduction of the absolute value
makes analytical calculations using this statistic much more complicated than the standard deviation
STEPS INVOLVED:
Step 1: Find the mean of the data collected as shown in the figure below
Step 2: Determine the elements of the new columns as shown below

Step 3: The average of the absolute values is determined. This value is called Mean deviation.

Step 4 : Quartile Deviation:the quartiles Q1 and Q3 are found with which the Quartile deviation
QD=(Q3-Q1)/2 is found

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 43


It is a measure of the amount of variation or dispersion of a set of values.
A low standard deviation indicates that the values tend to be close to the mean
(also called the expected value) of the set, while a high standard deviation
indicates that the values are spread out over a wider range.
To calculate the standard deviation of numbers:
1. Work out the Mean (the simple average of the numbers)
2. Then for each number: subtract the Mean and square the result.
3. Then work out the mean of those squared differences.
4. Take the square root of that and we are done!

Standered deviation in excel use =STDEV( )

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 44


EXPERIMENT - 16
AIM: To determine the standard deviation for the data collected in Excel.
PURPOSE: SD tells us about the shape of our distribution, how close the individual data values are
from the mean value.
STEPS INVOLVED:
Step 1: Select the data gathered for 2 livestock as shown below
Step 2: Type the syntax for standard deviation =STDEV( )and determine the same

To calculate standard deviation in excel we use STDEV function. In the


same example we shall use the STDEV function so our formula will be
=STDEV(B2:B12).

INFERENCE: Our answer is around 20 which indicates that the marks of


the students fluctuates a lot.

The standard deviation is a more complicated measure of absolute


dispersion, you could calculate it by squaring the difference between each
data point and the mean, summing those squares, dividing by a number that
is one less than the number of your data points, and then taking the square
root of that. Since your values are squared and in the end the square root is
taken again, the standard deviation is given in the your original units of
measure.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 45


Variance is one of the most useful tools in probability theory and
statistics. In science, it describes how far each number in the data set is
from the mean. In. How to find Variance in Excel?

This is complete data. When we capture complete data (entire population)


we calculate the variance of population. The Excel function for calculating
Variance of population is VAR.P. The syntax of VAR.P is

=VAR.P(number1,NUMBER2)

EXPERIMENT - 17
AIM: To determine the variance for the data collected.
PURPOSE: SD and variance tells us about the shape of our distribution, how close the
individual data values are from the mean value.
STEPS INVOLVED:
Step 1: Let's use this =VAR.P(number1,NUMBER2)formula to calculate the variance of our data.
Step 2 : We have data in cell C2:C15. So the formula will be:

INFERENCE: This returns a value 186.4285714, which is quite a large variance given our data

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 46


If one tail is longer than another, the distribution is skewed. These
distributions are sometimes called asymmetric or asymmetrical distributions
as they don’t show any kind of symmetry.
For example, the normal distribution is a symmetric distribution with no
skew. The tails are exactly the same.
There are two types of Skewness: Positive and Negative

Positive Skewness means when the tail on the right side of the distribution
is longer or fatter. The mean and median will be greater than the mode.

Negative Skewness is when the tail of the left side of the distribution is
longer or fatter than the tail on the right side. The mean and median will
be less than the mode.

So, when is the skewness too much? The rule of thumb seems to be:

• If the skewness is between -0.5 and 0.5, the data are fairly symmetrical.
• If the skewness is between -1 and -0.5(negatively skewed) or
between 0.5 and 1(positively skewed), the data are moderately
skewed.
• If the skewness is less than -1(negatively skewed) or greater
than 1(positively skewed), the data are highly skewed.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 47


Kurtosis is all about the tails of the distribution — not the peakedness or
flatness. It is used to describe the extreme values in one versus the other
tail. It is actually the measure of outliers present in the distribution.

High kurtosis in a data set is an indicator that data has heavy tails or
outliers. If there is a high kurtosis, then, we need to investigate why do we
have so many outliers. It indicates a lot of things, maybe wrong data entry
or other things. Investigate!

Low kurtosis in a data set is an indicator that data has light tails or lack of
outliers. If we get low kurtosis(too good to be true), then also we need to
investigate and trim the dataset of unwanted results.

Mesokurtic(Kurtosis =3): This distribution has kurtosis statistic similar to


that of the normal distribution. It means that the extreme values of the
distribution are similar to that of a normal distribution characteristic.
Leptokurtic (Kurtosis > 3): Distribution is longer, tails are fatter. Peak is
higher and sharper than Mesokurtic, which means that data are heavy-tailed
or profusion of outliers.
Platykurtic: (Kurtosis < 3): Distribution is shorter, tails are thinner than
the normal distribution. The peak is lower and broader than Mesokurtic,
which means that data are light- tailed or lack of outliers.
The reason for this is because the extreme values are less than that of the normal
distribution.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 48


EXPERIMENT - 18
AIM: Using Microsoft Excel spread sheet draw a Skewness graph and Kurtosis graph for randomly
generated dataset.
PURPOSE: Skewness and kurtosis is useful in finding the symmetry and peakedness of the data
distribution.
STEPS INVOLVED:
Step 1: For the collected data determine the mean and mode
Step 2: Draw the line graph
Step 3: In the graph, mark the mean and median and claim the negativeness and positiveness of the
graph.
(If the mean appears before the median then declare that the data is negatively skewed and positively
skewed otherwise)

Step 4: To determine the kurtosis enter the syntax (KURT(number1, number2..))

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 49


UNIT 4

INTRODUCTION TO PYTHON PROGRAMMING

Python is a popular programming language. It was created by Guido van Rossum,


and released in 1991.

It is used for:

• web development (server-side),


• software development, system scripting.
• mathematics,

• Python can be used on a server to create web applications.


• Python can connect to database systems. It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics..

• Python works on different platforms (Windows, Mac, Linux, etc).


• Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines
than some other programming languages.

• Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
• Python uses new lines to complete a command, as opposed to other
programming languages which often use semicolons or parentheses.
• Python relies on indentation, using whitespace, to define scope; such as the
scope of loops, functions and classes. Other programming languages often
use curly-brackets for this purpose.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 50


Python syntax can be executed by writing directly in the Command Line:

>>> print("Hello, World!")


Hello, World!

Indentation refers to the spaces at the beginning of a code line.

Where in other programming languages the indentation in code is for readability


only, the indentation in Python is very important.

Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")
OUTPUT:Five is greater than two!

2) Python will give you an error if you skip the indentation:

Syntax Error:

if 5 > 2:
print("Five is greater than two!")

File "demo_indentation_test.py", line 2


print("Five is greater than two!")
^
IndentationError: expected an indented block

3) The number of spaces is up to you as a programmer, but it has to be at least


one.

if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")

Five is greater than two!


Five is greater than two!

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 51


Python has commenting capability for the purpose of in-code documentation.

Comments start with a #, and Python will render the rest of the line as a comment:

Comments starts with a #, and Python will ignore them:

Example
#This is a comment
print("Hello, World!") Hello, World!

print("Hello, World!") Hello, World!

#print("Hello, World!")
print("Cheers, Mate!") Hello, World!

Python does not really have a syntax for multi line comments.

To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!") Hello, World!

Since Python will ignore string literals that are not assigned to a variable, you can
add a multiline string (triple quotes) in your code, and place your comment inside
it:

"""
This is a comment
written in
more than just one line
"""
print("Hello, World!") Hello, World!

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 52


Text Type: str

Numeric Types: int, float, complex

Sequence Types: list, tuple, range

Mapping Type: dict

Set Types: set, frozenset

Boolean Type: bool

Binary Types: bytes, bytearray, memoryview

You can get the data type of any object by using the type() function:

Example
Print the data type of the variable x:

x = 5
print(type(x)) <class 'int'>

Setting the Data Type

In Python, the data type is set when you assign a value to a variable:

Example Data Type OUTPUT

x = "Hello World" str


<class 'str'>

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 53


x = 20 int
<class 'int'>

x = 20.5 float <class 'float'>

x = 1j complex <class 'complex'>

x = ["apple", "banana", "cherry"] list <class 'list'>

x = ("apple", "banana", "cherry") tuple <class 'tuple'>

x = range(6) range range(0, 6)


<class 'range'>

In Python, variables are created when you assign a value to it:

Python has no command for declaring a variable.

Variables are containers for storing data values.

Example
Variables in Python:

x = 5
y = "Hello, World!"

A variable is created the moment you first assign a value to it.

Example
x = 5
y = "John"

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 54


print(x)
print(y)
5
John

Variables do not need to be declared with any particular type, and can even change
type after they have been set.

x = 4 # x is of type int
x = "Sally" # x is now of type str
print(x) Sally

If you want to specify the data type of a variable, this can be done with casting.

Example
x = str(3) 3
y = int(3) 3
z = float(3) 3.0

You can get the data type of a variable with the type() function.

Example
x = 5
y = "John"
print(type(x))
print(type(y)) <class 'int'>
<class 'str'>

String variables can be declared either by using single or double quotes:

Example
x = "John" John
# is the same as
x = 'John' John

Variable names are case-sensitive.

Example
This will create two variables:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 55


a = 4
A = "Sally"

4
Sally

Python supports the usual logical conditions from mathematics:

• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements"
and loops.

An is written by using the if keyword.

Example
If statement:

a = 33
b = 200
if b > a:
print("b is greater than a") b is greater than a

In this example we use two variables, a and b, which are used as part of the if
statement to test whether b is greater than a. As a is 33, and b is 200, we know
that 200 is greater than 33, and so we print to screen that "b is greater than a".

The elif keyword is pythons way of saying "if the previous conditions were not true, then try this
condition".

Example
a = 33
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal") a and b are equal

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 56


In this example a is equal to b, so the first condition is not true, but
the elif condition is true, so we print to screen that "a and b are equal".

The else keyword catches anything which isn't caught by the preceding conditions.

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b") a is greater than b

In this example a is greater than b, so the first condition is not true, also
the elif condition is not true, so we go to the else condition and print to screen
that "a is greater than b".

You can also have an else without the elif:

Example
a = 200
b = 33
if b > a:
print("b is greater than a")
else:
print("b is not greater than a") b is not greater than a

If you have only one statement to execute, you can put it on the same line as the if
statement.

Example
One line if statement:

if a > b: print("a is greater than b") "a is greater than b"

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 57


If you have only one statement to execute, one for if, and one for else, you can put
it all on the same line:

Example
One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B") "a is greater than b"

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:

Example
One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B") =

The and keyword is a logical operator, and is used to combine conditional


statements:

Example
Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True") Both conditions are True

The or keyword is a logical operator, and is used to combine conditional


statements:

Example
Test if a is greater than b, OR if a is greater than c:

a = 200

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 58


b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")

At least one of the conditions is True

You can have if statements inside if statements, this is


called nested if statements.

Example
x = 41

if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")

Above ten,
and also above 20!

if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.

Example
a = 33
b = 200
if b > a:
pass
# having an empty if statement like this, would raise an error without the
pass statement

Python has two primitive loop commands:

• while loops
• for loops

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 59


With the while loop we can execute a set of statements as long as a condition is
true.

Example
Print i as long as i is less than 6:

i = 1
while i < 6:
print(i)
i += 1
1
2
3
4
5

Note: remember to increment i, or else the loop will continue forever.

The while loop requires relevant variables to be ready, in this example we need to
define an indexing variable, i, which we set to 1.

With the break statement we can stop the loop even if the while condition is true:

Example
Exit the loop when i is 3:

i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
1
2
3

With the continue statement we can stop the current iteration, and continue with
the next:
Example
Continue to the next iteration if i is 3:
i = 0
while i < 6:
i += 1
if i == 3:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 60


continue
print(i)
1
2
4
5
6
# Note that number 3 is missing in the result

With the else statement we can run a block of code once when the condition no
longer is true:

Example
Print a message once the condition is false:

i = 1
while i < 6:
print(i)
i += 1
else:
print("i is no longer less than 6")

1
2
3
4
5
i is no longer less than 6

A for loop is used for iterating over a sequence (that is either a list, a tuple, a
dictionary, a set, or a string).

This is less like the for keyword in other programming languages, and works more
like an iterator method as found in other object-orientated programming
languages.

With the for loop we can execute a set of statements, once for each item in a list,
tuple, set etc.

Example
Print each fruit in a fruit list:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 61


apple
banana
cherry

The for loop does not require an indexing variable to set beforehand.

With the break statement we can stop the loop before it has looped through all the
items:

Example
Exit the loop when x is "banana":

fruits = ["apple", "banana", "cherry"]


for x in fruits:
print(x)
if x == "banana":
break
Example
Exit the loop when x is "banana", but this time the break comes before the print:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
break
print(x)
apple
banana

With the continue statement we can stop the current iteration of the loop, and
continue with the next:

Example
Do not print banana:

fruits = ["apple", "banana", "cherry"]


for x in fruits:
if x == "banana":
continue
print(x)

apple
cherry

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 62


The else keyword in a for loop specifies a block of code to be executed when the
loop is finished:

Example
Print all numbers from 0 to 5, and print a message when the loop has ended:

for x in range(6):
print(x)
else:
print("Finally finished!")
0
1
2
3
4
5
Finally finished!

A nested loop is a loop inside a loop.

The "inner loop" will be executed one time for each iteration of the "outer loop":

Example
Print each adjective for every fruit:

adj = ["red", "big", "tasty"]


fruits = ["apple", "banana", "cherry"]

for x in adj:
for y in fruits:
print(x, y)

red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 63


Exercise s
Note: Python does not have built-in support for Arrays, but Python Lists can be
used instead.

Note: This page shows you how to use LISTS as ARRAYS, however, to work with
arrays in Python you will have to import a library, like the NumPy library.

Arrays are used to store multiple values in one single variable:

Example
Create an array containing car names:

cars = ["Ford", "Volvo", "BMW"]


['Ford', 'Volvo', 'BMW']

You refer to an array element by referring to the index number.

Example
Get the value of the first array item:

x = cars[0] Ford

Use the len() method to return the length of an array (the number of elements in
an array).

Example
Return the number of elements in the cars array:

x = len(cars) 3

Note: The length of an array is always one more than the highest array index.

You can use the for in loop to loop through all the elements of an array.

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 64


Example
Print each item in the cars array:

for x in cars:
print(x)
Ford
Volvo
BMW

Python has a set of built-in methods that you can use on lists/arrays.

Method Description

append() Adds an element at the end of the list

clear() Removes all the elements from the list

copy() Returns a copy of the list

count() Returns the number of elements with the


specified value

extend() Add the elements of a list (or any iterable), to


the end of the current list

index() Returns the index of the first element with the


specified value

insert() Adds an element at the specified position

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 65


pop() Removes the element at the specified position

remove() Removes the first item with the specified


value

reverse() Reverses the order of the list

sort() Sorts the list

Note: Python does not have built-in support for Arrays, but Python Lists can be
used instead.

A function is a block of code which only runs when it is called.


You can pass data, known as parameters, into a function.
A function can return data as a result.

In Python a function is defined using the def keyword:

To call a function, use the function name followed by parenthesis:

Information can be passed into functions as arguments.

Arguments are specified after the function name, inside the parentheses. You can
add as many arguments as you want, just separate them with a comma.

Arguments are often shortened to args in Python documentations.

To let a function return a value, use the return statement:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 66


function definitions cannot be empty, but if you for some reason have
a function definition with no content, put in the pass statement to avoid getting an
error.

Python also accepts function recursion, which means a defined function can call
itself.

In this example, tri_recursion() is a function that we have defined to call itself


("recurse"). We use the k variable as the data, which decrements (-1) every time
we recurse. The recursion ends when the condition is not greater than 0 (i.e. when
it is 0).To a new developer it can take some time to work out how exactly this
works, best way to find out is by testing and modifying it.

EXPERIMENT 19
AIM: To write a python program to Convert Decimal to Binary, Octal and Hexadecimal.
CODE:

OUTPUT:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 67


EXPERIMENT 20
AIM: To write a python program to add 2 integers and 2 strings and print the result

CODE:

OUTPUT:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 68


EXPERIMENT 21
AIM: To write a python program to find the sum of first 10 natural numbers.

CODE:

OUTPUT:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 69


EXPERIMENT 22
AIM: To write a python program to find whether the number is odd or even.

CODE:

OUTPUT:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 70


EXPERIMENT 23
AIM: To write a python program to find the Mean, Mode, Standard deviation for the given set.
Excel Input

CODE:

OUTPUT:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 71


EXPERIMENT 24
AIM: To write a python program to enter the marks of the student across the subject
CODE:

OUTPUT

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 72


EXPERIMENT 25
AIM: To write a python program to create a labeled bar graph using matpoltlib. pyplot.
CODE:

OUT PUT

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 73


EXPERIMENT 26

AIM: To write a python program to create a labeled pie graph using matpoltlib. pyplot.

CODE:

OUTPUT:

178-GPT RBK BNT SCIENCE DEPT-20SC02P-S&A LAB Page 74

You might also like