SlideShare a Scribd company logo
1 of 75
Download to read offline
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Prepared by,
1. NITHIYA.K, AP/CSE
GE3171-PROBLEM SOLVING AND PYTHON
PROGRAMMING LABORATORY
LABORATORY
LAB MANUAL
(Regulation 2021)
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
LIST OF EXPERIMENTS:
COURSE OBJECTIVES:
􀁸 To understand the problem solving approaches.
􀁸 To learn the basic programming constructs in Python.
􀁸 To practice various computing strategies for Python-based solutions to real world
problems.
􀁸 To use Python data structures – lists, tuples, dictionaries.
􀁸 To do input/output with files in Python.
EXPERIMENTS:
SYLLABUS
GE3171 -PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY
Note: The examples suggested in each experiment are only indicative. The lab instructor is
expected to design other problems on similar lines. The Examination shall not be restricted
to the sample experiments listed here.
1. Identification and solving of simple real life or scientific or technical problems, and developing
flow charts for the same. (Electricity Billing, Retail shop billing, Sin series, weight of a
motorbike, Weight of a steel bar, compute Electrical Current in Three Phase AC Circuit, etc.)
2. Python programming using simple statements and expressions (exchange the values of two
variables, circulate the values of n variables, distance between two points).
3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns,
pyramid pattern)
4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a
library/Components of a car/ Materials required for construction of a building –operations of
list & tuples)
5. Implementing real-time/technical applications using Sets, Dictionaries. (Language,
components of an automobile, Elements of a civil structure, etc.- operations of Sets & Dictionaries)
6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape)
7. Implementing programs using Strings. (reverse, palindrome, character count, replacing
characters)
8. Implementing programs using written modules and Python Standard Libraries (pandas, numpy.
Matplotlib, scipy)
9. Implementing real-time/technical applications using File handling. (copy from one file to another, word
count, longest word)
10. Implementing real-time/technical applications using Exception handling. (divide by zero error,
voter’s age validity, student mark range validation)
11. Exploring Pygame tool.
12. Developing a game activity using Pygame like bouncing ball, car race etc.
TOTAL: 60 PERIODS
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
COURSE OUTCOMES:
On completion of the course, students will be able to:
CO1: Develop algorithmic solutions to simple computational problems
CO2: Develop and execute simple Python programs.
CO3: Implement programs in Python using conditionals and loops for solving problems.
CO4: Deploy functions to decompose a Python program.
CO5: Process compound data using Python data structures.
CO6: Utilize Python packages in developing software applications.
TEXT BOOKS: GE3171 Syllabus PROBLEM SOLVING AND PYTHON PROGRAMMING
LABORATORY
1. Allen B. Downey, “Think Python : How to Think like a Computer Scientist”, 2nd Edition, O’Reilly
Publishers, 2016.
2. Karl Beecher, “Computational Thinking: A Beginner’s Guide to Problem Solving and
Programming”, 1st Edition, BCS Learning & Development Limited, 2017.
REFERENCES:
1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021.
2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and
Data Scientists”, 1st Edition, Notion Press, 2021.
3. John V Guttag, “Introduction to Computation and Programming Using Python: With Applications
to Computational Modeling and Understanding Data‘‘, Third Edition, MIT Press, 2021
4. Eric Matthes, “Python Crash Course, A Hands – on Project Based Introduction to Programming”,
2nd Edition, No Starch Press, 2019.
5. https://www.python.org/
6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.1 Identification and solving of simple real life or scientific or technical problems,
and developing flow charts for the same
DATE:
a) Electricity Billing
Aim:
To Develop a flow chart and write the program for Electricity billing
Procedure:
From Unit To Unit Rate (Rs.) Prices
From Unit To Unit Rate (Rs.) Max.Unit
1 100 0 100
101 200 2 200
201 500 3 500-
- 101 -200 3.5 >500
201-500 4.6 >500
>500 606 >500
1b) Reatil Shop billing
Flow-Chart:
1c) Sin series
Flow Chart:
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
1d) To compute Electrical Current in Three Phase AC Circuit
Result :
Thus the flowchart of electric bill ,sine series was successfully verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO 2.a
Python Programming Using Simple Statements And Expressions -
Exchange The Values Of Two Variables)
DATE:
AIM:
Write a python program to exchange the values of two variables
PROCEDURE:
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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.2b Python Programming Using Simple Statements And Expressions - Circulate The
Values Of N Variables
DATE:
AIM:
Write a python program to circulate the values of n variables
PROCEDURE:
Step1: Circulate the values of n variables.
Step2: 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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
n = int(input("Enter number of values : "))
list1 = []
for val in range(0,n,1):
ele = int(input("Enter integer : "))
list1.append(ele)
print("Circulating the elements of list ", list1)
for val in range(0,n,1):
ele = list1.pop(0)
list1.append(ele)
print(list1)
OUTPUT:
Enter number of values : 4
Enter integer : 87
Enter integer : 58
Enter integer : 98
Enter integer : 52
Circulating the elements of list [87, 58, 98, 52]
[58, 98, 52, 87]
[98, 52, 87, 58]
[52, 87, 58, 98]
[87, 58, 98, 52]
RESULT:
Thus the python program to circulate the values of n variables was executed successfully and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
XPT.NO.2.C
Python Programming Using Simple Statements And
Expressions ( Calculate The Distance Between Two
Points)
DATE:
AIM:
Write a python program to calculate the distance between two numbers
PROCEDURE:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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=34
enter the value of x2=56
enter the value of y1=34
enter the value of y2=54
29.732137494637012
RESULT:
Thus the distance between of two points was successfully executed and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.3 (a) Scientific problems using Conditionals and Iterative loops.- Number
series
DATE:
AIM:
Write a Python program with conditional and iterative statements for Number Series.
PROCEDURE:
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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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 patterns is executed and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.3B
DATE:
Scientific Problems Using Conditionals And Iterative Loops. –Number
Patterns
AIM:
Write a Python program with conditional and iterative statements for Number Pattern.
PROCEDURE:
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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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=7
1
2 2
3 3 3
4 4 4 4
5 5 5 5 5
6 6 6 6 6 6
RESULT:
Thus the python program to print numbers patterns is executed and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.3 c
Scientific Problems Using Conditionals And Iterative Loops. -Pyramid
DATE:
AIM:
Write a Python program with conditional and iterative statements for Pyramid Pattern.
PROCEDURE:
Step 1: Start the program
Step 2: Read 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 = 0 to rows ;
Step 6: Set j in inner loop using range function, j=0 to i+1;
Step 7: Print * 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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
Program:
def pypart(n):
for i in range(0, n):
for j in range(0, i+1):
print(“*”,end=” “)
print(“r”)
O/P:
enter the no. of rows 5
*
* *
* * *
* * * *
* * * * *
RESULT:
Thus the python program to print numbers pyramid patterns is executed and verified.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.4(a)
Implementing Real-Time/Technical Applications Using Lists, Tuples
-Items Present InA Library)
DATE:
AIM :
To Write a python program to implement items present in a library
PROCEDURE:
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 tupel
STEP 4:To print the result using output statement
STEP 5: Stop the program
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
library=["books", "author", "barcodenumber" , "price"]
library[0]="ramayanam"
print(library[0])
library[1]="valmiki"
library[2]=123987
library[3]=234
print(library)
Tuple:
tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
# tup1[0] = 100 ------- Not assigned in tuple
# So let's create a new tuple as follows
tup3 = tup1 + tup2;
print(tup3)
TUPLE:
tup1 = (12134,250000 )
tup2 = ('books', 'totalprice')
# tup1[0] = 100 ------- Not assigned in tuple # So let's create a new tuple as follows
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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.4 b Implementing Real-Time/Technical Applications Using Lists, Tuples -Components
Of a Car
DATE:
AIM:
To Write a python program to implement components of a car
PROCEDURE:
STEP 1: Start the program
STEP 2: Create the variable inside that variable assigned the list of elements based on the car
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"] new_list = []
for i in cars:
if "M" in i:
new_list.append(i)
print(new_list)
TUPLE:
cars=("Ferrari", "BMW", "Audi", "Jaguar") print(cars)
print(cars[0])
print(cars[1])
print(cars[3])
print(cars[3])
print(cars[4])
OUTPUT:
LIST:
['Mercedes Benz', 'Maserati', 'Maruti Suzuki']
TUPLE:
('Ferrari', 'BMW', 'Audi', 'Jaguar')
Ferrari
BMW
Jaguar
Jaguar
RESULT:
Thus the Python Program is executed successfully and the output is verified.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.4 C Implementing Real-Time/Technical Applications Using Lists, Tuples - Materials Required
For Construction Of A Building.
DATE:
AIM:
To Write a python program to implement materials required for construction of building
PROCEDURE:
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 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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
materials= ["cementbags", "bricks", "sand", "Steelbars", "Paint"]
materials.append(“ Tiles”)
materials.insert(3,"Aggregates")
materials.remove("sand")
materials[5]="electrical"
print(materials)
TUPLE:
materials = ("cementbags", "bricks", "sand", "Steelbars", "Paint")
print(materials)
print ("list of element is=",materials)
print ("materials[0]:", materials [0])
print ("materials[1:3]:", materials [1:3])
OUTPUT:
LIST:
['cementbags', 'bricks', 'Aggregates', 'Steelbars', 'Paint', 'electrical']
TUPLE:
('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint')
list of element is= ('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint')
materials[0]: cementbags
materials[1:3]: ('bricks', 'sand')
RESULT:
Thus the Python Program is executed successfully and the output is verified.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 5 Implementing Real-Time/Technical Applications Using Sets, Dictionaries. –
Components Of An Automobile
DATE:
AIM:
To write a python program to implement Components of an automobile using
Sets and Dictionaries
PROCEDURE:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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= {'BMW', 'Mercedes', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda'}
==========
Approach #2
Car name = BMW
Car name = Mercedes
Car name = Toyota
Car name = Audi
Car name = Ferrari
Car name = Tesla
Car name = Honda
==========
New cars set = {'BMW', 'Mercedes', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda',
'Tata'}
discard() method = {'BMW', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda', 'Tata'}
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
DICTIONARY
PROGRAM:
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Adding elements one at a time
Dict[0] = 'BRICKS'
Dict[2] = 'CEMENT'
Dict[3] = BLUE PRINT
print("nDictionary after adding 3 elements: ")
print(Dict)
# Adding set of values
# to a single Key
Dict['Value_set'] = 2, 3, 4
print("nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[2] = 'STEEL'
print("nUpdated key value: ")
print(Dict)
# Adding Nested Key value to Dictionary
Dict[5] = {'Nested': {'1': 'LIME', '2': 'SAND'}}
print("nAdding a Nested Key: ")
print(Dict)
OUTPUT
Empty Dictionary:
{}
Dictionary after adding 3 elements:
{0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE_PRINT'}
Dictionary after adding 3 elements: {0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4)}
Updated key value:
{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4)}
Adding a Nested Key:
{0: 'BRICKS', 2: 'STEEL', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'LIME', '2':
'SAND'}}}
>
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
RESULT:
Thus the program was executed successfully and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
AIM:
To Write a Python function to calculate the factorial of a number
PROCEDURE:
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
EXPT.NO 6 (A)
Implementing Factorial Programs Using Functions.
DATE:
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO 6 B Implementing Program Largest Number In A List Using Function
DATE:
AIM:
To Write a Python program to get the largest number from a list.
PROCEDURE:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.6 (C) Implementing Programs Using Functions – Area Of Shape
DATE
AIM:
To Write a python program to implement area of shape using functions
PROCEDURE:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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(f"The area of rectangle is{rect_area}.")
elif name == "square":
s = int(input("Enter square's side length: "))
sqt_area = s * s
print(f"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(f"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(f"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: "))
# calculate area of parallelogram
para_area = b * h
print(f"The area of parallelogram is{para_area}.")
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
else:
print("Sorry! This shape is not available")
if __name__ == "__main__" :
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.7 (A) Implementing programs using Strings –Reverse
DATE
AIM:
To Write a python program to implement reverse of a string using string functions
PROCEDURE:
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
Step4: to print the reverse string value by Using reverse method function
Step5: print the result
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
def reverse(string):
string = string[::-1]
return string
s = "Firstyearece"
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 : Firstyearece
The reversed string(using extended slice syntax) is : eceraeytsriF
RESULT:
Thus the reverse of a string function python program was executed and successfully
verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO.7 (B)
Implementing Programs Using Strings -Palindrome
DATE:
AIM:
To write a python program to implement palindrome using string functions
PROCEDURE:
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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
def is Palindrome(s):
return s == s[::-1]
# Driver code
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 a string:madam
The string is a palindrome
RESULT:
Thus the program of palindrome by using function in python executed successfully and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 7 (C)
Implementing programs using Strings - character count
DATE:
AIM:
To Write a python program to implement Characters count using string functions
PROCEDURE:
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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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 : ANJALAI AMMAL MAHALINGAM COLLEGE
Total number of characters : 29
RESULT:
Thus the program of character count in string in python was executed successfully and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
AIM:
To write a python program to implement Replacing Characters using string functions
PROCEDURE:
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.
EXPT.NO: 7 (d)
Implementing programs using Strings – Replacing
Characters
DATE:
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM
string = "Welcome to python programming"
print(string.replace("to", "our"))
print(string.replace("ek", "a", 3))
OUTPUT:
Welcome our python programming
Welcome to python praramming
RESULT:
Thus the program was executed and successfully verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
AIM:
To write a python program to implement pandas modules. Pandas are
denote python data structures.
PROCEDURE:
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 4: python method of DataFrame has data aligned in rows and columns
like the SQL table or a spreadsheet database
Step 3: using Series: It is a 1-D size-immutable array like structure
having homogeneous data in a python module
Step 4:using max function method to display the maximum ages in a program
Step 4:List of elements can be displayed by using output statement in pandas.
Step 5: stop the program
EXPT.NO: 8 (a)
Implementing programs using written modules and
Python Standard Libraries–pandas
DATE:
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
In command prompt install this package: pip install pandas
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())
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
AIM:
To Write a python program to implement numpy module in python .
Numerical python are mathematical calculations are solved here.
PROCEDURE:
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
EXPT.NO: 8(b)
Implementing programs using written modules and
Python Standard Libraries– numpy
DATE:
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
In command prompt install this package-pip install numpy
import numpy as np
a = np.arange(6)
a2 = a[np.newaxis, :]
a2.shape
#Array Creation and functions:
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 Dimensions:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
AIM:
To write a python program to implement matplotolib module in python. .Matplotlib
python are used to show the visualization entities in python.
PROCEDURE:
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
EXPT.NO: 8(c)
Implementing programs using written modules and
Python Standard Libraries–matplotlib
DATE:
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
In command prompt install this package: pip install matplotlib
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()
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
OUTPUT:
PROGRAM 2:
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('_mpl-gallery')
x = np.linspace(0, 10, 100)
y = 4 + 2 * np.sin(2 * x)
fig, ax = plt.subplots()
ax.plot(x, y, linewidth=2.0)
ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8))
plt.show(
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 8 (d)
Implementing programs using written modules and Python Standard
Libraries– scipy
DATE:
AIM:
Write a python program to implement scipy module in python. .Scipy python
are used to solve the scientific calculations
PROCEDURE:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 9 (a)
Implementing real-time/technical applications using File handling -
copy from one file to another
DATE:
AIM:
To Write a python program to implement File Copying
PROCEDURE:
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:UsersAdministratorDesktopAAMEC2 (2)bookk.csv
Where the CSV file name is „products„ and the file extension is csv.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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:UsersAdministratorDesktop bookk.csv
Step 3: Copy the file in Python using shutil.copyfile
import shutil
original = r'C:UsersAdministratorDesktopAAMEC2(2)bookk.csv'
target = r'C:UsersAdministratorDesktopAAMEC2bookk.csv'
shutil.copyfile(original, target) shutil.copyfile(original, target)
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
RESULT:
Thus the a python program to implement File Copying was successfully executed
and verified .
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 9 (b)
Implementing real-time/technical applications using File handling
word count
DATE:
AIM:
To Write a python program to implement word count in File operations in python
PROCEDURE:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
file =open(r"C:UsersAdministratorDesktopcount2.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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 9 (c)
Implementing real-time/technical applications using File handling -
Longest word
DATE:
AIM:
To Write a python program to implement longest word in File operations
PROCEDURE:
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 longest of word in a file.
step 4: To display the longest word in a target file
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 10 (a)
Implementing real-time/technical applications using Exception
handling.- divide by zero error.
DATE:
AIM:
To Write a exception handling program using python to depict the divide by zero
error.
PROCEDURE:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
(i) marks = 10000
a = marks / 0
print(a)
output: ZeroDivisionError: division by zero
program
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 10 (b)
Implementing real-time/technical applications using Exception
handling.- Check voters eligibility
DATE:
AIM:
To Write a exception handling program using python to depict the voters eligibility
PROCEDURE:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
program:
def main():
#get the age
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 age43
Eligible to vote
RESULT:
Thus the exception handling program using python to depict the voters eligibility
was successfully executed and verified.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 10 (c)
Implementing real-time/technical applications using Exception
handling.- student mark range validation
DATE:
AIM:
To Implementing real-time/technical applications using Exception handling.- student mark
range validation
PROCEDURE:
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
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 69
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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 11
Exploring Pygame tool.
DATE:
AIM:
To Write a python program to implement pygame
PROCEDURE:
step 1: start the program
step 2: when Key presses, mouse movements, and even joystick movements are
some of the ways in which a user can provide input
step 3: To sets up a control variable for the game loop. To exit the loop and the
game, you set running = False. The game loop starts on line 29.
step 4: starts the event handler, walking through every event currently in the event
queue. If there are no events, then the list is empty, and the handler won’t do
anything.
step 5:check if the current event.type is a KEYDOWN event. If it is, then the
program checks which key was pressed by looking at the event.key attribute. If the
key is the Esc key, indicated by K_ESCAPE, then it exits the game loop by setting
running = False.
step 6: do a similar check for the event type called QUIT. This event only occurs
when the user clicks the window close button. The user may also use any other
operating system action to close the window.
step 7:The window won’t disappear until you press the Esc key, or otherwise trigger
a QUIT event by closing the window.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
import pygame
from pygame.locals import *
class Square(pygame.sprite.Sprite):
def __init__(self):
super(Square, self).__init__()
self.surf = pygame.Surface((25, 25))
self.surf.fill((0, 200, 255))
self.rect = self.surf.get_rect()
pygame.init()
screen = pygame.display.set_mode((800, 600))
square1 = Square()
square2 = Square()
square3 = Square()
square4 = Square()
gameOn = True
while gameOn:
for event in pygame.event.get():
if event.type == KEYDOWN:
if event.key == K_BACKSPACE:
gameOn = False
elif event.type == QUIT:
gameOn = False
screen.blit(square1.surf, (40, 40))
screen.blit(square2.surf, (40, 530))
screen.blit(square3.surf, (730, 40))
screen.blit(square4.surf, (730, 530))
pygame.display.flip()
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
OUTPUT
RESULT:
Thus the python program to implement pygame was successfully executed and
verified.
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
EXPT.NO: 12
Developing a game activity using Pygame like bouncing ball
DATE:
AIM:
To Write a python program to implement bouncing balls using pygame tool
PROCEDURE:
Step1: 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
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
PROGRAM:
import sys, pygame
pygame.init()
size = width, height = 800, 400
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing ball")
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
OUTPUT:
RESULT:
Thus the python program to implement bouncing balls using pygame tool was
executed successfully and verified
ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE
ALL THE BEST …!

More Related Content

What's hot

Operator Overloading
Operator OverloadingOperator Overloading
Operator OverloadingNilesh Dalvi
 
summer training report on python
summer training report on pythonsummer training report on python
summer training report on pythonShubham Yadav
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming pptismailmrribi
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python pptPriyanka Pradhan
 
Templates in C++
Templates in C++Templates in C++
Templates in C++Tech_MX
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception HandlingMegha V
 
Huffman Coding Algorithm Presentation
Huffman Coding Algorithm PresentationHuffman Coding Algorithm Presentation
Huffman Coding Algorithm PresentationAkm Monir
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaEdureka!
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in pythoneShikshak
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overridingRajab Ali
 

What's hot (20)

Operator Overloading
Operator OverloadingOperator Overloading
Operator Overloading
 
summer training report on python
summer training report on pythonsummer training report on python
summer training report on python
 
Loops c++
Loops c++Loops c++
Loops c++
 
C tokens
C tokensC tokens
C tokens
 
Python programming : Control statements
Python programming : Control statementsPython programming : Control statements
Python programming : Control statements
 
Python Programming ppt
Python Programming pptPython Programming ppt
Python Programming ppt
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Function in C program
Function in C programFunction in C program
Function in C program
 
Strings in C
Strings in CStrings in C
Strings in C
 
Intro to Python
Intro to PythonIntro to Python
Intro to Python
 
programming with python ppt
programming with python pptprogramming with python ppt
programming with python ppt
 
Templates in C++
Templates in C++Templates in C++
Templates in C++
 
Python Exception Handling
Python Exception HandlingPython Exception Handling
Python Exception Handling
 
C by balaguruswami - e.balagurusamy
C   by balaguruswami - e.balagurusamyC   by balaguruswami - e.balagurusamy
C by balaguruswami - e.balagurusamy
 
Introduction to Python
Introduction to Python  Introduction to Python
Introduction to Python
 
Huffman Coding Algorithm Presentation
Huffman Coding Algorithm PresentationHuffman Coding Algorithm Presentation
Huffman Coding Algorithm Presentation
 
Introduction to Compiler design
Introduction to Compiler design Introduction to Compiler design
Introduction to Compiler design
 
Date and Time Module in Python | Edureka
Date and Time Module in Python | EdurekaDate and Time Module in Python | Edureka
Date and Time Module in Python | Edureka
 
Datatypes in python
Datatypes in pythonDatatypes in python
Datatypes in python
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 

Similar to Anthropic Python Lab Manual

CBCS 2018 Scheme I sem Lab Manual for 18CPL17
CBCS 2018 Scheme I sem Lab Manual for 18CPL17 CBCS 2018 Scheme I sem Lab Manual for 18CPL17
CBCS 2018 Scheme I sem Lab Manual for 18CPL17 manjurkts
 
C Programming Lab manual 18CPL17
C Programming Lab manual 18CPL17C Programming Lab manual 18CPL17
C Programming Lab manual 18CPL17manjurkts
 
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxAASTHA76
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning materialArthyR3
 
Monte Carlo Simulation for project estimates v1.0
Monte Carlo Simulation for project estimates v1.0Monte Carlo Simulation for project estimates v1.0
Monte Carlo Simulation for project estimates v1.0PMILebanonChapter
 
Problem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialProblem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialTo Sum It Up
 
complexity analysis.pdf
complexity analysis.pdfcomplexity analysis.pdf
complexity analysis.pdfpasinduneshan
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016Ankit Dubey
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016Ankit Dubey
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016Ankit Dubey
 
c++ exp 1 Suraj...pdf
c++ exp 1 Suraj...pdfc++ exp 1 Suraj...pdf
c++ exp 1 Suraj...pdfayush616992
 
Introduction to computing Processing and performance.pdf
Introduction to computing Processing and performance.pdfIntroduction to computing Processing and performance.pdf
Introduction to computing Processing and performance.pdfTulasiramKandula1
 

Similar to Anthropic Python Lab Manual (20)

CBCS 2018 Scheme I sem Lab Manual for 18CPL17
CBCS 2018 Scheme I sem Lab Manual for 18CPL17 CBCS 2018 Scheme I sem Lab Manual for 18CPL17
CBCS 2018 Scheme I sem Lab Manual for 18CPL17
 
C Programming Lab manual 18CPL17
C Programming Lab manual 18CPL17C Programming Lab manual 18CPL17
C Programming Lab manual 18CPL17
 
Cp manual final
Cp manual finalCp manual final
Cp manual final
 
LMmanual.pdf
LMmanual.pdfLMmanual.pdf
LMmanual.pdf
 
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docxBottom of FormCreate your own FunctionFunctionsFor eac.docx
Bottom of FormCreate your own FunctionFunctionsFor eac.docx
 
Looping
LoopingLooping
Looping
 
Java conceptual learning material
Java conceptual learning materialJava conceptual learning material
Java conceptual learning material
 
Monte Carlo Simulation for project estimates v1.0
Monte Carlo Simulation for project estimates v1.0Monte Carlo Simulation for project estimates v1.0
Monte Carlo Simulation for project estimates v1.0
 
Lecture 7.pptx
Lecture 7.pptxLecture 7.pptx
Lecture 7.pptx
 
A01
A01A01
A01
 
chapter 1
chapter 1chapter 1
chapter 1
 
Problem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study materialProblem solving using computers - Unit 1 - Study material
Problem solving using computers - Unit 1 - Study material
 
complexity analysis.pdf
complexity analysis.pdfcomplexity analysis.pdf
complexity analysis.pdf
 
Cse cpl manual-2016
Cse cpl manual-2016Cse cpl manual-2016
Cse cpl manual-2016
 
UNIT-2-PPTS-DAA.ppt
UNIT-2-PPTS-DAA.pptUNIT-2-PPTS-DAA.ppt
UNIT-2-PPTS-DAA.ppt
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
Fy secondsemester2016
Fy secondsemester2016Fy secondsemester2016
Fy secondsemester2016
 
c++ exp 1 Suraj...pdf
c++ exp 1 Suraj...pdfc++ exp 1 Suraj...pdf
c++ exp 1 Suraj...pdf
 
Introduction to computing Processing and performance.pdf
Introduction to computing Processing and performance.pdfIntroduction to computing Processing and performance.pdf
Introduction to computing Processing and performance.pdf
 

More from ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE (8)

BIGDATA ANALYTICS LAB MANUAL final.pdf
BIGDATA  ANALYTICS LAB MANUAL final.pdfBIGDATA  ANALYTICS LAB MANUAL final.pdf
BIGDATA ANALYTICS LAB MANUAL final.pdf
 
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING-UNIT I
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING-UNIT IGE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING-UNIT I
GE8151-PROBLEM SOLVING AND PYTHON PROGRAMMING-UNIT I
 
IT6701-Information management question bank
IT6701-Information management question bankIT6701-Information management question bank
IT6701-Information management question bank
 
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT IIC PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
C PROGRAMMING BASICS- COMPUTER PROGRAMMING UNIT II
 
Unit ii ppt
Unit ii pptUnit ii ppt
Unit ii ppt
 
STUDY EDUCATIONAL OPERATING SYSTEM MINIX OPERATING SYSTEM AND DEVELOP REASO...
STUDY  EDUCATIONAL OPERATING  SYSTEM MINIX OPERATING SYSTEM AND DEVELOP REASO...STUDY  EDUCATIONAL OPERATING  SYSTEM MINIX OPERATING SYSTEM AND DEVELOP REASO...
STUDY EDUCATIONAL OPERATING SYSTEM MINIX OPERATING SYSTEM AND DEVELOP REASO...
 
Using fuzzy ant colony optimization for Diagnosis of Diabetes Disease
Using fuzzy ant colony optimization for Diagnosis of Diabetes DiseaseUsing fuzzy ant colony optimization for Diagnosis of Diabetes Disease
Using fuzzy ant colony optimization for Diagnosis of Diabetes Disease
 
Wireless sensor networks
Wireless sensor networksWireless sensor networks
Wireless sensor networks
 

Recently uploaded

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)lakshayb543
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfTechSoup
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONHumphrey A Beña
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parentsnavabharathschool99
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operationalssuser3e220a
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxHumphrey A Beña
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Mark Reed
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxAnupkumar Sharma
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxVanesaIglesias10
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...JojoEDelaCruz
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptshraddhaparab530
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptxmary850239
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxlancelewisportillo
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management systemChristalin Nelson
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptxiammrhaywood
 

Recently uploaded (20)

Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
Visit to a blind student's school🧑‍🦯🧑‍🦯(community medicine)
 
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptxFINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
FINALS_OF_LEFT_ON_C'N_EL_DORADO_2024.pptx
 
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdfInclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
Inclusivity Essentials_ Creating Accessible Websites for Nonprofits .pdf
 
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATIONTHEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
THEORIES OF ORGANIZATION-PUBLIC ADMINISTRATION
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Choosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for ParentsChoosing the Right CBSE School A Comprehensive Guide for Parents
Choosing the Right CBSE School A Comprehensive Guide for Parents
 
Expanded definition: technical and operational
Expanded definition: technical and operationalExpanded definition: technical and operational
Expanded definition: technical and operational
 
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptxINTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
INTRODUCTION TO CATHOLIC CHRISTOLOGY.pptx
 
Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)Influencing policy (training slides from Fast Track Impact)
Influencing policy (training slides from Fast Track Impact)
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptxMULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
MULTIDISCIPLINRY NATURE OF THE ENVIRONMENTAL STUDIES.pptx
 
ROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptxROLES IN A STAGE PRODUCTION in arts.pptx
ROLES IN A STAGE PRODUCTION in arts.pptx
 
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
ENG 5 Q4 WEEk 1 DAY 1 Restate sentences heard in one’s own words. Use appropr...
 
Integumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.pptIntegumentary System SMP B. Pharm Sem I.ppt
Integumentary System SMP B. Pharm Sem I.ppt
 
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptxYOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
YOUVE GOT EMAIL_FINALS_EL_DORADO_2024.pptx
 
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptxLEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
LEFT_ON_C'N_ PRELIMS_EL_DORADO_2024.pptx
 
4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx4.18.24 Movement Legacies, Reflection, and Review.pptx
4.18.24 Movement Legacies, Reflection, and Review.pptx
 
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptxQ4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
Q4-PPT-Music9_Lesson-1-Romantic-Opera.pptx
 
Concurrency Control in Database Management system
Concurrency Control in Database Management systemConcurrency Control in Database Management system
Concurrency Control in Database Management system
 
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptxAUDIENCE THEORY -CULTIVATION THEORY -  GERBNER.pptx
AUDIENCE THEORY -CULTIVATION THEORY - GERBNER.pptx
 

Anthropic Python Lab Manual

  • 1. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Prepared by, 1. NITHIYA.K, AP/CSE GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY LABORATORY LAB MANUAL (Regulation 2021)
  • 2. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE LIST OF EXPERIMENTS: COURSE OBJECTIVES: 􀁸 To understand the problem solving approaches. 􀁸 To learn the basic programming constructs in Python. 􀁸 To practice various computing strategies for Python-based solutions to real world problems. 􀁸 To use Python data structures – lists, tuples, dictionaries. 􀁸 To do input/output with files in Python. EXPERIMENTS: SYLLABUS GE3171 -PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY Note: The examples suggested in each experiment are only indicative. The lab instructor is expected to design other problems on similar lines. The Examination shall not be restricted to the sample experiments listed here. 1. Identification and solving of simple real life or scientific or technical problems, and developing flow charts for the same. (Electricity Billing, Retail shop billing, Sin series, weight of a motorbike, Weight of a steel bar, compute Electrical Current in Three Phase AC Circuit, etc.) 2. Python programming using simple statements and expressions (exchange the values of two variables, circulate the values of n variables, distance between two points). 3. Scientific problems using Conditionals and Iterative loops. (Number series, Number Patterns, pyramid pattern) 4. Implementing real-time/technical applications using Lists, Tuples. (Items present in a library/Components of a car/ Materials required for construction of a building –operations of list & tuples) 5. Implementing real-time/technical applications using Sets, Dictionaries. (Language, components of an automobile, Elements of a civil structure, etc.- operations of Sets & Dictionaries) 6. Implementing programs using Functions. (Factorial, largest number in a list, area of shape) 7. Implementing programs using Strings. (reverse, palindrome, character count, replacing characters) 8. Implementing programs using written modules and Python Standard Libraries (pandas, numpy. Matplotlib, scipy) 9. Implementing real-time/technical applications using File handling. (copy from one file to another, word count, longest word) 10. Implementing real-time/technical applications using Exception handling. (divide by zero error, voter’s age validity, student mark range validation) 11. Exploring Pygame tool. 12. Developing a game activity using Pygame like bouncing ball, car race etc. TOTAL: 60 PERIODS
  • 3. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE COURSE OUTCOMES: On completion of the course, students will be able to: CO1: Develop algorithmic solutions to simple computational problems CO2: Develop and execute simple Python programs. CO3: Implement programs in Python using conditionals and loops for solving problems. CO4: Deploy functions to decompose a Python program. CO5: Process compound data using Python data structures. CO6: Utilize Python packages in developing software applications. TEXT BOOKS: GE3171 Syllabus PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY 1. Allen B. Downey, “Think Python : How to Think like a Computer Scientist”, 2nd Edition, O’Reilly Publishers, 2016. 2. Karl Beecher, “Computational Thinking: A Beginner’s Guide to Problem Solving and Programming”, 1st Edition, BCS Learning & Development Limited, 2017. REFERENCES: 1. Paul Deitel and Harvey Deitel, “Python for Programmers”, Pearson Education, 1st Edition, 2021. 2. G Venkatesh and Madhavan Mukund, “Computational Thinking: A Primer for Programmers and Data Scientists”, 1st Edition, Notion Press, 2021. 3. John V Guttag, “Introduction to Computation and Programming Using Python: With Applications to Computational Modeling and Understanding Data‘‘, Third Edition, MIT Press, 2021 4. Eric Matthes, “Python Crash Course, A Hands – on Project Based Introduction to Programming”, 2nd Edition, No Starch Press, 2019. 5. https://www.python.org/ 6. Martin C. Brown, “Python: The Complete Reference”, 4th Edition, Mc-Graw Hill, 2018.
  • 4. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.1 Identification and solving of simple real life or scientific or technical problems, and developing flow charts for the same DATE: a) Electricity Billing Aim: To Develop a flow chart and write the program for Electricity billing Procedure: From Unit To Unit Rate (Rs.) Prices From Unit To Unit Rate (Rs.) Max.Unit 1 100 0 100 101 200 2 200 201 500 3 500- - 101 -200 3.5 >500 201-500 4.6 >500 >500 606 >500 1b) Reatil Shop billing Flow-Chart:
  • 6. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 1d) To compute Electrical Current in Three Phase AC Circuit Result : Thus the flowchart of electric bill ,sine series was successfully verified
  • 7. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO 2.a Python Programming Using Simple Statements And Expressions - Exchange The Values Of Two Variables) DATE: AIM: Write a python program to exchange the values of two variables PROCEDURE: 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
  • 8. 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.
  • 9. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.2b Python Programming Using Simple Statements And Expressions - Circulate The Values Of N Variables DATE: AIM: Write a python program to circulate the values of n variables PROCEDURE: Step1: Circulate the values of n variables. Step2: 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
  • 10. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: n = int(input("Enter number of values : ")) list1 = [] for val in range(0,n,1): ele = int(input("Enter integer : ")) list1.append(ele) print("Circulating the elements of list ", list1) for val in range(0,n,1): ele = list1.pop(0) list1.append(ele) print(list1) OUTPUT: Enter number of values : 4 Enter integer : 87 Enter integer : 58 Enter integer : 98 Enter integer : 52 Circulating the elements of list [87, 58, 98, 52] [58, 98, 52, 87] [98, 52, 87, 58] [52, 87, 58, 98] [87, 58, 98, 52] RESULT: Thus the python program to circulate the values of n variables was executed successfully and verified
  • 11. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE XPT.NO.2.C Python Programming Using Simple Statements And Expressions ( Calculate The Distance Between Two Points) DATE: AIM: Write a python program to calculate the distance between two numbers PROCEDURE: 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
  • 12. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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=34 enter the value of x2=56 enter the value of y1=34 enter the value of y2=54 29.732137494637012 RESULT: Thus the distance between of two points was successfully executed and verified
  • 13. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.3 (a) Scientific problems using Conditionals and Iterative loops.- Number series DATE: AIM: Write a Python program with conditional and iterative statements for Number Series. PROCEDURE: 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.
  • 14. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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 patterns is executed and verified
  • 15. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.3B DATE: Scientific Problems Using Conditionals And Iterative Loops. –Number Patterns AIM: Write a Python program with conditional and iterative statements for Number Pattern. PROCEDURE: 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.
  • 16. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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=7 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 6 6 6 6 6 6 RESULT: Thus the python program to print numbers patterns is executed and verified
  • 17. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.3 c Scientific Problems Using Conditionals And Iterative Loops. -Pyramid DATE: AIM: Write a Python program with conditional and iterative statements for Pyramid Pattern. PROCEDURE: Step 1: Start the program Step 2: Read 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 = 0 to rows ; Step 6: Set j in inner loop using range function, j=0 to i+1; Step 7: Print * 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.
  • 18. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE Program: def pypart(n): for i in range(0, n): for j in range(0, i+1): print(“*”,end=” “) print(“r”) O/P: enter the no. of rows 5 * * * * * * * * * * * * * * * RESULT: Thus the python program to print numbers pyramid patterns is executed and verified.
  • 19. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.4(a) Implementing Real-Time/Technical Applications Using Lists, Tuples -Items Present InA Library) DATE: AIM : To Write a python program to implement items present in a library PROCEDURE: 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 tupel STEP 4:To print the result using output statement STEP 5: Stop the program
  • 20. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: library=["books", "author", "barcodenumber" , "price"] library[0]="ramayanam" print(library[0]) library[1]="valmiki" library[2]=123987 library[3]=234 print(library) Tuple: tup1 = (12134,250000 ) tup2 = ('books', 'totalprice') # tup1[0] = 100 ------- Not assigned in tuple # So let's create a new tuple as follows tup3 = tup1 + tup2; print(tup3) TUPLE: tup1 = (12134,250000 ) tup2 = ('books', 'totalprice') # tup1[0] = 100 ------- Not assigned in tuple # So let's create a new tuple as follows 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.
  • 21. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.4 b Implementing Real-Time/Technical Applications Using Lists, Tuples -Components Of a Car DATE: AIM: To Write a python program to implement components of a car PROCEDURE: STEP 1: Start the program STEP 2: Create the variable inside that variable assigned the list of elements based on the car 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
  • 22. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: cars = ["Nissan", "Mercedes Benz", "Ferrari", "Maserati", "Jeep", "Maruti Suzuki"] new_list = [] for i in cars: if "M" in i: new_list.append(i) print(new_list) TUPLE: cars=("Ferrari", "BMW", "Audi", "Jaguar") print(cars) print(cars[0]) print(cars[1]) print(cars[3]) print(cars[3]) print(cars[4]) OUTPUT: LIST: ['Mercedes Benz', 'Maserati', 'Maruti Suzuki'] TUPLE: ('Ferrari', 'BMW', 'Audi', 'Jaguar') Ferrari BMW Jaguar Jaguar RESULT: Thus the Python Program is executed successfully and the output is verified.
  • 23. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.4 C Implementing Real-Time/Technical Applications Using Lists, Tuples - Materials Required For Construction Of A Building. DATE: AIM: To Write a python program to implement materials required for construction of building PROCEDURE: 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 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
  • 24. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: materials= ["cementbags", "bricks", "sand", "Steelbars", "Paint"] materials.append(“ Tiles”) materials.insert(3,"Aggregates") materials.remove("sand") materials[5]="electrical" print(materials) TUPLE: materials = ("cementbags", "bricks", "sand", "Steelbars", "Paint") print(materials) print ("list of element is=",materials) print ("materials[0]:", materials [0]) print ("materials[1:3]:", materials [1:3]) OUTPUT: LIST: ['cementbags', 'bricks', 'Aggregates', 'Steelbars', 'Paint', 'electrical'] TUPLE: ('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint') list of element is= ('cementbags', 'bricks', 'sand', 'Steelbars', 'Paint') materials[0]: cementbags materials[1:3]: ('bricks', 'sand') RESULT: Thus the Python Program is executed successfully and the output is verified.
  • 25. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 5 Implementing Real-Time/Technical Applications Using Sets, Dictionaries. – Components Of An Automobile DATE: AIM: To write a python program to implement Components of an automobile using Sets and Dictionaries PROCEDURE: 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
  • 26. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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= {'BMW', 'Mercedes', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda'} ========== Approach #2 Car name = BMW Car name = Mercedes Car name = Toyota Car name = Audi Car name = Ferrari Car name = Tesla Car name = Honda ========== New cars set = {'BMW', 'Mercedes', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda', 'Tata'} discard() method = {'BMW', 'Toyota', 'Audi', 'Ferrari', 'Tesla', 'Honda', 'Tata'}
  • 27. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE DICTIONARY PROGRAM: Dict = {} print("Empty Dictionary: ") print(Dict) # Adding elements one at a time Dict[0] = 'BRICKS' Dict[2] = 'CEMENT' Dict[3] = BLUE PRINT print("nDictionary after adding 3 elements: ") print(Dict) # Adding set of values # to a single Key Dict['Value_set'] = 2, 3, 4 print("nDictionary after adding 3 elements: ") print(Dict) # Updating existing Key's Value Dict[2] = 'STEEL' print("nUpdated key value: ") print(Dict) # Adding Nested Key value to Dictionary Dict[5] = {'Nested': {'1': 'LIME', '2': 'SAND'}} print("nAdding a Nested Key: ") print(Dict) OUTPUT Empty Dictionary: {} Dictionary after adding 3 elements: {0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE_PRINT'} Dictionary after adding 3 elements: {0: 'BRICKS', 2: 'CEMENT', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4)} Updated key value: {0: 'BRICKS', 2: 'STEEL', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4)} Adding a Nested Key: {0: 'BRICKS', 2: 'STEEL', 3: 'BLUE_PRINT', 'Value_set': (2, 3, 4), 5: {'Nested': {'1': 'LIME', '2': 'SAND'}}} >
  • 28. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE RESULT: Thus the program was executed successfully and verified
  • 29. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE AIM: To Write a Python function to calculate the factorial of a number PROCEDURE: 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 EXPT.NO 6 (A) Implementing Factorial Programs Using Functions. DATE:
  • 30. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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
  • 31. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO 6 B Implementing Program Largest Number In A List Using Function DATE: AIM: To Write a Python program to get the largest number from a list. PROCEDURE: 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
  • 32. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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
  • 33. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.6 (C) Implementing Programs Using Functions – Area Of Shape DATE AIM: To Write a python program to implement area of shape using functions PROCEDURE: 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
  • 34. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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(f"The area of rectangle is{rect_area}.") elif name == "square": s = int(input("Enter square's side length: ")) sqt_area = s * s print(f"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(f"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(f"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: ")) # calculate area of parallelogram para_area = b * h print(f"The area of parallelogram is{para_area}.")
  • 35. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE else: print("Sorry! This shape is not available") if __name__ == "__main__" : 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
  • 36. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.7 (A) Implementing programs using Strings –Reverse DATE AIM: To Write a python program to implement reverse of a string using string functions PROCEDURE: 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 Step4: to print the reverse string value by Using reverse method function Step5: print the result
  • 37. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: def reverse(string): string = string[::-1] return string s = "Firstyearece" 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 : Firstyearece The reversed string(using extended slice syntax) is : eceraeytsriF RESULT: Thus the reverse of a string function python program was executed and successfully verified
  • 38. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.7 (B) Implementing Programs Using Strings -Palindrome DATE: AIM: To write a python program to implement palindrome using string functions PROCEDURE: 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.
  • 39. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: def is Palindrome(s): return s == s[::-1] # Driver code 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 a string:madam The string is a palindrome RESULT: Thus the program of palindrome by using function in python executed successfully and verified
  • 40. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 7 (C) Implementing programs using Strings - character count DATE: AIM: To Write a python program to implement Characters count using string functions PROCEDURE: 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.
  • 41. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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 : ANJALAI AMMAL MAHALINGAM COLLEGE Total number of characters : 29 RESULT: Thus the program of character count in string in python was executed successfully and verified
  • 42. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE AIM: To write a python program to implement Replacing Characters using string functions PROCEDURE: 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. EXPT.NO: 7 (d) Implementing programs using Strings – Replacing Characters DATE:
  • 43. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM string = "Welcome to python programming" print(string.replace("to", "our")) print(string.replace("ek", "a", 3)) OUTPUT: Welcome our python programming Welcome to python praramming RESULT: Thus the program was executed and successfully verified
  • 44. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE AIM: To write a python program to implement pandas modules. Pandas are denote python data structures. PROCEDURE: 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 4: python method of DataFrame has data aligned in rows and columns like the SQL table or a spreadsheet database Step 3: using Series: It is a 1-D size-immutable array like structure having homogeneous data in a python module Step 4:using max function method to display the maximum ages in a program Step 4:List of elements can be displayed by using output statement in pandas. Step 5: stop the program EXPT.NO: 8 (a) Implementing programs using written modules and Python Standard Libraries–pandas DATE:
  • 45. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: In command prompt install this package: pip install pandas 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())
  • 46. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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
  • 47. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE AIM: To Write a python program to implement numpy module in python . Numerical python are mathematical calculations are solved here. PROCEDURE: 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 EXPT.NO: 8(b) Implementing programs using written modules and Python Standard Libraries– numpy DATE:
  • 48. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: In command prompt install this package-pip install numpy import numpy as np a = np.arange(6) a2 = a[np.newaxis, :] a2.shape #Array Creation and functions: 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 Dimensions: 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
  • 49. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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
  • 50. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE AIM: To write a python program to implement matplotolib module in python. .Matplotlib python are used to show the visualization entities in python. PROCEDURE: 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 EXPT.NO: 8(c) Implementing programs using written modules and Python Standard Libraries–matplotlib DATE:
  • 51. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: In command prompt install this package: pip install matplotlib 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()
  • 52. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE OUTPUT: PROGRAM 2: import matplotlib.pyplot as plt import numpy as np plt.style.use('_mpl-gallery') x = np.linspace(0, 10, 100) y = 4 + 2 * np.sin(2 * x) fig, ax = plt.subplots() ax.plot(x, y, linewidth=2.0) ax.set(xlim=(0, 8), xticks=np.arange(1, 8), ylim=(0, 8), yticks=np.arange(1, 8)) plt.show(
  • 53. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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.
  • 54. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 8 (d) Implementing programs using written modules and Python Standard Libraries– scipy DATE: AIM: Write a python program to implement scipy module in python. .Scipy python are used to solve the scientific calculations PROCEDURE: 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
  • 55. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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.
  • 56. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 9 (a) Implementing real-time/technical applications using File handling - copy from one file to another DATE: AIM: To Write a python program to implement File Copying PROCEDURE: 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:UsersAdministratorDesktopAAMEC2 (2)bookk.csv Where the CSV file name is „products„ and the file extension is csv.
  • 57. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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:UsersAdministratorDesktop bookk.csv Step 3: Copy the file in Python using shutil.copyfile import shutil original = r'C:UsersAdministratorDesktopAAMEC2(2)bookk.csv' target = r'C:UsersAdministratorDesktopAAMEC2bookk.csv' shutil.copyfile(original, target) shutil.copyfile(original, target)
  • 58. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE RESULT: Thus the a python program to implement File Copying was successfully executed and verified .
  • 59. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 9 (b) Implementing real-time/technical applications using File handling word count DATE: AIM: To Write a python program to implement word count in File operations in python PROCEDURE: 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
  • 60. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: file =open(r"C:UsersAdministratorDesktopcount2.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
  • 61. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 9 (c) Implementing real-time/technical applications using File handling - Longest word DATE: AIM: To Write a python program to implement longest word in File operations PROCEDURE: 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 longest of word in a file. step 4: To display the longest word in a target file
  • 62. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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.
  • 63. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 10 (a) Implementing real-time/technical applications using Exception handling.- divide by zero error. DATE: AIM: To Write a exception handling program using python to depict the divide by zero error. PROCEDURE: 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
  • 64. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: (i) marks = 10000 a = marks / 0 print(a) output: ZeroDivisionError: division by zero program 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
  • 65. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 10 (b) Implementing real-time/technical applications using Exception handling.- Check voters eligibility DATE: AIM: To Write a exception handling program using python to depict the voters eligibility PROCEDURE: 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
  • 66. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE program: def main(): #get the age 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 age43 Eligible to vote RESULT: Thus the exception handling program using python to depict the voters eligibility was successfully executed and verified.
  • 67. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 10 (c) Implementing real-time/technical applications using Exception handling.- student mark range validation DATE: AIM: To Implementing real-time/technical applications using Exception handling.- student mark range validation PROCEDURE: 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
  • 68. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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 69 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
  • 69. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 11 Exploring Pygame tool. DATE: AIM: To Write a python program to implement pygame PROCEDURE: step 1: start the program step 2: when Key presses, mouse movements, and even joystick movements are some of the ways in which a user can provide input step 3: To sets up a control variable for the game loop. To exit the loop and the game, you set running = False. The game loop starts on line 29. step 4: starts the event handler, walking through every event currently in the event queue. If there are no events, then the list is empty, and the handler won’t do anything. step 5:check if the current event.type is a KEYDOWN event. If it is, then the program checks which key was pressed by looking at the event.key attribute. If the key is the Esc key, indicated by K_ESCAPE, then it exits the game loop by setting running = False. step 6: do a similar check for the event type called QUIT. This event only occurs when the user clicks the window close button. The user may also use any other operating system action to close the window. step 7:The window won’t disappear until you press the Esc key, or otherwise trigger a QUIT event by closing the window.
  • 70. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: import pygame from pygame.locals import * class Square(pygame.sprite.Sprite): def __init__(self): super(Square, self).__init__() self.surf = pygame.Surface((25, 25)) self.surf.fill((0, 200, 255)) self.rect = self.surf.get_rect() pygame.init() screen = pygame.display.set_mode((800, 600)) square1 = Square() square2 = Square() square3 = Square() square4 = Square() gameOn = True while gameOn: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_BACKSPACE: gameOn = False elif event.type == QUIT: gameOn = False screen.blit(square1.surf, (40, 40)) screen.blit(square2.surf, (40, 530)) screen.blit(square3.surf, (730, 40)) screen.blit(square4.surf, (730, 530)) pygame.display.flip()
  • 71. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE OUTPUT RESULT: Thus the python program to implement pygame was successfully executed and verified.
  • 72. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 12 Developing a game activity using Pygame like bouncing ball DATE: AIM: To Write a python program to implement bouncing balls using pygame tool PROCEDURE: Step1: 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
  • 73. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE PROGRAM: import sys, pygame pygame.init() size = width, height = 800, 400 speed = [1, 1] background = 255, 255, 255 screen = pygame.display.set_mode(size) pygame.display.set_caption("Bouncing ball") ball = pygame.image.load("ball.png") ballrect = ball.get_rect() while 1: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() ballrect = ballrect.move(speed) if ballrect.left < 0 or ballrect.right > width: speed[0] = -speed[0] if ballrect.top < 0 or ballrect.bottom > height: speed[1] = -speed[1] screen.fill(background) screen.blit(ball, ballrect) pygame.display.flip()
  • 74. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE OUTPUT: RESULT: Thus the python program to implement bouncing balls using pygame tool was executed successfully and verified
  • 75. ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE ALL THE BEST …!