Python Programs Google Docs
Python Programs Google Docs
1.ELECTRICITY BILL
PROGRAM:
1.ELECTRICITY BILL
OUTPUT:
Result:
Thus the python program to get user's electric bill is executed successfully and the
Output is verified.
2.SIN SERIES
PROGRAM:
2.SIN SERIES
OUTPUT:
Result:
Thus the python program to compute sin series is executed successfully and the
Output is verified.
PROGRAM:
OUTPUT:
Result:
Thus the python program to calculate weight of a steel bar is executed successfully
and the output is verified.
PROGRAM:
import math
CL = P/(math.sqrt(3)*VL*pf)
print("Line Current =", round(CL,2),"A")
OUTPUT:
Result:
PROGRAM:
OUTPUT:
Result:
Thus the python program to exchange the values of two variables using third
variable is executed successfully and the output is verified.
PROGRAM:
OUTPUT:
Result:
Thus the python program to swap without using a third variable is executed
successfully and the output is verified.
PROGRAM:
#Read values
list1 = []
for val in range(0,n,1):
ele = int(input("Enter integer : "))
list1.append(ele)
OUTPUT:
Result:
PROGRAM:
OUTPUT:
Result:
Thus the python program to calculate the distance between two endpoints is executed
successfully and the output is verified.
7.(a).FLOYD'S TRIANGLE
PROGRAM:
7.(a).FLOYD'S TRIANGLE
OUTPUT:
Result:
7.(b).PRINT PATTERN
PROGRAM:
7.(b).PRINT PATTERN
OUTPUT:
Result:
PROGRAM:
n = int(input(‘Enter a Number:’))
sum =0
i=1
while i<=n:
sum=sum+i*i*i
i+=1
print(‘sum=’,sum)
OUTPUT:
Result:
PROGRAM:
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)
l.insert(0,'Steel Rod')
print("The list after inserting an new value is: ",l)
l.sort()
print("The list after sorting is: ",l)
l.pop()
print("After deleting last value: ",l)
l.remove('cement')
print("After deleting the value: ",l)
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.
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")
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.
PROGRAM:
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.
PROGRAM:
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.
PROGRAM:
def factorial(num):
fact=1
i=1
while (i<=num):
fact=fact*i
i=i+1
return fact
OUTPUT:
Result:
Thus the python program to find factorial of a given number using function
is executed successfully and the output is verified.
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])
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.
PROGRAM:
OUTPUT:
Result:
11.(b).PALINDROME OR NOT
PROGRAM:
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.
11.(c).ANAGRAM OR NOT
PROGRAM:
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.
Aim:
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
If this command fails, then use a python distribution that already has Pandas
installed like Anaconda, Spyder etc.
Importing Pandas
Pandas DataFrame:
Locate Row:
Pandas uses the loc attribute to return one or more specified row(s)
#refer to the row index:
print(df.loc[0])
Use the named index in the loc attribute to return the specified row(s).
#refer to the named index:
print(df.loc["day2"])
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
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 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'])}
df = pd.DataFrame(d)
print(df)
OUTPUT
7.
# Using the previous DataFrame, we will delete a column
# using del function
import pandas as pd
df = pd.DataFrame(d)
print ("Our data frame is:")
print df
8.
import pandas as pd
df = pd.DataFrame(d)
print(df.loc['b'])
OUTPUT
one 2.0
two 2.0
Name: b, dtype: float64
9.
import pandas as pd
df = pd.DataFrame(d)
print(df[2:4])
OUTPUT
one two
c 3.0 3
d NaN 4
10.
import pandas as pd
df = df.append(df2)
print(df)
OUTPUT
a b
0 1 2
1 3 4
0 5 6
1 7 8
Result:
Aim:
Numpy Arrays:
If you have Python and PIP already installed on a system, then installation
of NumPy is very easy.
Numpy Arrays
OUTPUT:
[1 2 3 4 5]
[[1 2 3]
[4 5 6]]
[[[1 2 3]
[4 5 6]
[1 2 3]
[4 5 6]]]
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
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]
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
#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]]
Array Iteration
#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
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)
OUTPUT
[array([1, 2]), array([3, 4]), array([5, 6])]
Array Sorting
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
Numpy Average
To find the average of an numpy array, you can use the numpy.average()
Function.
Syntax
Numpy Average
OUTPUT
5.0
Numpy Mean
The numpy mean function is used for computing the arithmetic mean of the
input values.
Syntax
Example
OUTPUT
Syntax
Example
import numpy
speed = [99,86,87,88,86,103,87,94,78,77,85,86]
x = numpy.median(speed)
print(x)
OUTPUT
86.5
Numpy Mode
The Mode value is the value that appears the most number
of times.
Syntax
Use the SciPy mode() method to find the number that appears the most.
Example
OUTPUT
ModeResult(mode=array([86]), count=array([3]))
RESULT
Aim:
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
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are
usually imported under the plt alias:
import matplotlib.pyplot as plt
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:-
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):
OUTPUT
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):
OUTPUT
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):
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:
OUTPUT
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:
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()
OUTPUT
Result:
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())
OUTPUT:
Result:
PROGRAM:
OUTPUT:
Result:
Thus the python program to find the longest word from a given file is
executed successfully and the output is verified.
PROGRAM:
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.
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)
OUTPUT:
RESULT
Thus the python program to find the minimum & maximum number in
a given list is executed successfully and the output is verified.
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")
OUTPUT:
RESULT
Thus the python program to validate voter’s Age Using exception handling is
executed successfully and the output is verified.
PROGRAM:
OUTPUT:
RESULT
PROGRAM:
import pygame,sys,time,random
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
direction=1
while True:
screen.fill(WHITE)
pygame.draw.circle(screen,RED,(200,y),13,0)
sleep(.006)
y+=direction
if y>=sh:
direction=-1
elif y<=0:
direction=1
pygame.display.update()
if event.type==QUIT:
pygame.quit()
sys.exit()
OUTPUT:
RESULT