\ DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING GE3171-PROBLEM SOLVING AND PYTHON PROGRAMMING LABORATORY LABORATORY LAB MANUAL (Regulation 2021) Prepared by, 1. NITHIYA.K, AP/CSE 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 DATE: Identification and solving of simple real life or scientific or technical problems, and developing flow charts for the same 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 1 101 201 - To Unit 100 200 500 101 -200 201-500 >500 1b) Reatil Shop billing Rate (Rs.) 0 2 3 3.5 4.6 606 Max.Unit 100 200 500>500 >500 >500 Flow-Chart: ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 1c) Sin series Flow Chart: 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 DATE: Python Programming Using Simple Statements And Expressions Exchange The Values Of Two Variables) AIM: Write a python program to exchange the values of two variables 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 ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE 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. EXPT.NO.2b DATE: Python Programming Using Simple Statements And Expressions - Circulate The Values Of N Variables AIM: Write a python program to circulate the values of n variables 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 DATE: Python Programming Using Simple Statements And Expressions ( Calculate The Distance Between Two Points) 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 Scientific problems using Conditionals and Iterative loops.- Number series EXPT.NO.3 (a) 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 22 333 4444 55555 666666 RESULT: Thus the python program to print numbers patterns is executed and verified ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO.3 c DATE: AIM: Scientific Problems Using Conditionals And Iterative Loops. -Pyramid 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) DATE: Implementing Real-Time/Technical Applications Using Lists, Tuples -Items Present InA Library) 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 DATE: Implementing Real-Time/Technical Applications Using Lists, Tuples -Components Of a Car 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 DATE: Implementing Real-Time/Technical Applications Using Lists, Tuples - Materials Required For Construction Of A Building. 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 DATE: Implementing Real-Time/Technical Applications Using Sets, Dictionaries. – Components Of An Automobile AIM: To write a python program to implement Components of an automobile using Sets and Dictionaries 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', ========== 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 'Tesla', 'Honda'} 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 EXPT.NO 6 (A) DATE: Implementing Factorial Programs Using Functions. 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 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 DATE: Implementing Program Largest Number In A List Using Function 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) DATE Implementing Programs Using Functions – Area Of Shape 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) DATE Implementing programs using Strings –Reverse 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) DATE: Implementing programs using Strings - character count 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 EXPT.NO: 7 (d) DATE: Implementing programs using Strings – Replacing Characters 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. 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 EXPT.NO: 8 (a) DATE: Implementing programs using written modules and Python Standard Libraries–pandas AIM: To write a python program to implement pandas modules. Pandas are denote python data structures. 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 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 EXPT.NO: 8(b) DATE: Implementing programs using written modules and Python Standard Libraries– numpy 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 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 EXPT.NO: 8(c) DATE: Implementing programs using written modules and Python Standard Libraries–matplotlib AIM: To write a python program to implement matplotolib module in python. .Matplotlib python are used to show the visualization entities in python. 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 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) DATE: Implementing programs using written modules and Python Standard Libraries– scipy AIM: Write a python program to implement scipy module in python. .Scipy python are used to solve the scientific calculations 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) DATE: Implementing real-time/technical applications using File handling copy from one file to another 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:\Users\Administrator\Desktop\AAMEC2 (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:\Users\Administrator\Desktop \bookk.csv Step 3: Copy the file in Python using shutil.copyfile import shutil original = r'C:\Users\Administrator\Desktop\AAMEC2(2)\bookk.csv' target = r'C:\Users\Administrator\Desktop\AAMEC2\bookk.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) DATE: Implementing real-time/technical applications using File handling word count AIM: To Write a python program to implement word count in File operations in python 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:\Users\Administrator\Desktop\count2.txt","rt") data = file.read() words = data.split() print('Number of words in text file :', len(words)) OUTPUT: Number of words in text file : 4 RESULT: Thus the python program to implement word count in File operations in python was executed successfully and verified ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE EXPT.NO: 9 (c) DATE: Implementing real-time/technical applications using File handling Longest word 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) DATE: Implementing real-time/technical applications using Exception handling.- divide by zero error. AIM: To Write a exception handling program using python to depict the divide by zero error. 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) DATE: Implementing real-time/technical applications using Exception handling.- Check voters eligibility AIM: To Write a exception handling program using python to depict the voters eligibility 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) DATE: Implementing real-time/technical applications using Exception handling.- student mark range validation AIM: To Implementing real-time/technical applications using Exception handling.- student mark range validation 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 …! ANJALAI AMMAL MAHALINGAM ENGINEERING COLLEGE