Python Lab Latest
Python Lab Latest
Program-
There are 33 keywords in Python 3.7. This number can vary slightly over the course of time.
Python Identifiers
An identifier is a name given to entities like class, functions, variables, etc. It helps to
differentiate one entity from another.
global = 1
Output
global = 1
1
a@ = 0
Output
a@ = 0
In this tutorial, you will learn about Python statements, why indentation is important and use of
comments in programming.
Python Statement
Instructions that a Python interpreter can execute are called statements. For example, a = 1 is
an assignment statement. if statement, for statement, while statement, etc. are other kinds of
statements which will be discussed later.
Multi-line statement
In Python, the end of a statement is marked by a newline character. But we can make a
statement extend over multiple lines with the line continuation character (\). For example:
a=1+2+3+\
4+5+6+\
7+8+9
This is an explicit line continuation. In Python, line continuation is implied inside parentheses ( ),
brackets [ ], and braces { }. For instance, we can implement the above multi-line statement as:
a = (1 + 2 + 3 +
4+5+6+
2
7 + 8 + 9)
Here, the surrounding parentheses ( ) do the line continuation implicitly. Same is the case with [
] and { }. For example:
colors = ['red',
'blue',
'green']
We can also put multiple statements in a single line using semicolons, as follows:
a = 1; b = 2; c = 3
Python Indentation
Most of the programming languages like C, C++, and Java use braces { } to define a block of
code. Python, however, uses indentation.
for i in range(1,11):
print(i)
if i == 5:
break
The enforcement of indentation in Python makes the code look neat and clean. This results in
Python programs that look similar and consistent.
Indentation can be ignored in line continuation, but it's always a good idea to indent. It makes
the code more readable. For example:
if True:
print('Hello')
a=5
and
if True: print('Hello'); a = 5
both are valid and do the same thing, but the former style is clearer.
3
Incorrect indentation will result in IndentationError.
Python Comments
#This is a comment
print('Hello')
Multi-line comments
#and it extends
Another way of doing this is to use triple quotes, either ''' or """.
These triple quotes are generally used for multi-line strings. But they can be used as a multi-line
comment as well. Unless they are not docstrings, they do not generate any extra code.
"""This is also a
perfect example of
multi-line comments"""
4
Program 2- Write programs to understand the use of Python String, Tuple, List, Set, Dictionary,
File input/output.
Program-
Strings in Python
A string is a sequence of characters. It can be declared in python by using double-quotes.
Strings are immutable, i.e., they cannot be changed.
a = "This is a string"
print (a)
Lists in Python
Lists are one of the most powerful tools in python. They are just like the arrays declared in
other languages. But the most powerful thing is that list need not be always homogeneous. A
single list can contain strings, integers, as well as objects. Lists can also be used for
implementing stacks and queues. Lists are mutable, i.e., they can be altered once declared.
Tuples in Python
A tuple is a sequence of immutable Python objects. Tuples are just like lists with the
exception that tuples cannot be changed once declared. Tuples are usually faster than lists.
The output is :
(1, 'a', 'string', 3)
a
Iterations in Python
Iterations or looping can be performed in python by ‘for’ and ‘while’ loops. Apart from
iterating upon a particular condition, we can also iterate on strings, lists, and tuples.
i=1
while(i<10):
print(i)
i+=1
5
The output is :
1
2
3
4
5
6
7
8
9
s ="Hello World"
foriins :
print(i)
The output is :
H
e
l
l
o
W
o
r
l
d
6
Iteration by for loop on list
L =[1, 4, 5, 7, 8, 9]
for iinL:
print(i)
The output is :
1
4
5
7
8
9
Creating a list
To create a list, you use the square brackets and add elements into it accordingly. If you do not
pass any elements inside the square brackets, you get an empty list as the output.
Adding Elements
Adding the elements in the list can be achieved using the append(), extend() and insert()
functions.
• The append() function adds all the elements passed to it as a single element.
• The extend() function adds the elements one-by-one into the list.
• The insert() function adds the element passed to the index value and increase the size of
the list too.
my_list = [1, 2, 3]
print(my_list)
my_list.append([555, 12]) #add as a single element
print(my_list)
7
my_list.extend([234, 'more_example']) #add as different elements
print(my_list)
my_list.insert(1, 'insert_example') #add element i
print(my_list)
Output:
[1, 2, 3]
[1, 2, 3, [555, 12]]
[1, 2, 3, [555, 12], 234, ‘more_example’]
[1, ‘insert_example’, 2, 3, [555, 12], 234, ‘more_example’]
8
Program 3-Write programs to understand the use of Numpy’sNdarray, Basic Operations,
Indexing, Slicing, and Iterating, Conditions and Boolean Arrays.
Program-
importnumpyas np
a =np.array([1,2,3])
print a
The output is as follows −
[1, 2, 3]
# minimum dimensions
importnumpyas np
a =np.array([1,2,3,4,5],ndmin=2)
print a
The output is as follows −
[[1, 2, 3, 4, 5]]
#ndarray.shape
This array attribute returns a tuple consisting of array dimensions. It can also be used to resize
the array.
Example 1
.
importnumpyas np
a =np.array([[1,2,3],[4,5,6]])
9
printa.shape
The output is as follows −
(2, 3)
Example 2
# this resizes the ndarray
importnumpyas np
a =np.array([[1,2,3],[4,5,6]])
a.shape=(3,2)
print a
The output is as follows −
[[1, 2]
[3, 4]
[5, 6]]
importnumpyas np
x =np.ones([2,2],dtype=int)
print x
Now, the output would be as follows −
10
[[1 1]
[1 1]]
importnumpyas np
a =np.arange(10)
s = slice(2,7,2)
print a[s]
Its output is as follows −
[2 4 6]
In the above example, an ndarray object is prepared by arange() function. Then a slice object is
defined with start, stop, and step values 2, 7, and 2 respectively. When this slice object is passed
to the ndarray, a part of it starting with index 2 up to 7 with a step of 2 is sliced.
The same result can also be obtained by giving the slicing parameters separated by a colon :
(start:stop:step) directly to the ndarray object.
importnumpyas np
a =np.arange(10)
b = a[2:7:2]
print b
Here, we will get the same output −
[2 4 6]
If only one parameter is put, a single item corresponding to the index will be returned. If a : is
inserted in front of it, all items from that index onwards will be extracted. If two parameters
(with : between them) is used, items between the two indexes (not including the stop index)
with default step one are sliced.
a =np.arange(10)
b = a[5]
print b
11
Its output is as follows −
5
12
Program 4- Write programs to understand the use of Numpy’s Shape Manipulation, Array
Manipulation, Vectorization
numpy.reshape
This function gives a new shape to an array without changing the data. It accepts the following
parameters −
numpy.reshape(arr, newshape, order')
importnumpyas np
a =np.arange(8)
print'The original array:'
print a
print'\n'
b =a.reshape(4,2)
print'The modified array:'
print b
Its output would be as follows −
The original array:
[0 1 2 3 4 5 6 7]
numpy.resize
This function returns a new array with the specified size. If the new size is greater than the
original, the repeated copies of entries in the original are contained. The function takes the
following parameters.
numpy.resize(arr, shape)
importnumpyas np
a =np.array([[1,2,3],[4,5,6]])
print'First array:'
13
print a
print'\n'
print'Second array:'
print b
print'\n'
Second array:
[[1 2]
[3 4]
[5 6]]
14
Program 5-Write programs to understand the use of Numpy’s Structured Arrays, Reading and
Writing Array Data on Files.
Program-
Structured array data types can be specified in a number of ways. Earlier, we saw the dictionary
method:
np.dtype('S10,i4,f8')
15
CharacterDescription Example
16
Program 6- Write programs to understand the use of Pandas Series, DataFrame, Index Objects,
Reindexing, Dropping, Arithmetic and Data Alignment.
Program-
1) Series
Before creating a Series, Firstly, we have to import the numpy module and then use array()
function in the program.
1. import pandas as pd
2. import numpy as np
3. info = np.array(['P','a','n','d','a','s'])
4. a = pd.Series(info)
5. print(a)
Output
0 P
1 a
2 n
3 d
4 a
5 s
dtype: object
Explanation: In this code, firstly, we have imported the pandas and numpy library with
the pd and np alias. Then, we have taken a variable named "info" that consist of an array of some
values. We have called the info variable through a Series method and defined it in an "a"
variable. The Series has printed by calling the print(a) method.
1. import pandas as pd
2. # a list of strings
3. x = ['Python', 'Pandas']
17
4.
5. # Calling DataFrame constructor on list
6. df = pd.DataFrame(x)
7. print(df)
Output
0
0 Python
1 Pandas
Explanation: In this code, we have defined a variable named "x" that consist of string values. The
DataFrame constructor is being called on a list to print the values.
Pandas Index
Creating index
First, we have to take a csv file that consist some data used for indexing.
Output:
18
# retrieving multiple columns by indexing operator
a = info[["Hire Date", "Salary"]]
print(a)
Output:
Output:
Name Salary
0 John Idle 50000.0
1 Smith Gilliam 65000.0
2 Parker Chapman 45000.0
3 Jones Palin 70000.0
4 Terry Gilliam 48000.0
5 Michael Palin 66000.0
19
Program 7 – Write programs to understand the use of Pandas Functions by Element, Functions
by Row or Column, Statistics Functions, Sorting and Ranking, Correlation and Covariance, “Not a
Number” Data.
Program-
import pandas as pd
import numpy as np
unsorted_df=pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns=['col2',
'col1'])
print unsorted_df
col2 col1
1 -2.063177 0.537527
4 0.142932 -0.684884
6 0.012667 -0.389340
2 -0.548797 1.848743
3 -1.044160 0.837381
5 0.385605 1.300185
9 1.031425 -1.002967
8 -0.407374 -0.435142
0 2.237453 -1.067139
7 -1.445831 -1.701035
In unsorted_df, the labels and the values are unsorted. Let us see how these can be sorted.
By Label
Using the sort_index() method, by passing the axis arguments and the order of sorting,
DataFrame can be sorted. By default, sorting is done on row labels in ascending order.
import pandas as pd
import numpy as np
20
unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns =
['col2','col1'])
sorted_df=unsorted_df.sort_index()
print sorted_df
col2 col1
0 0.208464 0.627037
1 0.641004 0.331352
2 -0.038067 -0.464730
3 -0.638456 -0.021466
4 0.014646 -0.737438
5 -0.290761 -1.669827
6 -0.797303 -0.018737
7 0.525753 1.628921
8 -0.567031 0.775951
9 0.060724 -0.322425
Order of Sorting
By passing the Boolean value to ascending parameter, the order of the sorting can be
controlled. Let us consider the following example to understand the same.
import pandas as pd
import numpy as np
unsorted_df = pd.DataFrame(np.random.randn(10,2),index=[1,4,6,2,3,5,9,8,0,7],columns =
['col2','col1'])
sorted_df = unsorted_df.sort_index(ascending=False)
print sorted_df
21
Its output is as follows −
col2 col1
9 0.825697 0.374463
8 -1.699509 0.510373
7 -0.581378 0.622958
6 -0.202951 0.954300
5 -1.289321 -1.551250
4 1.302561 0.851385
3 -0.157915 -0.388659
2 -1.222295 0.166609
1 0.584890 -0.291048
0 0.668444 -0.061294
By Value
Like index sorting, sort_values() is the method for sorting by values. It accepts a 'by' argument
which will use the column name of the DataFrame with which the values are to be sorted.
import pandas as pd
import numpy as np
unsorted_df = pd.DataFrame({'col1':[2,1,1,1],'col2':[1,3,2,4]})
sorted_df = unsorted_df.sort_values(by='col1')
print sorted_df
col1 col2
1 1 3
2 1 2
3 1 4
0 2 1
22
Program 8- Write programs to understand the use of Pandas for Reading and Writing Data
using CSV and Textual Files, HTML Files, XML, Microsoft Excel Files.
>>>df.to_csv('data.csv')
That’s it! You’ve created the file data.csv in your current working directory. You can expand the
code block below to see how your CSV file should look:
data.csvShow/Hide
This text file contains the data separated with commas. The first column contains the row
labels. In some cases, you’ll find them irrelevant. If you don’t want to keep them, then you can
pass the argument index=False to .to_csv().
>>>
>>>df=pd.read_csv('data.csv',index_col=0)
>>>df
COUNTRY POP AREA GDP CONT IND_DAY
CHN China 1398.72 9596.96 12234.78 Asia NaN
IND India 1351.16 3287.26 2575.67 Asia 1947-08-15
USA US 329.74 9833.52 19485.39 N.America 1776-07-04
IDN Indonesia 268.07 1910.93 1015.54 Asia 1945-08-17
BRA Brazil 210.32 8515.77 2055.51 S.America 1822-09-07
PAK Pakistan 205.71 881.91 302.14 Asia 1947-08-14
NGA Nigeria 200.96 923.77 375.77 Africa 1960-10-01
BGD Bangladesh 167.09 147.57 245.63 Asia 1971-03-26
RUS Russia 146.79 17098.25 1530.75 NaN 1992-06-12
MEX Mexico 126.58 1964.38 1158.23 N.America 1810-09-16
JPN Japan 126.22 377.97 4872.42 Asia NaN
DEU Germany 83.02 357.11 3693.20 Europe NaN
FRA France 67.02 640.68 2582.49 Europe 1789-07-14
GBR UK 66.44 242.50 2631.23 Europe NaN
23
ITA Italy 60.36 301.34 1943.84 Europe NaN
ARG Argentina 44.94 2780.40 637.49 S.America 1816-07-09
DZA Algeria 43.38 2381.74 167.56 Africa 1962-07-05
CAN Canada 37.59 9984.67 1647.12 N.America 1867-07-01
AUS Australia 25.47 7692.02 1408.68 Oceania NaN
KAZ Kazakhstan 18.53 2724.90 159.41 Asia 1991-12-16
>>>
>>>df.to_excel('data.xlsx')
The argument 'data.xlsx' represents the target file and, optionally, its path. The above
statement should create the file data.xlsx in your current working directory. That file should
look like this:
The first column of the file contains the labels of the rows, while the other columns store data.
24
>>>
>>>df=pd.read_excel('data.xlsx',index_col=0)
>>>df
COUNTRY POP AREA GDP CONT IND_DAY
CHN China 1398.72 9596.96 12234.78 Asia NaN
IND India 1351.16 3287.26 2575.67 Asia 1947-08-15
USA US 329.74 9833.52 19485.39 N.America 1776-07-04
IDN Indonesia 268.07 1910.93 1015.54 Asia 1945-08-17
BRA Brazil 210.32 8515.77 2055.51 S.America 1822-09-07
PAK Pakistan 205.71 881.91 302.14 Asia 1947-08-14
NGA Nigeria 200.96 923.77 375.77 Africa 1960-10-01
BGD Bangladesh 167.09 147.57 245.63 Asia 1971-03-26
RUS Russia 146.79 17098.25 1530.75 NaN 1992-06-12
MEX Mexico 126.58 1964.38 1158.23 N.America 1810-09-16
JPN Japan 126.22 377.97 4872.42 Asia NaN
DEU Germany 83.02 357.11 3693.20 Europe NaN
FRA France 67.02 640.68 2582.49 Europe 1789-07-14
GBR UK 66.44 242.50 2631.23 Europe NaN
ITA Italy 60.36 301.34 1943.84 Europe NaN
ARG Argentina 44.94 2780.40 637.49 S.America 1816-07-09
DZA Algeria 43.38 2381.74 167.56 Africa 1962-07-05
CAN Canada 37.59 9984.67 1647.12 N.America 1867-07-01
AUS Australia 25.47 7692.02 1408.68 Oceania NaN
KAZ Kazakhstan 18.53 2724.90 159.41 Asia 1991-12-16
25
Program 9-Write programs to understand the use of Matplotlib for Simple Interactive Chart, Set
the Properties of the Plot, matplotlib and NumPy
Program-
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of Matplotlib is very
easy.
If this command fails, then use a python distribution that already has Matplotlib installed, like
Anaconda, Spyder etc.
Import Matplotlib
import matplotlib
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported
under the plt alias:
26
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()
Result:
If we need to plot a line from (1, 3) to (8, 10), we have to pass two arrays [1, 8] and [3, 10] to
the plot function.
Program 2-Draw a line in a diagram from position (1, 3) to position (8, 10):
plt.plot(xpoints, ypoints)
plt.show()
27
Result:
To plot only the markers, you can use shortcut string notation parameter 'o', which means
'rings'.
Program 3-Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):
28
Result:
Multiple Points
You can plot as many points as you like, just make sure you have the same number of points in
both axis.
Program 4-Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and finally to
position (8, 10):
plt.plot(xpoints, ypoints)
plt.show()
29
Result:
30
Program 10-Write programs to understand the use of Matplotlib for Working with Multiple
Figures and Axes, Adding Text, Adding a Grid, Adding a Legend, Saving the Charts.
Program-
With Pyplot, you can use the grid() function to add grid lines to the plot.
import numpy as np
import matplotlib.pyplot as plt
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.grid()
plt.show()
31
Result:
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.grid(axis = 'x')
plt.show()
32
Result:
Matplotlib legend
importmatplotlib.pyplotasplt
importnumpyas np
y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend()
plt.show()
33
Matplotlib legend on bottom
To place the legend on the bottom, change the legend() call to:
Take into account that we set the number of columns two ncol=2 and set a shadow.
importmatplotlib.pyplotasplt
importnumpyas np
y = [2,4,6,8,10,12,14,16,18,20]
y2 = [10,11,12,13,14,15,16,17,18,19]
x = np.arange(10)
fig = plt.figure()
ax = plt.subplot(111)
ax.plot(x, y, label='$y = numbers')
ax.plot(x, y2, label='$y2 = other numbers')
plt.title('Legend inside')
ax.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05), shadow=True, ncol=2)
plt.show()
34
Program 11-Write programs to understand the use of Matplotlib for Working with Line Chart,
Histogram, Bar Chart, Pie Charts
35
Program-
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
plt.bar(x,y)
plt.show()
Result:
With Pyplot, you can use the pie() function to draw pie charts:
36
Program 2-A simple pie chart:
import matplotlib.pyplot as plt
import numpy as np
plt.pie(y)
plt.show()
Result:
Create Histogram
The hist() function will use an array of numbers to create a histogram, the array is sent into the
function as an argument.
For simplicity we use NumPy to randomly generate an array with 250 values, where the values
will concentrate around 170, and the standard deviation is 10. Learn more about Normal Data
Distribution in our Machine Learning Tutorial.
37
Result:
This will generate a random result, and could look like this:
38
187.10006553 178.90542991 171.65790645 183.19289193 168.17446717
155.84544031 177.96091745 186.28887898 187.89867406 163.26716924
169.71242393 152.9410412 158.68101969 171.12655559 178.1482624
187.45272185 173.02872935 163.8047623 169.95676819 179.36887054
157.01955088 185.58143864 170.19037101 157.221245 168.90639755
178.7045601 168.64074373 172.37416382 165.61890535 163.40873027
168.98683006 149.48186389 172.20815568 172.82947206 173.71584064
189.42642762 172.79575803 177.00005573 169.24498561 171.55576698
161.36400372 176.47928342 163.02642822 165.09656415 186.70951892
153.27990317 165.59289527 180.34566865 189.19506385 183.10723435
173.48070474 170.28701875 157.24642079 157.9096498 176.4248199 ]
39