Lab Manual Final Scaling
Lab Manual Final Scaling
AIM:
To write a python program for the electricity billing.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the input variable "unit".
Step 3: Process the following:
When the unit is less than or equal to 100units,
calculate usage-unit*5.
When the unit is between 100 to200 units,
calculate usage (100*5)+((unit-100)*7).
When the unit is between 200 to 300 units,
calculate usage (100*5)+(100*7)+((unit- 200)*10)
When the unit is above 300units, calculate usage
(100*5)+(100*7)+(100*10)+((unit- 300)*15)
For further, no additional charge will be calculated.
Step 4: Display the amount "usage" to the user.
Step 5: Stop the program.
PROGRAM:
unit=int(input("Please enter Number of Unit you
Consumed :"))
if(unit<=100):
usage=unit*5
elif(unit<=200):
usage=(100*5)+((unit-00)*7)
elif(unit<=300):
usage=(100*5)+(100*7)+((unit-0)*10)
else:
usage=(100*5)+(100*7)+(100*10)+((unit-300)*15)
print("Electricity Bill=%.2f"%usage)
print("Note: No additional charge will be calculated ")
OUTPUT:
Please enter Number of Unit you Consumed : 650
Electricity Bill = 7450.00
Note: No additional charge will be calculated
RESULT:
Thus the electricity billing program has been executed and
verified successfully.
Ex.No.1(b) Identification and solving of simple real life or
scientific or technical problems - Retail Shop Billing
AIM:
To write a python program for the retail shop billing.
ALGORITHM:
Step 1: Start the program
Step 2: Initialize the values of the items
Step 3: Read the input like the name of item and quantity.
Step 4: Process the following amount= (item_name *quantity) +
amount
Step 5: Repeat the step4 until the condition get fails.
Step 6: Display the value of "amount".
Step 7: Stop the program.
PROGRAM:
print("Welcome to Riya Retail Shopping")
print("List of items in our market")
soap=60;power=120;tooth_brush=40;paste=80;perfume=250
amount=0
print("1.Soap\n2.Powder\n3.Tooth Brush\n4.Tooth Paste
\n5.Perfume")
print("To Stop the shopping type number 0")
while (1):
item = int(input("Enter the item number: "))
if(item==0):
break
else:
if(item<=5):
quantity=int(input("Enter the quantity: "))
if(item==1):
amount=(soap*quantity)+amount
elif(item==2):
amount=(power*quantity)+amount
elif(item==3):
amount=(tooth_brush*quantity)+amount
elif(item==4):
amount=(paste*quantity)+amount
elif(item==5):
amount=(perfume*quantity)+amount
else:
print("Item Not available")
print("Total amount need to pay is: ",amount)
print("Happy for your visit")
OUTPUT:
Welcome to Riya Retail Shopping
List of items in our market
1.Soap
2.Powder
3.Tooth Brush
4.Tooth Paste
5.Perfume
To Stop the shopping type number 0
Enter the item number: 1
Enter the quantity: 5
Enter the item number: 2
Enter the quantity: 4
Enter the item number: 0
Total amount need to pay is: 780
Happy for your visit
RESULT:
Thus the retail shop billing program has been executed and verified
successfully.
Ex.No.1(c) Identification and solving of simple real life or
scientific or technical problems - Sin Series
AIM:
To write a python program for sin series.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the input like the value of x in radians and n
where n is a number up to which we want to print the
sum of series.
Step 3: For first term,
x-x*3.14159/180
t-x;
sum-x
Step 4: For next term,
t(t*(-1)*x*x)/(2*i*(2*i+1))
sum-sum+t;
Step 5: Repeat the step4, looping 'n' 'times to get the sum of
first 'n' terms of the series.
Step 6: Display the value of sum.
Step 7: Stop the program.
PROGRAM:
x=float(input("Enter the value for x : "))
a=x
n=int(input("Enter the value for n : "))
x=x*3.14159/180
t=x;
sum=x
for i in range(1,n+1):
t=(t*(-1)*x*x)/(2*i*(2*i+1))
sum=sum+t
print("The value of Sin(",a,")=",round(sum,2))
OUTPUT:
Enter the value for x : 30
Enter the value for n : 5
The value of Sin( 30.0 )= 0.5
RESULT:
Thus the sine series program has been executed and verified
successfully.
Ex.No.2(a) Python programming using simple statements and
expressions - Exchange the Values of Two Variables
AIM:
Write a python program to exchange the values of two variables.
ALGORITHM:
Step 1: Declared a temporary variable a and b.
Step 2: Assign the value of a and b.
Step 3: Assign the value of a to b, and b to a.
Step 4: We don’t even need to perform arithmetic operations.
We can use:
a,b = b,a
Step 5: To print the result.
PROGRAM:
a=10
b=20
a,b=b,a
print("The swapping of a value is=",a)
print("The swapping of b value is=",b)
OUTPUT:
The swapping of a value is= 20
The swapping of b value is= 10
RESULT:
Thus the swapping of two numbers python program was executed
successfully and verified.
Ex.No.2(b) Python programming using simple statements and
expressions - Circulate the Values of “n” Variables
AIM:
Write a python program to circulate the values of n variables.
ALGORITHM:
Step 1: Circulate the values of n variables.
Step 2: Get the input from the user.
Step 3: To create the empty list then declare the conditional
statements using for loop.
Step 4: Using append operation to add the element in the list and
the values are rotate by using this append operation.
Step 5: Stop the program.
PROGRAM:
def circulate(A,N):
for i in range(1,N+1):
B=A[i:]+A[:i]
print("circulation",i,"=",B)
return
A=[11,12,13,14,15,16,17,18]
N=int(input("Enter n:"))
circulate(A,N)
OUTPUT:
Enter n:5
circulation 1 = [12, 13, 14, 15, 16, 17, 18, 11]
circulation 2 = [13, 14, 15, 16, 17, 18, 11, 12]
circulation 3 = [14, 15, 16, 17, 18, 11, 12, 13]
circulation 4 = [15, 16, 17, 18, 11, 12, 13, 14]
circulation 5 = [16, 17, 18, 11, 12, 13, 14, 15]
RESULT:
Thus the python program to circulate the values of n variables was
executed successfully and verified.
Ex.No.2(c) Python programming using simple statements and
expressions - Distance between two points
AIM:
Write a python program to calculate the distance between two
numbers.
ALGORITHM:
Step 1: Start the program.
Step 2: Read all the values of x1,x2,y1,y2.
Step 3: Calculate the result.
Step 4: Print the result.
Step 5: Stop the program.
PROGRAM:
import math
x1=int(input("Enter the value of x1="))
x2=int(input("Enter the value of x2="))
y1=int(input("Enter the value of y1="))
y2=int(input("Enter the value of y2="))
dx=x2-x1
dy=y2-y1
d=dx**2+dy**2
result=math.sqrt(d)
print(result)
OUTPUT:
Enter the value of x1=56
Enter the value of x2=76
Enter the value of y1=87
Enter the value of y2=98
22.825424421026653
RESULT:
Thus the distance between of two points was successfully executed
and verified.
Ex.No.3(a) Scientific problems using conditionals and
iterative loops - Number Series
AIM:
Write a python program with conditional and iterative statements for
number series.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the value of n.
Step 3: Initialize i = 1,x=0.
Step 4: Repeat the following until i is less than or equal to n.
Step 4.1: x=x*2+1.
Step 4.2: Print x.
Step 4.3: Increment the value of i .
Step 5: Stop the program.
PROGRAM:
n=int(input(" Enter the number of terms for the series "))
i=1
x=0
while(i<=n):
x=x*2+1
print(x, sep= "")
i+=1
OUTPUT:
Enter the number of terms for the series 5
1
3
7
15
31
RESULT:
Thus the python program to print numbers series is executed and
verified.
Ex.No.3(b) Scientific problems using conditionals and
iterative loops - Number Patterns
AIM:
Write a python program with conditional and iterative statements for
number pattern.
ALGORITHM:
Step 1: Start the program.
Step 2: Declare the value for rows.
Step 3: Let i and j be an integer number.
Step 4: Repeat step 5 to 8 until all value parsed.
Step 5: Set i in outer loop using range function, i = rows+1 and
rows will be initialized to I.
Step 6: Set j in inner loop using range function and i integer will be
initialized to j.
Step 7: Print i until the condition becomes false in inner loop.
Step 8: Print new line until the condition becomes false in outer
loop.
Step 9: Stop the program.
PROGRAM:
rows = int(input('Enter the number of rows'))
for i in range(rows+1):
for j in range(i):
print(i, end=' ')
print(' ')
OUTPUT:
Enter the number of rows 5
1
22
333
4444
55555
RESULT:
Thus the python program to print numbers patterns is executed and
verified
Ex.No.3(c) Scientific problems using conditionals and
iterative loops - Pyramid Pattern
AIM:
Write a Python program with conditional and iterative statements for
Pyramid Pattern.
ALGORITHM:
AIM:
To Write a python program to implement items present in a library.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create the variable inside that variable assigned the list of
elements based on the library using List and tuple.
STEP 3: Using array index to print the items using list and tuple.
STEP 4: To print the result using output statement.
STEP 5: Stop the program.
PROGRAM:
library=["books", "author", "barcodenumber" , "price"]
library[0]="ramayanam"
print(library[0])
library[1]="valmiki"
library[2]=123987
library[3]=234
print(library)
print("Tuple : ")
tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
tup3 = tup1+ tup2
print(tup3)
OUTPUT:
ramayanam
['ramayanam', 'valmiki', 123987, 234]
Tuple :
(12134, 250000, 'books', 'totalprice')
RESULT:
Thus the Python Program is executed successfully and the output is
verified.
Ex.No.5(a) Implementing real-time/technical applications
using sets, dictionaries - Language
AIM:
To write a python program for language.
ALGORITHM:
Step 1: Start the program.
Step 2: Assign the languages.
Step 3: Perform all the dictionary operations.
Step 4: Print the result.
Step 5: End the program.
PROGRAM:
LANGUAGE1={'Pitch','Syllabus','Script','Grammar','Sentences'}
LANGUAGE2={'Grammar','Syllabus','Context','Words','Phonetics'}
print("Union of LANGUAGE1 and LANGUAGE2
is”,LANGUAGE1|LANGUAGE2)
print("Intersection of LANGUAGE1 and LANGUAGE2
is ",LANGUAGE1&LANGUAGE2)
print("Difference of LANGUAGE1 and LANGUAGE2
is ",LANGUAGE1-LANGUAGE2)
print("Symmetric difference of LANGUAGE1 and LANGUAGE2
is ",LANGUAGE1^LANGUAGE2)
OUTPUT:
Union of LANGUAGE1 and LANGUAGE2 is {'Syllabus',
'Sentences', 'Pitch', 'Grammar', 'Words', 'Script', 'Context',
'Phonetics'}
Intersection of LANGUAGE1 and LANGUAGE2 is {'Syllabus',
'Grammar'}
Difference of LANGUAGE1 and LANGUAGE2 is {'Script',
'Sentences', 'Pitch'}
Symmetric difference of LANGUAGE1 and LANGUAGE2 is
{'Script', 'Sentences', 'Pitch', 'Context', 'Words', 'Phonetics'}
RESULT:
Thus the Language program has been executed and verified
successfully.
Ex.No.5(b) Implementing real-time/technical applications using
sets, dictionaries - Components of an Automobile
AIM:
To write a python program to implement Components of an
automobile using Sets and Dictionaries.
ALGORITHM:
STEP 1: Start the program.
STEP 2: Create the variable and stored the unordered list of
elements based on materials required for construction of
building set and dictionary.
STEP 3: Using for loop to list the number of elements and using
array index to print the items using set and dictionary.
STEP 4: To print the result using output statement.
STEP 5: Stop the program.
(i) SET :
PROGRAM:
cars={'BMW','Honda','Audi','Mercedes','Honda','Toyota','Ferrari',
'Tesla'}
print('Approach #1=',cars)
print('---------------')
print('Approach #2')
for car in cars:
print('Car name={}'.format(car))
print('---------------')
cars.add('Tata')
print('New cars set={}'.format(cars))
cars.discard('Mercedes')
print('discard()method={}'.format(cars))
OUTPUT:
Approach #1= {'Ferrari', 'Mercedes', 'Audi', 'Tesla', 'BMW', 'Toyota',
'Honda'}
---------------
Approach #2
Car name=Ferrari
Car name=Mercedes
Car name=Audi
Car name=Tesla
Car name=BMW
Car name=Toyota
Car name=Honda
---------------
New cars set={'Ferrari', 'Tata', 'Mercedes', 'Audi', 'Tesla', 'BMW',
'Toyota', 'Honda'}
discard()method={'Ferrari', 'Tata', 'Audi', 'Tesla', 'BMW', 'Toyota',
'Honda'}
(ii) DICTIONARY
PROGRAM:
Dict = {}
print("Empty Dictionary: ")
print(Dict)
Dict[0] = 'BRICKS'
Dict[2] = 'CEMENT'
Dict[3] = 'BLUE PRINT'
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict['Value_set'] = 2, 3, 4
print("\nDictionary after adding 3 elements: ")
print(Dict)
Dict[2] = 'STEEL'
print("\nUpdated key value: ")
print(Dict)
Dict[5] = {'Nested': {'1': 'LIME', '2': 'SAND'}}
print("\nAdding a Nested Key: ")
print(Dict)
OUTPUT:
Empty Dictionary:
{}
AIM:
To write a python program for elements of a civil structure.
ALGORITHM:
Step 1: Start the program.
Step 2: Assign the elements of a civil structure.
Step 3: Perform all the set operations.
Step 4: Print the result.
Step 5: End the program.
PROGRAM:
print("Elements of a civil structure")
print("............................")
print("1.foundation\n2.floors\n3.walls\n4.beamsandslabs\n5.
columns\n6.roof\n7.stairs\n8.parapet\n9.lintels \
n10.Dampproof")
elements1={"foundation","floors","floors","walls",
"beamsandslabs","columns","roof","stairs","parapet",
"lintels"}
print("\n")
print(elements1)
print("\n")
elements1.add("dampproof")
print(elements1)
elements2={"plants","compound"}
print("\n")
print(elements2)
print("\n")
elements1.update(elements2)
elements1.remove("stairs")
print(elements1)
elements1.discard("hardfloor")
elements1.pop()
print(elements1)
print(sorted(elements1))
print("\n")
print("set operation")
s1={"foundation","floors"}
s2={"floors","walls","beams"}
print(s1.symmetric_difference(s2))
print(s1.difference(s2))
print(s2.difference(s1))
print(s1.intersection(s2))
print(s1.union(s2))
OUTPUT:
Elements of a civil structure
............................
1.foundation
2.floors
3.walls
4.beamsandslabs
5.columns
6.roof
7.stairs
8.parapet
9.lintels
10.Dampproof
set operation
{'foundation', 'walls', 'beams'}
{'foundation'}
{'beams', 'walls'}
{'floors'}
{'walls', 'floors', 'foundation', 'beams'}
RESULT:
Thus the elements of a civil structure program has been executed and
verified successfully.
Ex.No.6(a) Implementing factorial programs using functions
AIM:
To Write a Python function to calculate the factorial of a number.
ALGORITHM:
Step 1: Get a positive integer input (n) from the user.
Step 2: Check if the values of n equal to 0 or not if it's zero it
will return 1 Otherwise else statement can be executed.
Step 3: Using the below formula, calculate the factorial of a
number n*factorial(n-1).
Step 4: Print the output i.e the calculated.
PROGRAM:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
n=int(input("Input a number to compute the factiorial : "))
print(factorial(n))
OUTPUT:
Input a number to compute the factiorial : 4
24
RESULT:
Thus the program was executed and verified successfully.
Ex.No.6(b) Implementing program largest number
in a list using function
AIM:
To Write a Python program to get the largest number from a list.
ALGORITHM:
Step 1: Declare a function that will find the largest number.
Step 2: Use max() method and store the value returned by it in a
variable.
Step 3: Return the variable.
Step 4: Declare and initialize a list or take input.
Step 5: Call the function and print the value returned by it.
PROGRAM:
def max_num_in_list( list ):
max = list[ 0 ]
for a in list:
if a > max:
max = a
return max
print(max_num_in_list([1, 2, -8, 0]))
OUTPUT:
2
RESULT:
Thus the program was executed and verified successfully.
Ex.No.6(c) Implementing programs using functions –
area of shape
AIM:
To Write a python program to implement area of shape using
functions.
ALGORITHM:
Step 1: Get the input from the user shape’s name.
Step 2: If it exists in our program then we will proceed to find the
entered shape’s area according to their respective
formulas.
Step 3: If that shape doesn’t exist then we will print “Sorry!”.
Step 4: Stop the program.
PROGRAM:
def calculate_area(name):
name = name.lower()
if name == "rectangle":
l = int(input("Enter rectangle's length: "))
b = int(input("Enter rectangle's breadth: "))
rect_area = l * b
print("The area of rectangle is", rect_area, ".")
elif name == "square":
s = int(input("Enter square's side length: "))
sqt_area = s * s
print("The area of square is", sqt_area, ".")
elif name == "triangle":
h = int(input("Enter triangle's height length: "))
b = int(input("Enter triangle's breadth length: "))
tri_area = 0.5 * b * h
print("The area of triangle is", tri_area, ".")
elif name == "circle":
r = int(input("Enter circle's radius length: "))
pi = 3.14
circ_area = pi * r * r
print("The area of triangle is", circ_area, ".")
elif name == 'parallelogram':
b = int(input("Enter parallelogram's base length: "))
h = int(input("Enter parallelogram's height length: "))
para_area = b * h
print("The area of parallelogram is", para_area, ".")
else:
print("Sorry! This shape is not available")
print("Calculate Shape Area")
shape_name = input("Enter the name of shape whose area you
want to find: ")
calculate_area(shape_name)
OUTPUT:
Calculate Shape Area
Enter the name of shape whose area you want to find:RECTANGLE
Enter rectangle's length: 10
Enter rectangle's breadth: 15
The area of rectangle is 150.
RESULT:
Thus the python program to implement area of shape using functions
was successfully executed and verified.
Ex.No.7(a) Implementing programs using strings – Reverse
AIM:
To write a python program to implement reverse of a string using
string functions.
ALGORITHM:
Step 1: Start the program.
Step 2: Using function string values of arguments passed in that
function.
Step 3: Python string to accept the negative number using slice
operation.
Step 4: To print the reverse string value by Using reverse method
function.
Step 5: Print the result.
PROGRAM:
def reverse(string):
string = string[::-1]
return string
s = "Firstyearcse"
print ("The original string is : ",end="")
print (s)
print ("The reversed string(using extended slice syntax) is :
",end="")
print (reverse(s))
OUTPUT:
The original string is : Firstyearcse
The reversed string(using extended slice syntax) is : escraeytsriF
RESULT:
Thus the reverse of a string function python program was executed
and successfully verified.
Ex.No. 7(b) Implementing programs using strings - Palindrome
AIM:
To write a python program to implement palindrome using string
functions.
ALGORITHM:
Step 1: Start by declaring the isPalindrome() function and passing
the string argument.
Step 2: Then, in the function body,
Step 3: To get the reverse of the input string using a slice operator
– string[::-1].
Step 4: -1 is the step parameter that ensures that the slicing will
start from the end of the string with one step back each
time.
Step 5: If the reversed string matches the input string, it is a
palindrome Or else, it is not a palindrome.
PROGRAM:
def isPalindrome(s):
return s == s[::-1]
s = input("Enter the string=")
ans = isPalindrome(s)
if ans:
print("The string is palindrome ")
else:
print("The string is not a palindrome")
OUTPUT:
Enter the string=madam
The string is palindrome
RESULT:
Thus the program of palindrome by using function in python
executed successfully and verified.
Ex.No.7(c) Implementing programs using strings
- Character count
AIM:
To Write a python program to implement Characters count using
string functions.
ALGORITHM:
Step 1: User to enter the string. Read and store it in a variable.
Step 2: Initialize one counter variable and assign zero as its value.
Step 3: Increment this value by 1 if any character is found in the
string.
Step 4: Using one loop, iterate through the characters of the string
one by one.
Step 5: Check each character if it is a blank character or not. If it is
not a blank character, increment the value of the counter
variable by ’1‘.
Step 6: After the iteration is completed, print out the value of the
counter.
Step 7: This variable will hold the total number of characters in
the string.
PROGRAM:
input_string = input("Enter a string : ")
count = 0
for c in input_string :
if c.isspace() != True:
count = count + 1
print("Total number of characters : ",count)
OUTPUT:
Enter a string : RAJIV GANDHI COLLEGE OF ENGINEERING
AND TECHNOLOGY
Total number of characters : 44
RESULT:
Thus the program of character count in string in python was executed
successfully and verified.
Ex.No.7(d) Implementing programs using strings
– Replacing Characters
AIM:
To write a python program to implement Replacing Characters using
string functions.
ALGORITHM:
Step 1: Using string.replace(old, new, count)
Step 2: by using string Parameters to change it old – old substring
you want to replace.new – new substring which would
replace the old substring.
Step 3: count – (Optional ) the number of times you want to
replace the old substring with the new substring.
Step 4: To returns a copy of the string where all occurrences of a
substring are replaced with another substring.
PROGRAM:
string = "Welcome to python programming"
print(string.replace("to", "our"))
print(string.replace("og", "a", 3))
OUTPUT:
Welcome our python programming
Welcome to python praramming
RESULT:
Thus the program was executed and successfully verified.
Ex.No.8(a) Implementing programs using written
modules and python standard libraries – pandas
AIM:
To write a python program to implement pandas modules. Pandas
are denote python data structures.
ALGORITHM:
Step 1: Start the program.
Step 2: DataFrame is the key data structure in Pandas. It allows us
to store and manipulate tabular data.
Step 3: Python method of DataFrame has data aligned in rows and
columns like the SQL table or a spreadsheet database.
Step 4: Using Series: It is a 1-D size-immutable array like structure
having homogeneous data in a python module.
Step 5:Using max function method to display the maximum ages
in a program.
Step 6: List of elements can be displayed by using output
statement in pandas.
Step 7: Stop the program.
PROGRAM:
import pandas as pd
df = pd.DataFrame(
{
"Name": [ "Braund, Mr. Owen Harris","Allen, Mr. William
Henry","Bonnell, Miss. Elizabeth"],
"Age": [22, 35, 58],
"Sex": ["male", "male", "female"],
}
)
print(df)
print(df["Age"])
ages = pd.Series([22, 35, 58], name="Age")
print(ages)
df["Age"].max()
print(ages.max())
print(df.describe())
OUTPUT:
Name Age Sex
0 Braund, Mr. Owen Harris 22 male
1 Allen, Mr. William Henry 35 male
2 Bonnell, Miss. Elizabeth 58 female
0 22
1 35
2 58
Name: Age, dtype: int64
0 22
1 35
2 58
Name: Age, dtype: int64
58
Age
count 3.000000
mean 38.333333
std 18.230012
min 22.000000
25% 28.500000
50% 35.000000
75% 46.500000
max 58.0000
RESULT:
Thus the python program to implement pandas modules. Pandas are
Denote python data structures was successfully executed and verified.
Ex.No.8(b) Implementing programs using written
modules and python standard libraries – numpy
AIM:
Implementing programs using written modules and Python Standard
Libraries – numpy.
ALGORITHM:
Step 1: Start the program
Step 2: To create the package of numpy in python and using array
index in numpy for numerical calculation.
Step 3: To create the array index inside that index to assign the
values in that dimension.
Step 4: Declare the method function of arrange statement can be
used in that program.
Step 5: By using output statement we can print the result.
PROGRAM:
import numpy as np
a = np.arange(6)
a2 = a[np.newaxis, :]
a2.shape
a = np.array([1, 2, 3, 4, 5, 6])
a = np.array([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])
print(a[0])
print(a[1])
np.zeros(2)
np.ones(2)
np.arange(4)
np.arange(2, 9, 2)
np.linspace(0, 10, num=5)
x = np.ones(2, dtype=np.int64)
print(x)
arr = np.array([2, 1, 5, 3, 7, 4, 6, 8])
np.sort(arr)
a = np.array([1, 2, 3, 4])
b = np.array([5, 6, 7, 8])
np.concatenate((a, b))
array_example = np.array([[[0, 1, 2, 3], [4, 5, 6, 7]], [[0, 1, 2, 3],
[4,5, 6, 7]], [[0 ,1 ,2, 3], [4, 5, 6, 7]]])
array_example.ndim
array_example.size
array_example.shape
a = np.arange(6)
print(a)
b=a.reshape(3, 2)
print(b)
np.reshape(a, newshape=(1, 6), order='C')
OUTPUT:
[1 2 3 4]
[5 6 7 8]
[1 1]
[0 1 2 3 4 5]
[[0 1]
[2 3]
[4 5]]
RESULT:
Thus the python program to implement numpy module in
python,Numerical python are mathematical calculations are successfully
executed and verified.
Ex.No.8(c) Implementing programs using written modules
And python standard libraries – matplotlib
AIM:
To write a python program to implement matplotolib module in
python. .matplotlib python are used to show the visualization entities in
python.
ALGORITHM:
Step 1: Start the program.
Step 2: It divided the circle into 4 sectors or slices which
represents the respective category(playing, sleeping,
eating and working) along with the percentage they hold.
Step 3: Now, if you have noticed these slices adds up to 24 hrs,
but the calculation of pie slices is done automatically .
Step 4: In this way, pie charts are calculates the percentage or the
slice of the pie in same way using area plot etc using
matplotlib.
Step 5: Stop the program.
PROGRAM:
import matplotlib.pyplot as plt
days = [1,2,3,4,5]
sleeping =[7,8,6,11,7]
eating = [2,3,4,3,2]
working =[7,8,7,2,2]
playing = [8,5,7,8,13]
slices = [7,2,2,13]
activities = ['sleeping','eating','working','playing']
cols = ['c','m','r','b']
plt.pie(slices,labels=activities, colors=cols,
startangle=90,
shadow= True,
explode=(0,0.1,0,0),
autopct='%1.1f%%')
plt.title('Pie Plot')
plt.show()
OUTPUT:
RESULT:
Thus the python program to implement matplotolib module in
python. .matplotlib python are used to show the visualization entites in
python was successfully executed and verified.
Ex.No.8(d) Implementing programs using written modules and
python standard libraries – scipy
AIM:
Write a python program to implement scipy module in python. .scipy
python are used to solve the scientific calculations.
ALGORITHM:
Step 1: Start the program.
Step 2: The SciPy library consists of a subpackage named
scipy.interpolate that consists of spline functions and
classes, one-dimensional and multi-dimensional
(univariate and multivariate) interpolation classes, etc.
Step 3: To import the package of np in a program and create
x,x1,y,y1 identifier inside that assign the np function.
Step 4: SciPy provides interp1d function that can be utilized to
produce univariate interpolation.
Step 5: Stop the program.
PROGRAM:
import matplotlib.pyplot as plt
from scipy import interpolate
import numpy as np
x = np.arange(5, 20)
y = np.exp(x/3.0)
f = interpolate.interp1d(x, y)
x1 = np.arange(6, 12)
y1 = f(x1) # use interpolation function returned by `interp1d`
plt.plot(x, y, 'o', x1, y1, '--')
plt.show()
OUTPUT:
RESULT:
Thus the python program to implement Scipy module in python.
Scipy python are used to show the visualization entites in python was
successfully executed and verified.
Ex.No.9(a) Implementing real-time/technical applications
using file handling - copy from one file to another
AIM:
To Write a python program to implement File Copying.
ALGORITHM:
Step 1: Capture the original path
To begin, capture the path where your file is currently
stored.
For example, I stored a CSV file in a folder called
AAMEC2(2):
C:\Users\Administrator\Desktop\AAMEC2 (2)\bookk.csv
Where the CSV file name is „products„ and the file extension
is csv
Step 2: Capture the target path
Next, capture the target path where you‟d like to copy the
file.
In my case, the file will be copied into a folder called
AAMEC2:
C:\Users\Administrator\Desktop \bookk.csv
Step 3: Copy the file in Python using shutil.copyfile
PROGRAM:
import shutil
original = r'C:\Users\RGCET\Desktop\RGCET
target = r'C:\Users\RGCET\Desktop\RGCET
shutil.copyfile(original, target)
RESULT:
Thus the a python program to implement File Copying was
successfully executed and verified .
Ex.No.9(b) Implementing real-time/technical applications
using file handling - word count
AIM:
To Write a python program to implement word count in file
operations in python.
ALGORITHM:
Step 1: Open and create the txt file with some statements.
Step 2: To save that file with the extension of txt file.
Step3 : Now to count the the lenghth of word in a file.
Step 4: To display the word count in a target file.
PROGRAM:
file =open(r"C:\Users\Administrator\Desktop\count2.txt","rt")
data = file.read()
words = data.split()
print('Number of words in text file :', len(words))
OUTPUT:
Number of words in text file : 4
RESULT:
Thus the python program to implement word count in file
operations in python was executed successfully and verified.
Ex.No.9(c) Implementing real-time/technical applications
using file handling - Longest word
AIM:
To Write a python program to implement longest word in File
operations.
ALGORITHM:
Step 1: Open and create the txt file with some statements.
Step 2: To save that file with the extension of txt file.
Step 3: Now to count the longest of word in a file.
Step 4: To display the longest word in a target file.
PROGRAM:
def longest_word(count):
with open(count, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key=len))
return [word for word in words if len(word) == max_len]
print(longest_word('count.txt'))
OUTPUT:
['welcome', 'program']
RESULT:
Thus the python program to implement longest word in File
operations was executed successfully verified.
Ex.No.10(a) Python Program for implementing
real-time/technical applications using exception
handling.- divide by zero error
AIM:
To Write a exception handling program using python to depict the
divide by zero error.
ALGORITHM:
Step 1: Start the program.
Step 2: The try block tests the statement of error. The except
block handle the error.
Step 3: A single try statement can have multiple except
statements. This is useful when the try block contains
statements that may throw different types of exceptions.
Step 4: To create the two identifier name and enter the values.
Step 5: By using division operation and if there is any error in that
try block raising the error in that block.
Step 6: Otherwise it display the result.
PROGRAM:
(I)
marks = 10000
a = marks / 0
print(a)
OUTPUT:
ZeroDivisionError: division by zero
(II)
a=int(input("Entre a="))
b=int(input("Entre b="))
try:
c = ((a+b) / (a-b))
#Raising Error
if a==b:
raise ZeroDivisionError
#Handling of error
except ZeroDivisionError:
print ("a/b result in 0")
else:
print (c)
OUTPUT:
Entre a=4
Entre b=6
-5.0
RESULT:
Thus the exception handling program using python to depict the
divide by zero error was successfully executed and verified.
Ex.No.10(b) Python program for implementing
real-time/technical applications using
exception handling - Check voters eligibility
AIM:
To Write a exception handling program using python to depict the
voters eligibility.
ALGORITHM:
Step 1: Start the program.
Step 2: Read the input file which contains names and age by using
try catch exception handling method.
Step 3:To Check the age of the person. If the age is greater than
18 then write the name into voter list otherwise write the
name into non voter list.
Step 4: Stop the program.
PROGRAM:
def main():
try:
age=int(input("Enter your age"))
if age>18:
print("Eligible to vote")
else:
print("Not eligible to vote")
except:
print("age must be a valid number")
main()
OUTPUT:
Enter your age 43
Eligible to vote
RESULT:
Thus the exception handling program using python to depict the
voters eligibility was successfully executed and verified.
Ex.No.10(c) Python program for implementing
real-time/technical applications using
exception handling - student mark range validation
AIM:
To Implementing real-time/technical applications using exception
handling. Student mark range validation.
ALGORITHM:
Step 1: Start the program.
Step 2: By using function to get the input from the user.
Step 3: Using Exception handling in that cif statement can be used
to check the mark range in the program.
Step 4: Given data is not valid it will throw the IOexception in the
process.
Step 5: Stop the program.
PROGRAM:
def main():
try:
mark=int(input("enter your mark:"))
if mark>=35 and mark<101:
print("pass and your mark is valid")
else:
print("fail and your mark is valid")
except ValueError:
print("mark must be avalid number")
except IOError:
print("enter correct valid mark")
except:
print("An error occurred")
main()
OUTPUT:
enter your mark:65
pass and your mark is valid
RESULT:
Thus the real-time/technical applications using Exception handling.
Student mark range validation was successfully executed and verified.
EX.No.11 Developing a game activity using pygame
like bouncing ball
AIM:
To Write a python program to implement bouncing balls using
pygame tool.
ALGORITHM:
Step 1: Start the program
Step 2: The pygame.display.set_mode() function returns the
surface object for the window. This function accepts the
width and height of the screen as arguments.
Step 3: To set the caption of the window, call the
pygame.display.set_caption() function. Opened the image
using the pygame.image.load() method and set the ball
rectangle area boundary using the get_rect() method.
Step 4: The fill() method is used to fill the surface with a
background color.
Step 5: pygame flip() method to make all images visible.
Step 6: Stop the program.
PROGRAM:
import pygame
import sys
pygame.init()
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Bouncing Ball")
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
Sprite_Radius = 40
sprite_pos = [WIDTH // 2, HEIGHT // 2] # Starting position
sprite_Velocity = [18, 18] # Speed in x and y directions
BORDER_WIDTH = 30
border_rect = pygame.Rect(BORDER_WIDTH // 2, BORDER_WIDTH //
2, WIDTH - BORDER_WIDTH, HEIGHT - BORDER_WIDTH)
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
sprite_pos[0] += sprite_Velocity[0]
sprite_pos[1] += sprite_Velocity[1]
if sprite_pos[0] >= WIDTH- BORDER_WIDTH- Sprite_Radius or
sprite_pos[0] <= Sprite_Radius+BORDER_WIDTH:
sprite_Velocity[0] = -sprite_Velocity[0]
if sprite_pos[1] >= HEIGHT -BORDER_WIDTH- Sprite_Radius or
sprite_pos[1] <= Sprite_Radius + BORDER_WIDTH:
sprite_Velocity[1] = -sprite_Velocity[1]
screen.fill(WHITE)
pygame.draw.rect(screen,BLACK, border_rect, BORDER_WIDTH)
pygame.draw.circle(screen, BLACK, sprite_pos, Sprite_Radius+2)
pygame.draw.circle(screen, RED, sprite_pos, Sprite_Radius)
pygame.display.flip()
pygame.time.Clock().tick(60)
OUTPUT:
RESULT:
Thus the python program to implement bouncing balls using pygame
tool was executed successfully and verified.