Python Programs Google Docs

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 80

lOMoARcPSD|20682595

Python programs - Google Docs

Python Programming laboratory (Anna University)

Studocu is not sponsored or endorsed by any college or university


Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)
lOMoARcPSD|20682595

1.ELECTRICITY BILL

PROGRAM:

name=input("Enter Your Name:")


units=int(input("Enter Your Units:"))
if units==500:
charge=100+units*1.75
elif units>=300 and units<500:
charge=50+units*0.75
elif units>=200 and units<300:
charge=25+units*0.65
elif units>=100 and units<200:
charge=15+units*0.50
else:
charge=units*0.25
print("The Charge For Your Electric Bill Is:",charge)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

1.ELECTRICITY BILL

OUTPUT:

Result:

Thus the python program to get user's electric bill is executed successfully and the
Output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

2.SIN SERIES

PROGRAM:

x = int(input("Enter the value of x: "))


n = int(input("Enter the value of n: "))
sign = -1
fact = i =1
sum = 0
while i<=n:
p=1
fact = 1
for j in range(1,i+1):
p = p*x
fact = fact*j
sign = -1*sign
sum = sum + sign* p/fact
i = i+2
print("sin(",x,") =",sum)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

2.SIN SERIES

OUTPUT:

Result:

Thus the python program to compute sin series is executed successfully and the
Output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

3.WEIGHT OF A STEEL BAR

PROGRAM:

d=int(input("Enter a value of Diameter:"))


L=int(input("Enter a value of Length:"))
#calculate weight
weight=d*d*L/162
print('The Value of Weight:',weight)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

3.WEIGHT OF A STEEL BAR

OUTPUT:

Result:

Thus the python program to calculate weight of a steel bar is executed successfully
and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

4.ELECTRIC CURRENT IN A THREE PHASE AC CIRCUIT

PROGRAM:

import math

P = eval(input("Enter power (in Watts) : "))


pf = eval(input("Enter power factor (pf<1): "))
VL = eval(input("Enter Line Voltage (in Volts) : "))

CL = P/(math.sqrt(3)*VL*pf)
print("Line Current =", round(CL,2),"A")

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

4.ELECTRIC CURRENT IN A THREE PHASE AC CIRCUIT

OUTPUT:

Result:

Thus the python program to compute electric current in a three phase AC


circuit is executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

5.(a).EXCHANGE THE VALUES OF TWO VARIABLES USING THIRD


VARIABLE

PROGRAM:

x=input("Enter value of x: ")


y=input("Enter the value of y: ")
a=x
x=y
print("The value of x: ",x)
print ("The value of y: ",a)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

5.(a).EXCHANGE THE VALUES OF TWO VARIABLES USING THIRD


VARIABLE

OUTPUT:

Result:

Thus the python program to exchange the values of two variables using third
variable is executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

5.(b).SWAP WITHOUT USING A THIRD VARIABLE

PROGRAM:

x=input("Enter value of x: ")


y=input("Enter the value of y: ")
(x, y)=(y, x)
print("The value of x: ",x)
print ("The value of y: ",y)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

5.(b).SWAP WITHOUT USING A THIRD VARIABLE

OUTPUT:

Result:

Thus the python program to swap without using a third variable is executed
successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

6.(a).CIRCULATE THE VALUES OF N VARIABLES

PROGRAM:

# Circulate the values of n variables

n= int(input("Enter number of values : "))

#Read values
list1 = []
for val in range(0,n,1):
ele = int(input("Enter integer : "))
list1.append(ele)

#Circulate and display values


print("Circulating the elements of list ", list1)

for val in range(0,n,1):


ele = list1.pop(0)
list1.append(ele)
print(list1)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

6.(a).CIRCULATE THE VALUES OF N VARIABLES

OUTPUT:

Result:

Thus the python program to circulate the values of N variables is executed


successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

6.(b).CALCULATE THE DISTANCE BETWEEN TWO ENDPOINTS

PROGRAM:

x1=float(input("Enter the x1 value: "))


y1=float(input("Enter the y1 value: "))
x2=float(input("Enter the x2 value: "))
y2=float(input("Enter the y2 value: "))
distance=((((x2-x1)**2)+((y2-y1)**2))**0.5)
print("The endpoints are : ","{:.3f}".format(distance))

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

6.(b).CALCULATE THE DISTANCE BETWEEN TWO ENDPOINTS

OUTPUT:

Result:

Thus the python program to calculate the distance between two endpoints is executed
successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

7.(a).FLOYD'S TRIANGLE

PROGRAM:

num=int(input("Enter the number of rows: "))


k=1
for i in range(1,num+1):
for j in range(1,i+1):
print(k,end=" ")
k=k+1
print()

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

7.(a).FLOYD'S TRIANGLE

OUTPUT:

Result:

Thus the python program to print the floyd's triangle is executed


successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

7.(b).PRINT PATTERN

PROGRAM:

num=int(input("Enter the number of rows: "))


k=1
for i in range(1,num+1):
for j in range(1,i+1):
print(j,end="")
k=k+1
print()

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

7.(b).PRINT PATTERN

OUTPUT:

Result:

Thus the python program to print the given pattern is executed


successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

7.(c).CALCULATE THE VALUE OF 13+23+33+…+N3

PROGRAM:

n = int(input(‘Enter a Number:’))
sum =0
i=1
while i<=n:
sum=sum+i*i*i
i+=1
print(‘sum=’,sum)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

7.(c).CALCULATE THE VALUE OF 13+23+33+…+N3

OUTPUT:

Result:

Thus the python program to calculate the value 1 +23+33+….+N3 is executed


3

successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

8.(a).LIST OPERATIONS-CONSTRUCTION OF A BUILDING

PROGRAM:

#To append values in a list

l=[ ]
n=int(input("Enter no.of values to be inserted: "))
for i in range(n):
l.append(input("Enter the material required for construction of a building:") )
print("The created list is: ",l)

#To insert a value in a list using insert method

l.insert(0,'Steel Rod')
print("The list after inserting an new value is: ",l)

#To sort the list

l.sort()
print("The list after sorting is: ",l)

#To delete the value using pop

l.pop()
print("After deleting last value: ",l)

#To delete cement from the list

l.remove('cement')
print("After deleting the value: ",l)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

8.(a).LIST OPERATIONS-CONSTRUCTION OF A BUILDING

OUTPUT:

Result:

Thus the python program to demonstrate the various methods and operations
of list - Materials required for construction of a building is executed
successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

8.(b).TUPLE ITEMS IN A LIBRARY

PROGRAM:

t=()
#To add the values in a tuple
n=int(input("Enter no.of values to be inserted: "))
for i in range(n):
t+=((input("Enter the items in Library: ")),)
print("The created tuple is: ",t)
#To find the length of the tuple
print("The length tuple is: ",len(t))
#To find the min and max value in a tuple
print("The minimum value in the tuple is: ",min(t))
print("The maximum value in the tuple is: ",max(t))
#To delete the tuple
del t
print("The tuple is deleted")

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

8.(b).TUPLE ITEMS IN A LIBRARY

OUTPUT:

Result:

Thus the python program to demonstrate the various methods and operations
of a tuple item in the library is executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

9.(a).SET METHODS AND OPERATIONS

PROGRAM:

#To create a set


l=[]
n=int(input("Enter no.of values to be inserted: "))
for i in range(n):
l.append(int(input("Enter a number: ")))
t=set(l)
print("The created set is: ",t)
#To find the length of the tuple
print("The length of set is: ",len(t))
#To find the min and max value in a tuple
print("The minimum value in the set is: ",min(t))
print("The maximum value in the set is: ",max(t))
#To print all the unique elements of list
print("The unique elements of the list are: ",list(t))

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

9.(a).SET METHODS AND OPERATIONS

OUTPUT:

Result:

Thus the python program to demonstrate the various set methods and operations
Print all the unique elements of a list is executed successfully and the output
is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

9.(b).DICTIONARY METHODS AND OPERATIONS-STUDENT


MARKSHEET

PROGRAM:

#To create a dictionary


d={}
n=int(input("Enter no.of values to be inserted: "))
for i in range(n):
a=input("Enter the subject: ")
b=int(input("Enter the mark: "))
d[a]=b
#To view key value pairs
print("The created dictionary is: ",d.items())
#To find the length of the dictionary
print("The length of the dictionary is: ",len(d))
#To delete the value using pop
d.pop(a)
print("After deleting last value: ",d)
#To delete entire dictionary
d.clear()

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

9.(b).DICTIONARY METHODS AND OPERATIONS-STUDENT


MARKSHEET

OUTPUT:

Result:

Thus the python program to demonstrate the various methods and operations
Of a dictionary-student marksheet is executed successfully and the output
is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

10.(a).FACTORIAL OF A GIVEN NUMBER

PROGRAM:

def factorial(num):
fact=1
i=1
while (i<=num):
fact=fact*i
i=i+1
return fact

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


result=factorial(num)
print("factorial of the number:" ,result)
factorial(num)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

10.(a).FACTORIAL OF A GIVEN NUMBER

OUTPUT:

Result:

Thus the python program to find factorial of a given number using function
is executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

10.(b).MAXIMUM AND MINIMUM NUMBER USING FUNCTION

PROGRAM:

def maxmin():
l=[]
a=int(input("Enter the number of elements: "))
for i in range(1,a+1):
num=int(input("Enter the values one by one: "))
l.append(num)
maximum = max(l)
minimum = min(l)
return maximum,minimum

output=maxmin()
print("The smallest value in the list is: ",output[1])
print("The largest value in the list is: ",output[0])

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

10.(b).MAXIMUM AND MINIMUM NUMBER USING FUNCTION

OUTPUT:

Result:

Thus the python program to find maximum and minimum number from a given
list using function is executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

11.(a).REVERSE A GIVEN STRING

PROGRAM:

a=input("Enter a string : ")


print("The reversed string will be: ",a[::-1])

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

11.(a).REVERSE A GIVEN STRING

OUTPUT:

Result:

Thus the python program to reverse a given string is executed successfully


and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

11.(b).PALINDROME OR NOT

PROGRAM:

b=input("Enter a word to check it is palindrome or not: ")


if b==b[::-1]:
print(b,"- it is palindrome.")
else:
print(b,"- it is not palindrome")

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

11.(b).PALINDROME OR NOT

OUTPUT:

Result:

Thus the python program to check whether the given string is palindrome or not
is executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

11.(c).ANAGRAM OR NOT

PROGRAM:

a=input("Enter a string: ")


b=input("Enter a string: ")
if (sorted(a))==(sorted(b)):
print("Yes:) it is an anagram")
else:
print("No:( it is not anagram")

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

11.(c).ANAGRAM OR NOT

OUTPUT:

Result:

Thus the python program to check whether the given string is anagram or not
is executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

12.PROGRAM TO DEMONSTRATE PANDAS LIBRARY

Aim:

To understand about Working with Pandas dataframes

Installation of Pandas

If you have Python and PIP already installed on a system, then installation of
Pandas are very easy. It can be installed with this command

C:\Users\Your Name>pip install pandas

If this command fails, then use a python distribution that already has Pandas
installed like Anaconda, Spyder etc.

Importing Pandas

Once Pandas is installed, import it in your applications by adding the


import keyword:
import pandas as pd

Pandas DataFrame:

A Pandas DataFrame is a 2 dimensional data structure, like a 2 dimensional


array, or a table with rows and columns.

Locate Row:

Pandas uses the loc attribute to return one or more specified row(s)
#refer to the row index:
print(df.loc[0])

Locate Named Indexes

Use the named index in the loc attribute to return the specified row(s).
#refer to the named index:
print(df.loc["day2"])

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Load Files Into a DataFrame


import pandas as pd
df = pd.read_csv('data.csv')
print(df)

Using DataFrame method of Pandas:

1.
import pandas as pd
data = [1,2,3,4,5]
df = pd.DataFrame(data)
print(df)

OUTPUT

0
0 1
1 2
2 3
3 4
4 5

2.
import pandas as pd
data = [['Alex',10],['Bob',12],['Clarke',13]]
df = pd.DataFrame(data,columns=['Name','Age'])
print(df)

Name Age
0 Alex 10
1 Bob 12
2 Clarke 13

3.
import pandas as pd
data = {'Name':['Tom', 'Jack', 'Steve', 'Ricky'],'Age':[28,34,29,42]}
df = pd.DataFrame(data)
print(df)

OUTPUT

Name Age
0 Tom 28
1 Jack 34
2 Steve 29
3 Ricky 42

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

4.
#Program to demonstrate missing values –NAN(Not A Number)
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]
df = pd.DataFrame(data)
print(df)

OUTPUT

a b c
0 1 2 NaN
1 5 10 20.0

5.
import pandas as pd
data = [{'a': 1, 'b': 2},{'a': 5, 'b': 10, 'c': 20}]

#With two column indices, values same as dictionary keys


df1 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b'])

#With two column indices with one index with other name
df2 = pd.DataFrame(data, index=['first', 'second'], columns=['a', 'b1'])
print(df1)
print(df2)

OUTPUT

a b
first 1 2
second 5 10
a b1
first 1 NaN
second 5 NaN

Pandas Series
A pandas Series is a one-dimensional labeled data structure which can
hold data such as strings, integers and even other Python objects.
It is built on top of a numpy array and is the primary data structure to hold
one-dimensional data in pandas.

6.
import pandas as pd
#Series
d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),
'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

df = pd.DataFrame(d)

# Adding a new column to an existing DataFrame object with column label


by passing new series

print ("Adding a new column by passing as Series:")


df['three']=pd.Series([10,20,30],index=['a','b','c'])
print(df)

print ("Adding a new column using the existing columns in DataFrame:")


df['four']=df['one']+df['three']

print(df)

OUTPUT

Adding a new column by passing as Series:


one two three
a 1.0 1 10.0
b 2.0 2 20.0
c 3.0 3 30.0
d NaN 4 NaN
Adding a new column using the existing columns in DataFrame:
one two three four
a 1.0 1 10.0 11.0
b 2.0 2 20.0 22.0
c 3.0 3 30.0 33.0
d NaN 4 NaN NaN

7.
# Using the previous DataFrame, we will delete a column
# using del function
import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),


'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd']),
'three' : pd.Series([10,20,30], index=['a','b','c'])}

df = pd.DataFrame(d)
print ("Our data frame is:")
print df

# using del function


print ("Deleting the first column using DEL function:")
del df['one']
print(df)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

# using pop function


print ("Deleting another column using POP function:")
df.pop('two')
print(df)

8.
import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),


'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print(df.loc['b'])

OUTPUT

one 2.0
two 2.0
Name: b, dtype: float64

9.
import pandas as pd

d = {'one' : pd.Series([1, 2, 3], index=['a', 'b', 'c']),


'two' : pd.Series([1, 2, 3, 4], index=['a', 'b', 'c', 'd'])}

df = pd.DataFrame(d)
print(df[2:4])

OUTPUT

one two
c 3.0 3
d NaN 4

10.
import pandas as pd

df = pd.DataFrame([[1, 2], [3, 4]], columns = ['a','b'])


df2 = pd.DataFrame([[5, 6], [7, 8]], columns = ['a','b'])

df = df.append(df2)
print(df)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

OUTPUT

a b
0 1 2
1 3 4
0 5 6
1 7 8

Result:

Thus working with Pandas DataFrames is completed.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

13.PROGRAM TO DEMONSTRATE NUMPY LIBRARY

Aim:

To understand about working with Numpy arrays

Numpy Arrays:

If you have Python and PIP already installed on a system, then installation
of NumPy is very easy.

Install it using this command:

Once NumPy is installed, import it in your applications by adding the import


keywords:

Numpy Arrays

NumPy is used to work with arrays. The array object in NumPy


is
called ndarray.

Importing and creating an array in numpy

OUTPUT:

[1 2 3 4 5]
[[1 2 3]
[4 5 6]]
[[[1 2 3]
[4 5 6]
[1 2 3]
[4 5 6]]]

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Finding the dimension of numpy array:

import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])

print(a.ndim)
print(b.ndim)

OUTPUT:

0
3

Array indexing

Array indexing is the same as accessing an array element.

import numpy as np
#1D arrays
arr = np.array([1, 2, 3, 4])
print(arr[0])

#MultiDimensional Arrays
arr = np.array([[1,2,3,4,5], [6,7,8,9,10]])
print('5th element on 2nd row: ', arr[1, 4])

OUTPUT

1
5th element on 2nd row: 9

Array Slicing

Slicing in python means taking elements from one given index to another given
index. We pass a slice instead of an index like this: [start:end].
We can also define the step, like this: [start:end:step]

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7])
#prints from 2nd to 5th element
print(arr[1:5])
arr = np.array([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10]])
#print 2nd to 4th element from the 2nd element
print(arr[1, 1:4])

OUTPUT

[7 8 9]

ARRAY SHAPE:

NumPy arrays have an attribute called shape that returns a tuple with each
index having the number of corresponding elements.

import numpy as np
arr = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(arr.shape)

OUTPUT

(2, 4)

Array Reshape

By reshaping we can add or remove dimensions or change the number of


elements in each dimension.

#Converting a 1d array to 2d
import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12])
newark =arr.reshape(4, 3)
print(newarr)

OUTPUT

[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Array Iteration

Iterating means going through elements one by one.

#iterating in a 1d array
import numpy as np
arr = np.array([1,2, 3])
for x in arr:
print(x)

OUTPUT

1
2
3

Array joining

Joining means putting contents of two or more arrays in a single array.

Array shape

import numpy as np
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
arr = np.concatenate((arr1, arr2))
print(arr)

OUTPUT

[1 2 3 4 5 6]

Splitting is the reverse operation of Joining. Splitting breaks one array into
Multiple.

import numpy as np
arr = np.array([1, 2, 3, 4, 5, 6])
newarr = np.array_split(arr, 3)
print(newarr)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

OUTPUT
[array([1, 2]), array([3, 4]), array([5, 6])]

Array Sorting

Sorting means putting elements in an ordered sequence.

import numpy as np
#sorting numbers in ascending order
arr = np.array([3, 2, 0, 1])
print(np.sort(arr))
#sorting in alphabetical order
arr = np.array(['banana', 'cherry', 'apple'])
print(np.sort(arr))

OUTPUT

['apple' 'banana' 'cherry']

Numpy Average

To find the average of an numpy array, you can use the numpy.average()
Function.

Syntax

numpy.average(a, axis=None, weights=None, returned=False)

Numpy Average

# Using numpy to calculate the average of a list


from numpy import mean
numbers = [1,2,3,4,5,6,7,8,9]
average = mean(numbers)
print(average)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

OUTPUT

5.0

Numpy Mean

The numpy mean function is used for computing the arithmetic mean of the
input values.

Syntax

numpy.mean(a, axis=some_value, dtype=some_value, out=some_value,


keepdims=some_value)

Example

from numpy import mean


number_list = [45, 34, 10, 36, 12, 6, 80]
avg = mean(number_list)
print("The average is ", round(avg,2))

OUTPUT

The average is 31.86


The numpy median function helps in finding the middle value of a sorted array.

Syntax

numpy.median(a, axis=None, out=None, overwrite_input=False,


keepdims=False)

Example

import numpy
speed = [99,86,87,88,86,103,87,94,78,77,85,86]
x = numpy.median(speed)
print(x)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

OUTPUT

86.5

Numpy Mode

The Mode value is the value that appears the most number
of times.

Syntax

scipy.stats.mode(a, axis=0, nan_policy='propagate')

Use the SciPy mode() method to find the number that appears the most.

Example

from scipy import stats


speed = [99,86,87,88,111,86,103,87,94,78,77,85,86]
x = stats.mode(speed)
print(x)

OUTPUT

ModeResult(mode=array([86]), count=array([3]))

RESULT

Thus working with Numpy is completed.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

14.PROGRAM TO DEMONSTRATE MATPLOTLIB LIBRARY

Aim:

To understand about basic plots using matplotlib

Matplotlib is a low level graph plotting library in python that serves as a


visualization utility.

Matplotlib is mostly written in python, a few segments are written in C, Objective-C


and Javascript for Platform compatibility.

Installation of Matplotlib

If you have Python and PIP already installed on a system, then installation of
Matplotlib is very easy.

Importing Matplotlib

Once Matplotlib is installed, import it in your applications by adding the import module

statement:
import matplotlib

Now Matplotlib is imported and ready to use:

Pyplot

Most of the Matplotlib utilities lies under the pyplot submodule, and are
usually imported under the plt alias:
import matplotlib.pyplot as plt

Now the Pyplot package can be referred to as plt.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Draw a line in a diagram from position (0,0) to position (6,250):

Import matplotlib.pyplot
as plt import numpy as np
xpoints = np.array([0, 6])
ypoints = np.array([0, 250])
plt.plot(xpoints, ypoints)
plt.show()

OUTPUT

Matplotlib plotting:-

Plotting x and y points

The plot() function is used to draw points (markers) in a diagram. Draw a line
in a diagram from position (1, 3) to position (8, 10):

import matplotlib.pyplot as plt


import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints,ypoints)
plt.show()

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

OUTPUT

Plotting Without Line

To plot only the markers, you can use the shortcut string notation parameter 'o',
which means 'rings'.

Draw two points in the diagram, one at position (1, 3) and one in position (8, 10):

import matplotlib.pyplot as plt


import numpy as np
xpoints = np.array([1, 8])
ypoints = np.array([3, 10])
plt.plot(xpoints, ypoints, 'o')
plt.show()

OUTPUT

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

You can plot as many points as you like, just make sure you have the same
number of points in both axes.

Draw a line in a diagram from position (1, 3) to (2, 8) then to (6, 1) and
finally to position (8, 10):

import matplotlib.pyplot as plt


import numpy as np
xpoints = np.array([1, 2, 6, 8])
ypoints = np.array([3, 8, 1, 10])
plt.plot(xpoints, ypoints)
plt.show()

OUTPUT

Default X-Points

If we do not specify the points in the x-axis, they will get the default values
0, 1, 2, 3, (etc. depending on the length of the y-points.

So, if we take the same example as above, and leave out the x-points, the
diagram will look like this:

Plotting without x-points:

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

import matplotlib.pyplot as plt


import numpy as np
ypoints = np.array([3, 8, 1, 10, 5, 7])
plt.plot(ypoints)
plt.show()

OUTPUT

Creating Scatter Plots

With Pyplot, you can use the scatter() function to draw a scatter plot.

The scatter() function plots one dot for each observation. It needs two arrays
of the same length, one for the values of the x-axis, and one for values on
the y-axis:

import matplotlib.pyplot as plt


import numpy as np

x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])

plt.scatter(x, y)
plt.show()

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

OUTPUT

Result:

Thus working with matplotlib is completed.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

15.(a).COPYING CONTENT OF ONE FILE TO ANOTHER FILE

PROGRAM:

f=open(‘abm.txt’,’r’)
f1=open(‘aba.txt’,’w’)
for i in f :
f1.write(i)
f1.close()
f1=open(‘aba.txt’)
print(“copied data from other file is:” ,f1.read())

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

15.(a).COPYING CONTENT OF ONE FILE TO ANOTHER FILE

OUTPUT:

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Result:

Thus the python program to copy the content of a file to another is


executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

15.(b).LONGEST WORD FROM A GIVEN FILE

PROGRAM:

#write a python program to find longest word in a file


with open ("sam.txt","r")as f:
words=f.read().split()
count=0
for word in words:
count+=1
print("The count of the word are: ",count)
print("The longest word is: ",max(words))

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

OUTPUT:

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Result:

Thus the python program to find the longest word from a given file is
executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

15.(c).OCCURRENCES OF A GIVEN WORD IN A GIVEN FILE

PROGRAM:

#write a python program to find the occurrences of a given word in a file


n=input("Enter a word: ")
with open ("sam.txt","r")as f:
words=f.read().split()
count=0
for word in words:
if word==n:
count+=1
print("The count of a given word is: ",count)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

15.(c).OCCURRENCES OF A GIVEN WORD IN A GIVEN FILE

OUTPUT:

Result:

Thus the python program to find the occurrences of a given word in a given file is
executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

16.(a).EXCEPTION HANDLING-DIVIDE BY ZERO ERROR

PROGRAM

try:
num1=int(input("Enter First Number:"))
num2=int(input("Enter Second Number:"))
result=num1/num2
print(result)

except ValueError as e:
print("Invalid Input Integer")

except ZeroDivisionError as e:
print(e)

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

16.(a).EXCEPTION HANDLING-DIVIDE BY ZERO ERROR

OUTPUT:

RESULT

Thus the python program to find the minimum & maximum number in
a given list is executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

16.(b).VOTERS AGE VALIDATION

PROGRAM

try:
age=int(input("enter the age of voter:"))
if age>=18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except ValueError:
print("age must be a valid number")

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

16.(b).VOTERS AGE VALIDATION

OUTPUT:

RESULT

Thus the python program to validate voter’s Age Using exception handling is
executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

17.(a). DRAWING DIFFERENT SHAPES-PYGAME

PROGRAM:

#python program to draw different shapes using pygame module


import pygame
pygame.init()
white=(255,255,255)
green=(0,255,0)
blue=(0,0,255)
black=(0,0,0)
red=(255,0,0)
x=400
y=400
display_surface=pygame.display.set_mode((x,y))
pygame.display.set_caption('Drawing')
display_surface.fill(white)
pygame.draw.circle(display_surface,green,(50,50),10,0)
pygame.draw.ellipse(display_surface,green,(300,250,40,80),1)
pygame.draw.rect(display_surface,black,(150,300,100,50))
while True:
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
quit()
pygame.display.update()

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

OUTPUT:

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

RESULT

Thus the python pygame program to draw different shapes such as


circle,ellipse,rectangle is executed successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

17.(b).SIMULATE A BOUNCING BALL-PYGAME

PROGRAM:

#Simulate a bouncing ball-Pygame

import pygame,sys,time,random

from pygame.locals import*

from time import*

pygame.init()

screen=pygame.display.set_mode((500,400),0,32)

pygame.display.set_caption("Bouncing Ball")

WHITE=(255,255,255)

RED=(255,0,0)

info=pygame.display.Info()

sw=info.current_w

sh=info.current_h

y=0

#Initial direction is down

direction=1

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

while True:

screen.fill(WHITE)

pygame.draw.circle(screen,RED,(200,y),13,0)

sleep(.006)

y+=direction

if y>=sh:

#changes the direction from down to try:

direction=-1

elif y<=0:

#change the direction from up to down:

direction=1

pygame.display.update()

for event in pygame.event.get():

if event.type==QUIT:

pygame.quit()

sys.exit()

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

17.(b).SIMULATE A BOUNCING BALL-PYGAME

OUTPUT:

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

RESULT

Thus the python pygame program to simulate a bouncing ball is executed


successfully and the output is verified.

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)


lOMoARcPSD|20682595

Downloaded by Sundari YBT (sundari.ybt@hmgi.ac.in)

You might also like