PYTHON PROGRAMMING LABMANUAL Prepared by : Dr. S.Shylaja Assistant Professor, Department of Computer Applications, Sri Ramakrishna College of Arts & Science Coimbatore – 641006. 1. Write a Python program to perform arithmetic operations. 2. Mr. Ankit is working in an organization as data analyst. He uses Python Programming conditional statement. He got a dataset of the passengers for the year 2010 to 2012 for January, March and December. His manager wants certain information from him, but he is facing some problems. Help him by answering few questions given below: S. No Year Month Passenge r 1 2010 Jan 25 2 2010 Mar 50 3 2012 Jan 35 4 2010 Dec 55 5 2012 Dec 65 i) Write the python commands to print the details of “January” month with number of passengers. ii) Write the python commands to print the details of passengers in 2010. 3. Write a Python program to manipulate a string 4. Write a Python program that takes a number as input and prints a multiplication table for that number from 1 to 10. 5. Write a Python program to calculate the sum of even numbers in a given list using a lambda function. 6. Write a Python program to import a function from the math module and use it to compute the square root of a given number. SYLLABUS
2.
7. Write aPython program that takes a list of numbers as input, sorts the list, and prints the sorted list. 8. Write a Python program that takes a set of numbers and adds a new element to the set, then prints the updated set. 9. Write a Python program to handle division by zero using exception handling. 10. Write a Python program that raises an exception if the user enters a negative number. Coding 1. # Python program demonstrating Operators and Expressions a = 10 b = 5 # Arithmetic Operations print(f"Arithmetic Operations between {a} and {b}:") print(f"Addition: {a} + {b} = {a + b}") print(f"Subtraction: {a} - {b} = {a - b}") print(f"Multiplication: {a} * {b} = {a * b}") print(f"Division: {a} / {b} = {a / b}") print(f"Modulus: {a} % {b} = {a % b}") print(f"Exponentiation: {a} ** {b} = {a ** b}") print(f"Floor Division: {a} // {b} = {a // b}") print() # Comparison Operations print(f"Comparison Operations between {a} and {b}:") print(f"Equal to: {a} == {b} -> {a == b}") print(f"Not equal to: {a} != {b} -> {a != b}") print(f"Greater than: {a} > {b} -> {a > b}") print(f"Less than: {a} < {b} -> {a < b}") print(f"Greater than or equal to: {a} >= {b} -> {a >= b}") print(f"Less than or equal to: {a} <= {b} -> {a <= b}") print() # Logical Operations print("Logical Operations:") print(f"AND Operation: {a} and {b} -> {a and b}") print(f"OR Operation: {a} or {b} -> {a or b}")
3.
print(f"NOT Operation on{a}: not {a} -> {not a}") print(f"NOT Operation on {b}: not {b} -> {not b}") print() # Assignment Operations print("Assignment Operations:") c = a print(f"Initial Value: c = {a}") c += b print(f"Add and Assign: c += {b} -> c = {c}") c -= b print(f"Subtract and Assign: c -= {b} -> c = {c}") c *= b print(f"Multiply and Assign: c *= {b} -> c = {c}") c /= b print(f"Divide and Assign: c /= {b} -> c = {c}") c %= b print(f"Modulus and Assign: c %= {b} -> c = {c}") c **= b print(f"Exponent and Assign: c **= {b} -> c = {c}") c //= b print(f"Floor Division and Assign: c //= {b} -> c = {c}") print() # Bitwise Operations print(f"Bitwise Operations between {a} and {b}:") print(f"AND: {a} & {b} -> {a & b}") print(f"OR: {a} | {b} -> {a | b}") print(f"XOR: {a} ^ {b} -> {a ^ b}") print(f"NOT on {a}: ~{a} -> {~a}") print(f"Left Shift {a} << 1: {a} << 1 -> {a << 1}") print(f"Right Shift {a} >> 1: {a} >> 1 -> {a >> 1}") print() 1. # Python program demonstrating Operators and Expressions import cmath a=float(input("enter the value of a")) b=float(input("enter the value of b")) c=float(input("enter the value of c"))
4.
d=(b*b)-(4*a*c) if(d>0.0): r1 = (-b + cmath.sqrt(d)) / (2 * a) r2 = ( -b - cmath.sqrt(d)) / (2 * a) print("the roots are "+str(r1)+" and "+str(r2)) elif(d==0.0): r=-b/(2*a) print("the root is: "+str(r)) else: print("Roots are not real") 2. Mr. Ankit is working in an organization as data analyst. He uses Python Programming conditional statement. He got a dataset of the passengers for the year 2010 to 2012 for January, March and December. His manager wants certain information from him, but he is facing some problems. Help him by answering few questions given below: S. No Year Month Passenger 1 2010 Jan 25 2 2010 Mar 50 3 2012 Jan 35 4 2010 Dec 55 5 2012 Dec 65 (i) Write the python commands to print the details of “January” month with number of passengers. import pandas as pd data = {"Year": [2010, 2010, 2012, 2010, 2012], "Month": ["Jan", "Mar", "Jan", "Dec", "Dec"], "Passengers": [25, 50, 35, 55, 65]} df = pd.DataFrame(data) print(df[['Month', 'Passengers']][df['Month'] == 'Jan'])
5.
(ii) Write thepython commands to print the details of passengers in 2010. import pandas as pd data = {"Year": [2010, 2010, 2012, 2010, 2012], "Month": ["Jan", "Mar", "Jan", "Dec", "Dec"], "Passengers": [25, 50, 35, 55, 65]} df = pd.DataFrame(data) print(df[['Year', 'Passengers']][df['Year'] == 2010]) 3. Samyukta is the event in charge in a school. One of her students gave her a suggestion to use Python programming looping statement for analyzing and visualizing the data, respectively. She has created a Data frame “Sports Day” to keep track of the number of First, Second and Third prizes won by different houses in various events. House First Second Third Green 5 7 6 Yellow 10 5 4 Pink 8 13 15 Blue 10 5 3 (i) Write the python commands to calculate the points of various houses. import pandas as pd data = {"House": ["Green", "Yellow", "Pink", "Blue"], "First": [5, 10, 8, 10], "Second": [7, 5, 13, 5], "Third": [6, 4, 15, 3]} df = pd.DataFrame(data) df['Points'] = df['First'] + df['Second'] + df['Third'] print(df) (ii) Write the python commands to print the First place, second place, third place by using points. import pandas as pd
6.
data = {"House":["Green", "Yellow", "Pink", "Blue"], "First": [5, 10, 8, 10], "Second": [7, 5, 13, 5], "Third": [6, 4, 15, 3]} df = pd.DataFrame(data) df['Points'] = df['First'] + df['Second'] + df['Third'] df = df.sort_values(by=['Points'], ascending=False) print(df) 4. Write a program in python using functions and modules. import functions a = int(input("enter the value of a ")) b = int(input("enter the value of b ")) print("choose operation") print("1. add") print("2. subtract") print("3. multiply") print("4. divide") choose = input("enter the choice [1 / 2 / 3 / 4]: ") if choose == '1': print(a, "+", b, "=", functions.add(a, b)) elif choose == '2': print(a, "-", b, "=", functions.sub(a, b)) elif choose == '3': print(a, "*", b, "=", functions.mul(a, b)) elif choose == '4': print(a, "/", b, "=", functions.div(a, b)) else: print("invalid option") 5. Create a python program using elementary data items, lists, sets, dictionaries and tuples. # use of list, tuple, set and # dictionary # Lists
7.
l = [] #Adding Element into list l.append(5) l.append(10) print("Adding 5 and 10 in list", l) # Popping Elements from list- # Set s = set() # Adding element into set s.add(5) s.add(10) print("Adding 5 and 10 in set", s) # Removing element from set s.remove(5) print("Removing 5 from set", s) print() # Tuple t = tuple(l) # Tuples are immutable print("Tuple", t) print() # Dictionary d = {} # Adding the key value pair d[5] = "Five" d[10] = "Ten" print("Dictionary", d) # Removing key-value pair del d[10] print("Dictionary", d) 6. Develop a python program using exception handling. import sys
8.
randomList = ['a',0, 2] for entry in randomList: try: print("The entry is", entry) r = 1/entry except: print("Oops!", sys.exc_info()[0], "occurred.") print("Next entry.") print() print("The reciprocal of", entry, "is", r) 7. Implement the python program using inheritance and operator. class Shape: def __init__(self, name): self.name = name def area(self): pass def __str__(self): return f"This is a {self.name}" class Rectangle(Shape): def __init__(self, length, width): super().__init__("Rectangle") self.length = length self.width = width def area(self): return self.length * self.width def __str__(self): return f"{super().__str__()} with length {self.length} and width {self.width}" def __add__(self, other): if isinstance(other, Shape): return self.area() + other.area() return NotImplemented
9.
class Circle(Shape): def __init__(self,radius): super().__init__("Circle") self.radius = radius def area(self): import math return math.pi * (self.radius ** 2) def __str__(self): return f"{super().__str__()} with radius {self.radius}" def __add__(self, other): if isinstance(other, Shape): return self.area() + other.area() return NotImplemented # Usage rectangle = Rectangle(3, 4) circle = Circle(2) print(rectangle) print(f"Area of rectangle: {rectangle.area()}") print(circle) print(f"Area of circle: {circle.area()}") # Adding areas of two shapes total_area = rectangle + circle print(f"Total area of rectangle and circle: {total_area}") 8.Create a python program using polymorphism class Shape: def __init__(self, name): self.name = name def area(self): pass def __str__(self): return f"This is a {self.name}" class Rectangle(Shape): def __init__(self, length, width): super().__init__("Rectangle")
10.
self.length = length self.width= width def area(self): return self.length * self.width def __str__(self): return f"{super().__str__()} with length {self.length} and width {self.width}" class Circle(Shape): def __init__(self, radius): super().__init__("Circle") self.radius = radius def area(self): import math return math.pi * (self.radius ** 2) def __str__(self): return f"{super().__str__()} with radius {self.radius}" # Function to demonstrate polymorphism def print_area(shapes): for shape in shapes: print(f"{shape}: Area = {shape.area()}") # Create instances of Rectangle and Circle shapes = [ Rectangle(3, 4), Circle(2), Rectangle(5, 6), Circle(3) ] # Demonstrate polymorphism print_area(shapes) 9. Develop a python program to implement the file operator def create_file(filename): #Create a new file try: with open(filename, 'w') as file: file.write("") # Create an empty file
11.
print(f"nFile '{filename}' createdsuccessfully.") except Exception as e: print(f"Error creating file '{filename}': {e}") def write_to_file(filename, content): #Write content to a file try: with open(filename, 'w') as file: file.write(content) print(f"Content written to file '{filename}' successfully.") except Exception as e: print(f"Error writing to file '{filename}': {e}") def read_from_file(filename): #Read content from a file try: with open(filename, 'r') as file: content = file.read() print(f"Content of file '{filename}':nn") print(content) except Exception as e: print(f"Error reading file '{filename}': {e}") def append_to_file(filename, content): """Append content to a file""" try: with open(filename, 'a') as file: file.write(content) print(f"Content appended to file '{filename}' successfully.") except Exception as e: print(f"Error appending to file '{filename}': {e}") # Usage filename = 'example.txt' # Create a new file create_file(filename) # Write to the file write_to_file(filename, "Hello, this is the first line.n") # Read from the file read_from_file(filename)
12.
# Append tothe file append_to_file(filename, "This is an appended line.n") # Read again to see the appended content read_from_file(filename) 10. Create a program using string manipulation # Initialize strings str1 = "Hello" str2 = "World" # Concatenate strings concatenated = str1 + str2 print("Concatenated:", concatenated) # Slice string sliced = concatenated[1:8] print("Sliced:", sliced) # Change case to uppercase uppercased = concatenated.upper() print("Uppercased:", uppercased) # Change case to lowercase lowercased = concatenated.lower() print("Lowercased:", lowercased) # Check if string is uppercase is_upper = concatenated.isupper() print("Is Upper:", is_upper) # Check if string is lowercase is_lower = concatenated.islower() print("Is Lower:", is_lower) # Check if string is alphanumeric is_alphanumeric = concatenated.isalnum() print("Is Alphanumeric:", is_alphanumeric) # Check if string contains only alphabetic characters is_alpha = concatenated.isalpha() print("Is Alpha:", is_alpha)
13.
# Check ifstring is numeric is_numeric = concatenated.isdigit() print("Is Numeric:", is_numeric) # Count occurrences of a substring substring = "lo" count = concatenated.count(substring) print(f"Occurrences of '{substring}': {count}") # Format strings formatted = "Formatted: {} - {}".format(str1, str2) print(formatted) # Replace formatting placeholders with values formatted = f"Formatted (f-string): {str1} - {str2}" print(formatted) # Reverse string reversed_str = concatenated[::-1] print("Reversed:", reversed_str) # Find substring index = concatenated.find("loWo") print("Index of 'loWo' in '{}': {}".format(concatenated, index)) # Replace substring replaced = concatenated.replace("World", " Everyone") print("Replaced:", replaced) # Split string split = replaced.split() print("Split:", split) # Join strings with a delimiter joined = "-".join(split) print("Joined:", joined) # Strip whitespace str3 = " aaaaaa Hello World aaaaa " stripped = str3.strip(" a") print("without stripped:", str3) print("Stripped:", stripped)