Vimal Python Program (2)
Vimal Python Program (2)
PAGE.
S.NO DATE LIST OF EXPERINMENTS. MARKS SIGN
NO.
1(A) PYTHON BASICS. 3
1(B) DATATYPES. 5
2(B) FUNCTIONS. 13
3(A) STRING. 19
3(B) REGEX. 21
3(C) LIST. 23
3(D) TUPLES. 25
4(A) DICTIONARY. 27
4(B) EXCEPTION. 29
5(A) NUMPY-I. 35
5(B) NUMPY-II. 37
5(C) PANDAS-I. 39
PANDAS-II.
5(D) 41
6(A) POLMORPHISM. 43
6(D) ENCAPSULATION. 49
EX.NO : 1(A)
PYTHON BASICS.
DATE :
PROGRAM STATEMENT :
Write a python program to Add two complex numbers. Get the inputs using eval().
ALGORITHM :
1. Start the program.
2. Accept the first complex number input from the user using eval() and store it in the
variable num1.
3. Accept the second complex number input from the user using eval() and store it in the
variable num2.
4. Add num1 and num2 and store the result in a variable result.
5. Print the value of result.
6. End the program.
PROGRAM :
n1=eval(input())
n2=eval(input())
print("A is",n1)
print("B is",n2)
print("Sum is",n1+n2)
OUTPUT :
RESULT :
Thus, the program to add two complex numbers using eval() is created successfully.
EX.NO : 1(B)
DATATYPES.
DATE :
PROGRAM STATEMENT :
Write a python program to read an integer value and convert it into a float value.
ALGORITHM :
1. Start the program.
2. Accept an integer input from the user and store it in a variable.
3. Convert the integer value into a float value using type conversion.
4. Print the converted float value.
5. End the program.
PROGRAM :
x=float(input())
y=float(input())
z=complex(x,y)
print(z)
print(y)
OUTPUT :
RESULT :
Thus, the program to read an integer value and convert it into a float value is created
successfully.
EX.NO : 1(C)
VARIABLES & EXPRESSIONS OPERATOR.
DATE :
PROGRAM STATEMENT :
Write a python program for bitwise shift operators on the user given integers.
ALGORITHM :
1. Start the program.
2. Accept an integer input from the user and store it in a variable.
3. Accept the number of positions to shift from the user and store it in another variable.
4. Perform a left shift operation (<<) on the integer by the specified number of positions and
store the result.
5. Perform a right shift operation (>>) on the integer by the specified number of positions and
store the result.
6. Print the results of both the left shift and right shift operations.
7. End the program.
PROGRAM :
a =int(input())
b=
int(input())
print(a > b)
print(a < b)
print(a >= b)
print(a <= b)
print(a == b)
print(a != b)
OUTPUT :
RESULT :
Thus, the program to perform bitwise shift operations (<< and >>) on user-given integers is
created successfully.
EX.NO : 1(D)
CONDITIONAL STATEMENTS.
DATE :
PROGRAM STATEMENT :
Write a python program to check whether the given number is even or odd using If..else statements.
ALGORITHM :
1. Start the program.
2. Accept an integer input from the user and store it in a variable.
3. Use an if statement to check if the number is divisible by 2 (i.e., check if the
remainder when divided by 2 is 0).
4. If the number is divisible by 2, print that the number is even.
5. If the number is not divisible by 2, print that the number is odd.
6. End the program.
PROGRAM :
a=int(input())
if a%2==0 :
print("EVEN)
else:
print("ODD")
OUTPUT :
RESULT :
Thus, the program to check whether the given number is even or odd using if...else statements
is created successfully.
EX.NO : 2(A)
ITERATIVE STATEMENTS.
DATE :
PROGRAM STATEMENT :
Python Program to print numbers range from M to N (including M and N values) divisible by 11 in
reverse order.
ALGORITHM :
1. Start the program.
2. Accept two integer inputs from the user, M and N, and store them in variables.
3. Use a for loop to iterate through the numbers from N to M in reverse order.
4. Within the loop, check if the current number is divisible by 11.
5. If the number is divisible by 11, print it.
6. End the program.
PROGRAM :
a=int(input())
for i in range(1,a+1):
if i%2==0:
print(i)
OUTPUT :
RESULT :
Thus, the program to print numbers in the range from M to N (inclusive) that are divisible by
11 in reverse order is created successfully.
EX.NO : 2(B)
FUNCTIONS.
DATE :
PROGRAM STATEMENT :
Write a python program to define a function that accepts side of a square and returns the area of a
square.
ALGORITHM :
1. Start the program.
2. Define a function area_of_square that accepts one parameter side, representing
the side length of the square.
3. Inside the function, calculate the area of the square by squaring the side (side * side).
4. Return the calculated area.
5. Outside the function, prompt the user to input the side of the square.
6. Call the function with the input value and print the result.
7. End the program.
PROGRAM :
def result(a,b,c):
mul=a*b*c
print(f"Multiply is {mul}")
a = int(input())
b = int(input())
c=int(input())
result(a,b,c)
OUTPUT :
RESULT :
Thus, the program to define a function that accepts the side of a square and returns its area is
created successfully.
EX.NO : 2(C)
BUILT-IN FUNCTIONS & LAMBDA FUNCTIONS.
DATE :
PROGRAM STATEMENT :
Write a lambda function which takes z as a parameter and returns z*2 using python.
ALGORITHM :
1. Start the program.
2. Define a lambda function that takes one parameter z.
3. In the lambda function, return z * 2.
4. Call the lambda function with a value for z and print the result.
5. End the program.
PROGRAM :
a=int(input())
if a%2==0:
print(a,"is even")
else:
print(a,"is odd")
OUTPUT :
RESULT :
Thus, the lambda function that takes z as a parameter and returns z * 2 is created successfully.
EX.NO : 2(D)
LOOPINT(PATTERNS).
DATE :
PROGRAM STATEMENT :
Python program to print alternate number pattern .Get the number of rows as input.
ALGORITHM :
1. Start the program.
2. Accept the number of rows n from the user.
3. Initialize a variable num to 1, which will be used to print the numbers in the pattern.
4. Use a loop to iterate through each row from 1 to n.
5. For each row, use a nested loop to print the numbers in an alternating pattern,
incrementing the value of num by 2 for each number printed.
6. Print a new line after each row.
7. End the program.
PROGRAM :
a=int(input())
for i in
range(a,0,-1):
for j in range(i):
print("*",end=' ')
print()
OUTPUT :
RESULT :
Thus, the program to print an alternate number pattern based on the number of rows is created
successfully.
EX.NO : 3(A)
STRING.
DATE :
PROGRAM STATEMENT :
Write a python program to compute the length of the string without using built-in function.
ALGORITHM :
1. Start the program.
2. Accept the input string from the user and store it in a variable.
3. Initialize a variable length to 0.
4. Use a for loop to iterate through each character of the string.
5. For each character, increment the length variable by 1.
6. After the loop ends, print the value of length, which represents the length of the string.
7. End the program.
PROGRAM :
def
convert(char):
result=''
for i in range(len(char)):
if char[i].isalpha():
result += "#"
elif char[i].isalnum():
result += "A"
else:
result += "5"
print(result)
OUTPUT :
RESULT :
Thus, the program to compute the length of the string without using built-in functions is created
successfully.
EX.NO : 3(B)
REGEX.
DATE :
PROGRAM STATEMENT :
Write a Python program to check that a string contains only a certain set of characters (in this case
a-z, A-Z and 0-9).
ALGORITHM :
1. Start the program.
2. Accept the input string from the user and store it in a variable.
3. Define a set of allowed characters, which includes lowercase letters (a-z), uppercase letters
(A-Z), and digits (0-9).
4. Use a loop to iterate through each character of the string.
5. For each character, check if it belongs to the set of allowed characters.
6. If any character does not belong to the allowed set, print that the string contains
invalid characters and exit.
7. If all characters belong to the allowed set, print that the string is valid.
8. End the program.
PROGRAM :
import re
z=input()
x=re.search(r".{3}b",z)
if x:
print("Found a match!")
else:
print("Not matched!")
OUTPUT :
RESULT :
Thus, the program checks whether the string contains only the characters a-z, A-Z, and 0-9
successfully.
EX.NO : 3(C)
LIST.
DATE :
PROGRAM STATEMENT :
Write a Python program to multiply all the items in a list [1,6,4,7].
ALGORITHM :
1. Start the program.
2. Initialize a list with the values [1, 6, 4, 7].
3. Initialize a variable result to 1, which will be used to store the product of all items.
4. Use a loop to iterate through each item in the list.
5. Multiply each item with the result variable.
6. After the loop, print the value of result, which will be the product of all the items in the list.
7. End the program.
PROGRAM :
input_list=[14,15,6,7,9,2,4]
n=len(input_list)
#Add your code
print(input_list[::-1]
)
OUTPUT :
RESULT :
Thus, the program multiplies all the items in the list [1, 6, 4, 7] and computes the result
successfully.
EX.NO : 3(D)
TUPLES.
DATE :
PROGRAM STATEMENT :
Create a python code to create tuple with repetition for N times.
ALGORITHM :
1. Start the program.
2. Accept the value of N (number of repetitions) from the user.
3. Accept the value or element to be repeated from the user.
4. Create a tuple that repeats the element N times.
5. Print the created tuple.
6. End the program.
PROGRAM :
a=int(input())
b=[]
for i in range(1,a):
if i%9==0:
b.append(i)
print(tuple(b))
print("Length of the
tuple is",len(b))
OUTPUT :
RESULT :
Thus, the program creates a tuple with the given element repeated N times successfully.
EX.NO : 4(A)
DICTIONARY.
DATE :
PROGRAM STATEMENT :
Write a python program to display the keys alphabetically using dictionary.
ALGORITHM :
1. Start the program.
2. Define a dictionary with some key-value pairs.
3. Extract the keys of the dictionary using the keys() method.
4. Sort the keys alphabetically using the sorted() function.
5. Print the sorted keys.
6. End the program.
PROGRAM :
RESULT :
Thus, the program displays the keys of the dictionary alphabetically.
EX.NO : 4(B)
EXCEPTION.
DATE :
PROGRAM STATEMENT :
Write a python code to check if the value given in age as input is negative and then force the
program to raise an exception using raise keyword.
ALGORITHM :
1. Start the program.
2. Accept the age as input from the user.
3. Check if the input age is negative.
4. If the age is negative, use the raise keyword to trigger an exception with
an appropriate error message.
5. If the age is not negative, print a message confirming the entered age.
6. End the program.
PROGRAM :
a=['laptop','mobile','pen']
try:
print(a[4])
except:
print('check index
range')
OUTPUT :
RESULT :
Thus, the program checks if the value of age is negative and raises an exception using the raise
keyword if it is.
EX.NO : 4(C)
FILES MODULES.
DATE :
PROGRAM STATEMENT :
Find unique words in a file : Write a function to find all unique words in a file.
ALGORITHM :
1. Start the program.
2. Define a function find_unique_words that accepts the file name as input.
3. Open the file in read mode.
4. Read the content of the file and convert it into lowercase to avoid case sensitivity issues.
5. Split the content into words (using spaces and punctuation as delimiters).
6. Use a set to store the words, which will automatically handle duplicates.
7. Return the unique words from the set.
8. Print the unique words.
9. End the program.
PROGRAM :
file.write(content)
def find_longest_word(file_path):
with open(file_path,'r') as f:
a=f.read()
b=a.split()
l=''
for i in b:
if len(i)>len(l):
l=i
return l
RESULT :
Thus, the program finds all unique words in the given file.
EX.NO : 4(D)
CLASSES & OBJECTS.
DATE :
PROGRAM STATEMENT :
Write Python Program to take the radius from the user and find the area of the circle using class
name 'cse' and function name 'mech'.
ALGORITHM :
1. Start the program.
2. Define a class named cse.
3. Inside the class, define a method mech that takes radius as an argument.
4. In the mech method, calculate the area of the circle using the formula: area = π * radius
* radius.
5. Print the area of the circle inside the mech method.
6. Outside the class, create an object of class cse.
7. Take the radius input from the user and pass it to the mech method using the class object.
8. End the program.
PROGRAM :
import math
x = int(input())
z = math.pi*x**2
print(f"Area of circle: {z:.2f}")
OUTPUT :
RESULT :
Thus, the program calculates and displays the area of the circle based on the radius provided by
the user.
EX.NO : 5(A)
NUMPY-I.
DATE :
PROGRAM STATEMENT :
Write a NumPy program to create an array of integers from 30 to 70.
ALGORITHM :
1. Start the program.
2. Import the numpy library.
3. Use the numpy.arange() function to create an array of integers from 30 to 70.
4. Print the created array.
5. End the program.
PROGRAM :
import numpy as np
n,m=map(int,input().split()
) a=np.zeros((n,m))
for i in range(n):
r=list(map(int,input().split())
) a[i]=r
print(round(np.prod(np.sum(a,axis=0))))
OUTPUT :
RESULT :
Thus, the program creates an array of integers from 30 to 70 using NumPy.
EX.NO : 5(B)
NUMPY-II.
DATE :
PROGRAM STATEMENT :
Create a numPy program for the following problem statement.
You are given a space separated list of nine integers. Your task is to convert this list into
a 3X3NumPy array.
ALGORITHM :
1. Start the program.
2. Accept a space-separated list of nine integers as input from the user.
3. Convert the input string into a list of integers using the split() method and map() function.
4. Use numpy.array() to convert the list into a NumPy array.
5. Reshape the array into a 3x3 matrix using numpy.reshape().
6. Print the resulting 3x3 array.
7. End the program.
PROGRAM :
import numpy as np
z=[]
n=list(map(int,input().split()))
for i in range(n[0]):
x=list(map(int,input().split()))
z.append(x)
a=np.array(z)
c=np.transpose(a)
print(c)
b=np.ravel(a)
print(b)
OUTPUT :
RESULT :
Thus, the program converts a space-separated list of nine integers into a 3x3 NumPy array.
EX.NO : 5(C)
PANDAS-I.
DATE :
PROGRAM STATEMENT :
Create a pandas program to get the positions of items of series A in another series B.
ALGORITHM :
1. Start the program.
2. Import the pandas library.
3. Create two pandas Series, A and B.
4. Use the isin() method on series A to check which elements of A are present in series B.
5. Use where() or nonzero() to find the positions (indices) of elements in A that appear in B.
6. Print the positions of the elements.
7. End the program.
PROGRAM :
import pandas
data=eval(input())
dp=pandas.DataFrame(data)
print(dp)
OUTPUT :
RESULT :
Thus, the program finds and prints the positions of items in Series A that also appear in Series
B.
EX.NO : 5(D)
PANDAS-II.
DATE :
PROGRAM STATEMENT :
Create a Pandas program to merge two given datasets using multiple join keys.
ALGORITHM :
1. Start the program.
2. Import the pandas library.
3. Create two datasets (DataFrames) with common columns that will be used as join keys.
4. Use the merge() function to merge the datasets based on multiple columns (join keys).
5. Specify the columns to join on by providing them as a list in the on parameter of the
merge() function.
6. Print the merged DataFrame.
7. End the program.
PROGRAM :
import numpy as np
import pandas as pd
a=eval(input())
b=eval(input())
c=pd.DataFrame(a)
d=pd.DataFrame(b)
print("Original
DataFrames:") print(c)
print(" ")
print(d)
print()
print("Merged Data:")
print(pd.merge(c,d))
OUTPUT :
RESULT :
Thus, the program merges two given datasets using multiple join keys and prints the merged
result.
EX.NO : 6(A)
POLYMORPHISM.
DATE :
PROGRAM STATEMENT :
Create two new classes: Lion and Giraffe The outputs from this program are carnivore and
herbivore, respectively. The two classes both use the method name diet, but they define those
methods differently. An object instantiated from the Lion class will use the method as it is defined
in that class. The Giraffe class may have a method with the same name, but objects instantiated
from the Lion class won’t interact with it.
ALGORITHM :
1. Start the program.
2. Define the Lion class with the method diet that prints "Carnivore".
3. Define the Giraffe class with the method diet that prints "Herbivore".
4. Instantiate objects of both classes (Lion and Giraffe).
5. Call the diet method on each object and observe how each class implements its own version
of the diet method.
6. End the program.
PROGRAM :
class Lion:
def diet(self):
print("carnivore")
class Giraffe:
def diet(self):
print("herbivore")
obj_lion=Lion()
obj_giraffe=Giraffe()
obj_lion.diet()
# returns carnivore
obj_giraffe.diet()
OUTPUT :
RESULT :
The program will print "Carnivore" when the diet method of the Lion class is called, and
"Herbivore" when the diet method of the Giraffe class is called. The objects will not interact with
each other, even though both classes have a method with the same name.
EX.NO : 6(B)
OPERATOR OVERLOADING.
DATE :
PROGRAM STATEMENT :
Write a Python program for simply using the overloading operator for adding two objects.
ALGORITHM :
1. Start the program.
2. Define a class (e.g., MyClass) with an init method to initialize an object with
a numerical value.
3. Define the add method in the class to overload the + operator. This method will define
how two objects of the class should be added together.
4. Create two objects of the class with numerical values.
5. Add the two objects using the + operator, which will invoke the add method.
6. Print the result of the addition.
7. End the program.
PROGRAM :
class Product:
def init (self, amt, word):
self.amt = amt
self.word = word
o1 = Product(23, "hello")
o2 = Product(21, "world")
res = o1+o2
print(res)
OUTPUT :
RESULT :
Thus, the program adds two objects by overloading the + operator.
EX.NO : 6(C)
ABSTRACTION.
DATE :
PROGRAM STATEMENT :
Bank is an abstract class which having intertest() abstract method. SBI class is a child class to Bank
class, so SBI class should provide implementation for abstract method which is available in Bank
abstract class. An object is created to subclass, which is SBI, and then implemented method
interest() is called.
ALGORITHM :
1. Start the program.
2. Define an abstract class Bank with an abstract method interest() using the abc module.
3. Create a subclass SBI that inherits from the Bank class.
4. Implement the interest() method in the SBI class.
5. Instantiate an object of the SBI class and call the interest() method.
6. End the program.
PROGRAM :
from abc import ABC, abstractmethod
#Abstract Class
class Bank(ABC):
def bank_info(self):
print("Welcome to bank")
@abstractmethod
def interest(self):
print("In sbi bank 5 rupees interest")
class SBI(Bank):
def interest(self):
print("In sbi bank 5 rupees interest")
s= SBI()
s.bank_info ()
s.interest()
OUTPUT :
RESULT :
The program demonstrates how an abstract method in a parent class can be implemented in a
child class. The interest() method of the SBI class will be called and executed.
EX.NO : 6(D)
ENCAPSULATION.
DATE :
PROGRAM STATEMENT :
Create a class pub_mod with two variables name and age of a person define a method to display the
age value,create an object for the class to invoke age method.
ALGORITHM :
1. Start the program.
2. Define a class named pub_mod with two variables: name and age representing the name
and age of a person.
3. Define a method display_age() within the class to display the age value.
4. Create an object of the pub_mod class and initialize the name and age variables.
5. Invoke the display_age() method using the created object to display the person's age.
6. End the program.
PROGRAM :
# illustrating public members & public access modifier
class pub_mod:
# constructor
def init (self, name, age):
self.name = name;
self. age = age;
def Age(self):
return self. age
obj = pub_mod("Jason", 35)
print("Name: ", obj.name)
print("Age: ", obj.Age())
OUTPUT :
RESULT :
The program will display the age of the person based on the input values provided during
object creation.