Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Record

Download as pdf or txt
Download as pdf or txt
You are on page 1of 104

1

Ex. No. 1.a DIFFERENT ARITHMETIC OPERATIONS ON


NUMBERS
Date :

AIM:
To write a program to perform different Arithmetic Operations on numbers in
python.

ALGORITHM:
Step 1: Start the program.
Step 2: Initialize variables 'a' and 'b' to be integers and prompt the user to input a
value for 'a' and 'b'.
Step 3: Perform addition, subtraction, multiplication, division, remainder,
exponent, and floor division operations on 'a' and 'b'
Step 4: Print the results of each operation.
Step 5: Stop the program.
2

PROGRAM:

# arithmetic_operations.py
a=int(input("Enter a value ")) #input() takes data from console at runtime as string.
b=int(input("Enter b value ")) #typecast the input string to int.
print("Addition of a and b ",a+b)
print("Subtraction of a and b ",a-b)
print("Multiplication of a and b ",a*b)
print("Division of a and b ",a/b)
print("Remainder of a and b ",a%b)
print("Exponent of a and b ",a**b) #exponent operator (a^b)
print("Floor division of a and b ",a//b) # floor division
3

OUTPUT:
E:\Python>python arithmetic_operations.py
Enter a value 3
Enter b value 4
Addition of a and b 7
Subtraction of a and b -1
Multiplication of a and b 12
Division of a and b 0.75
Remainder of a and b 3
Exponent of a and b 81
Floor division of a and b 0

RESULT:
Thus, the program to perform different arithmetic operations on numbers in
python was written and executed successfully.
4

Ex. No. 1.b CREATE, CONCATENATE AND SLICE STRING

Date :

AIM:
To write a program to create, concatenate and print a string and accessing sub-
string from a given string.

ALGORITHM:
Step 1: Start the program.
Step 2: Initialize variables 's1' and 's2' to be strings and prompt the user to input
a value for 's1' and 's2'.
Step 3: Print the values of 's1' and 's2'.
Step 4: Concatenate and print the strings 's1' and 's2'.
Step 5: Create and print a substring of 's1' by using string slicing.
Step 6: Stop the program.
5

PROGRAM:

# string_manipulation.py
s1=input("Enter first String : ")
s2=input("Enter second String : ")
print("First string is : ",s1)
print("Second string is : ",s2)
print("concatenations of two strings :",s1+s2)
print("Substring of given string :",s1[1:4])
6

OUTPUT:
E:\Python>python string_manipulation.py
Enter first String : Hello
Enter second String : World
First string is : Hello
Second string is : World
concatenations of two strings : HelloWorld
Substring of given string : ell

RESULT:
Thus, the program to create, concatenate and print a string and accessing sub-
string from a given string in python was written and executed successfully.
7

Ex. No. 2.a COMPUTE DISTANCE BETWEEN TWO POINTS


Date :

AIM:

To write a python program to compute the distance between two points taking
input from the user (Pythagorean Theorem)

ALGORITHM:

Step 1: Start the program

Step 2: Import the math module

Step 3: Get input for x1 and y1 from the user

Step 4: Get input for x2 and y2 from the user

Step 5: Calculate the distance between the two points using the Pythagorean
theorem
Step 6: Print the distance between the two points
Step 7: Stop the program
8

PROGRAM:
import math;

x1=int(input("Enter x1--->"))

y1=int(input("Enter y1--->"))

x2=int(input("Enter x2--->"))

y2=int(input("Enter y2--->"))

d1 = (x2 - x1) * (x2 - x1);

d2 = (y2 - y1) * (y2 - y1);

res = math.sqrt(d1+d2)

print ("Distance between two points:",res);


9

OUTPUT:
Enter x1--->10

Enter y1--->20

Enter x2--->15

Enter y2--->19

Distance between two points: 5.0990195135927845

RESULT:
Thus, the program to find the distance between two points in python was
written and executed successfully.
10

Ex. No. 2.b FIND THE LARGEST OF THREE NUMBERS

Date :

AIM:

To write a python program to find largest of three numbers.

ALGORITHM:

Step 1: Start the program

Step 2: Get input for num1, num2 and num3 from the user

Step 3: Check if num1 is greater than both num2 and num3, if so set largest to

num1

Step 4: If not, check if num2 is greater than both num1 and num3, if so set

largest to num2

Step 5: If not, set largest to num3

Step 6: Print the largest number

Step 7: Stop the program


11

PROGRAM:

# week8.py
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
num3 = int(input("Enter third number: "))

if (num1 > num2) and (num1 > num3):


largest = num1
elif (num2 > num1) and (num2 > num3):
largest = num2
else:
largest = num3

print("The largest number is",largest)


12

OUTPUT 1:
E:\Python>python week8.py
Enter first number: 400
Enter second number: 500
Enter third number: 200
The largest number is 500

OUTPUT 2:
Enter first number: 10
Enter second number: 12
Enter third number: 14
The largest number is 14.0

OUTPUT 3:
Enter first number: -1
Enter second number: 0
Enter third number: -3
The largest number is 0.0

RESULT:
Thus, the program to find the largest of three numbers in Python was written
and executed successfully.
13

Ex. No. 3.a ODD OR EVEN NUMBER

Date :

AIM:
To write a program to check whether the given number is even number or not.

ALGORITHM:

Step 1: Start the program

Step 2: Get input for the number from the user

Step 3: Check if the number is even by using the modulus operator to determine

if there is a remainder when the number is divided by 2

Step 4: If there is no remainder, print that the number is even

Step 5: If there is a remainder, print that the number is odd

Step 6: Stop the program


14

PROGRAM:
num = int (input (“Enter any number to test whether it is odd or even: “)

if (num % 2) == 0:

print (“The number is even”)

else:

print (“The provided number is odd”)


15

OUTPUT:

Enter any number to test whether it is odd or even:

887

887 is odd.

RESULT:
Thus, the program to check whether the given number is even number or not in
Python was written and executed successfully.
16

Ex. No. 3.b PRIME NUMBERS LESS THAN 100


Date :

AIM:
To write a python program to prints the prime numbers less than 100.

ALGORITHM:

Step 1: Start the program

Step 2: Print "Prime numbers between 1 and 100 are:"

Step 3: Set the upper limit of the range to 100

Step 4: Iterate through each number in the range from 2 to the upper limit

Step 5: For each number, check if it is divisible by any number between 2 and

itself

Step 6: If the number is not divisible by any other number, print it as a prime

number

Step 7: Continue to the next number in the range

Step 8: Stop the program when the range is complete


17

PROGRAM:

# week11.py
print("Prime numbers between 1 and 100 are:")
ulmt=100;
for num in range(ulmt):
# prime numbers are greater than 1
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
18

OUTPUT:

Prime numbers between 1 and 100 are:

2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73
79 83 89 97

RESULT:
Thus, the program to print the prime numbers less than 100 in python was
written and executed successfully.
19

Ex. No. 4.a SUM OF ALL NUMBERS STORED IN A LIST USING LOOPS

Date :

AIM:
To write a python program to find the sum of all numbers stored in a list using
loops.

ALGORITHM:
Step 1: Start the program
Step 2: Create a list of numbers
Step 3: Set a variable sum to 0
Step 4: Iterate through each number in the list
Step 5: For each number, add it to the sum variable
Step 6: Print the final sum of all the numbers in the list
Step 7: Stop the program
20

PROGRAM:
# List of numbers
numbers = [6, 5, 3, 8, 4, 2, 5, 4, 11]

# variable to store the sum


sum = 0

# iterate over the list


for val in numbers:
sum = sum+val

print("The sum is", sum)


21

OUTPUT:

The sum is 48

RESULT:
Thus, the program to find the sum of all numbers stored in a list using loops in
python was written and executed successfully.
22

Ex. No. 4.b SUM OF NEGATIVE NUMBERS, POSITIVE EVEN NUMBERS


AND POSITIVE ODD NUMBERS IN A LIST
Date :

AIM:
To write a python program to print sum of negative numbers, positive even
numbers and positive odd numbers in a list

ALGORITHM:

Step 1: Start the program

Step 2: Get the number of elements that will be in the list from the user

Step 3: Create an empty list and get input for each element from the user

Step 4: Set variables sum1, sum2, and sum3 to 0

Step 5: Iterate through each element in the list

Step 6: If the element is positive, check if it is even or odd and add it to the

appropriate sum

Step 7: If the element is negative, add it to sum3

Step 8: Print the sum of all positive even numbers, the sum of all positive odd

numbers, and the sum of all negative numbers

Step 9: Stop the program


23

PROGRAM:
n=int(input("Enter the number of elements to be in the list:"))
b=[]
for i in range(0,n):
a=int(input("Element: "))
b.append(a)
sum1=0
sum2=0
sum3=0
for j in b:
if(j>0):
if(j%2==0):
sum1=sum1+j
else:
sum2=sum2+j
else:
sum3=sum3+j
print("Sum of all positive even numbers:",sum1)
print("Sum of all positive odd numbers:",sum2)
print("Sum of all negative numbers:",sum3)
24

OUTPUT:
Case 1:
Enter the number of elements to be in the list:4
Element: -12
Element: 34
Element: 35
Element: 89
Sum of all positive even numbers: 34
Sum of all positive odd numbers: 124
Sum of all negative numbers: -12

Case 2:
Enter the number of elements to be in the list:5
Element: -45
Element: -23
Element: 56
Element: 23
Element: 7
Sum of all positive even numbers: 56
Sum of all positive odd numbers: 30
Sum of all negative numbers: -68

RESULT:
Thus, the program to find sum of negative numbers, positive even numbers and
positive odd numbers in a list in python was written and executed successfully.
25

Ex. No. 5.a ADDITION OF TWO SQUARE MATRICES


Date :

AIM:
To write a python program to perform addition of two square matrices

ALGORITHM:

Step 1: Start the program


Step 2: Get the number of rows and columns from the user
Step 3: Create an empty list for matrix A and get input for each element from
the user, adding them to the list and appending the row to matrix A
Step 4: Create an empty list for matrix B and get input for each element from
the user, adding them to the list and appending the row to matrix B
Step 5: Create an empty list for the sum of matrix A and matrix B and iterate
through each row and column, adding the corresponding elements from
matrix A and matrix B and adding them to the list and appending the row to the
sum list
Step 6: Print matrix A, matrix B, and the sum list
Step 7: Stop the program
26

PROGRAM:
r=int(input("enter rows"))
c=int(input("enter columns"))
a=[]
for i in range(r):
t=[]
for j in range(c):
val=int(input(f"enter a[{i}[{j}]:"))
t.append(val)
a.append(t)
b=[]
for i in range(r):
t=[]
for j in range(c):
val=int(input(f"enter b[{i}[{j}]:"))
t.append(val)
b.append(t)
sum=[]
for i in range(r):
t=[]
for j in range(c):
val=a[i][j]+b[i][j]
t.append(val)
sum.append(t)
print(a)
print(b)
print(sum)
27

OUTPUT:
enter rows 3
enter columns 3
enter a[0[0]:1
enter a[0[1]:1
enter a[0[2]:1
enter a[1[0]:2
enter a[1[1]:2
enter a[1[2]:2
enter a[2[0]:3
enter a[2[1]:3
enter a[2[2]:3
enter b[0[0]:4
enter b[0[1]:4
enter b[0[2]:4
enter b[1[0]:5
enter b[1[1]:5
enter b[1[2]:5
enter b[2[0]:1
enter b[2[1]:1
enter b[2[2]:1
[[1, 1, 1], [2, 2, 2], [3, 3, 3]]
[[4, 4, 4], [5, 5, 5], [1, 1, 1]]
[[5, 5, 5], [7, 7, 7], [4, 4, 4]]

RESULT:
Thus, the program to perform addition of two square matrices in python was
written and executed successfully.
28

Ex. No. 5.b MULTIPLICATION OF TWO SQUARE MATRICES


Date :

AIM:
To write a python program to perform multiplication of two square matrices

ALGORITHM:
Step 1: Start the program
Step 2: Get the number of rows and columns for matrix 1 and matrix 2 from the
user
Step 3: Check if matrix 1 and matrix 2 are compatible for multiplication (if the
number of columns in matrix 1 is equal to the number of rows in
matrix 2)
Step 4: If they are compatible, initialize a zero matrix for the result
Step 5: Get input for each element of matrix 1 and matrix 2 from the user
Step 6: Perform matrix multiplication on matrix 1 and matrix 2 and store the
result in the zero matrix
Step 7: Print the resulting matrix
Step 8: If matrix 1 and matrix 2 are not compatible, print an error message
Step 9: Stop the program
29

PROGRAM:
a = int(input("Enter the no of rows for Matrix 1: "))

b = int(input("Enter the no of columns for Matrix 1: "))

a1 = int(input("Enter the no of rows for Matrix 2: "))

b1 = int(input("Enter the no of columns for Matrix 2: "))

# condition for checking the matrix multiplication


if (b == a1):
mat1 = []
mat2 = []
ans = []

# intilization of the resultant matrix to be zero matrix


for i in range(a):
tem = []
for j in range(b1):
v=0
tem.append(v)
ans.append(tem)

m=0
n=0

# getting the values for matrix 1

print("\n")
print("-----------Enter the values for Matrix 1-------------")

for i in range(a):
tem = []
for j in range(b):
m = int(input("Enter the value {0} for matrix 1:".format(n + 1)))
tem.append(m)
n=n+1
mat1.append(tem)
30

# printing the values of matrix 1


for r in mat1:
print(r)
# getting the values for matrix 2

print("\n\n")
print("------------Enter the values for Matrix 2-----------------")

n=0
for i in range(a1):
tem = []
for j in range(b1):
m = int(input("Enter the value {0} for matrix 2:".format(n + 1)))
tem.append(m)
n=n+1
mat2.append(tem)

# printing the values of matrix 2

print("Matrix-------->2")
for r in mat2:
print(r)

# doing the multiplication of matrix


print("---------------Result Matrix-----------------")
for i in range(len(mat1)):

for j in range(len(mat2[0])):

for k in range(len(mat2)):
ans[i][j] += mat1[i][k] * mat2[k][j]

# printing the result matrix


for r in ans:
print(r)

else:
print("\n")
print("UNABLE TO DO MATRIX MULTIPLICATION")
31

OUTPUT:

Enter the no of rows for Matrix 1: 2

Enter the no of columns for Matrix 1: 3

Enter the no of rows for Matrix 2: 3

Enter the no of columns for Matrix 2: 2

-------------------Enter the values for Matrix 1-------------------------

Enter the value 1 for matrix 1:1

Enter the value 2 for matrix 1:2

Enter the value 3 for matrix 1:3

Enter the value 4 for matrix 1:4

Enter the value 5 for matrix 1:5

Enter the value 6 for matrix 1:6

[1, 2, 3]

[4, 5, 6]
32

--------------------Enter the values for Matrix 2-------------------------

Enter the value 1 for matrix 2:1

Enter the value 2 for matrix 2:2

Enter the value 3 for matrix 2:3

Enter the value 4 for matrix 2:4

Enter the value 5 for matrix 2:5

Enter the value 6 for matrix 2:6

Matrix-------->2

[1, 2]

[3, 4]

[5, 6]

---------------------------Result Matrix-------------------------

[22, 28]

[49, 64]

RESULT:
Thus, the program to perform multiplication of two square matrices in python
was written and executed successfully.
33

Ex. No. 6 FIND THE FACTORIAL OF A NUMBER USING


RECURSION
Date :

AIM:
To write a python program to find the factorial of a number using recursion

ALGORITHM:

Step 1: Start the program


Step 2: Define a function to calculate the factorial of a number
Step 3: Check if the number is 0, if so return 1
Step 4: If the number is not 0, return the result of the number multiplied by the
factorial of the number minus 1
Step 5: Get input for the number from the user
Step 6: Call the factorial function and store the result in a variable
Step 7: Print the factorial of the number
Step 8: Stop the program
34

PROGRAM:
def fact(n):
if n == 0:
return 1
else:
return n*fact(n-1) #function calling itself

#taking input from the user


n = int(input("Enter the number : "))
result=fact(n)
print("The factorial of", n, "is", result)
35

OUTPUT:
Enter the number : 4
The factorial of 4 is 24

RESULT:
Thus, the program to find the factorial of a number using recursion in python
was written and executed successfully.
36

Ex. No. 7.a CONVERT AN INTEGER TO ROMAN NUMERAL


USING CLASS
Date :

AIM:

To write a python program to convert an integer to roman numeral using class

ALGORITHM:

Step 1: Start the program


Step 2: Create a class called RomanConverter
Step 3: In the class, create a dictionary with integer keys and Roman numeral
values
Step 4: Create a list of the integer keys in the dictionary, sorted in descending
order
Step 5: Define a function called "convert" that takes in a number and returns a
string
Step 6: In the "convert" function, create an empty result string
Step 7: Iterate over the sorted integer keys in the dictionary
Step 8: For each integer key, check if the number is greater than or equal to the
key
Step 9: If the number is greater than or equal to the key, add the corresponding
Roman numeral value to the result string and subtract the key from the
number
Step 10: Repeat this process until the number is less than the current key
Step 11: Return the result string
Step 12: Create an instance of the RomanConverter class
Step 13: Get user input for the number to be converted
Step 14: Call the "convert" function on the number and print the result
Step 15: Stop the program
37

PROGRAM:
class RomanConverter:
def __init__(self):
self.num_to_sym_map = {
1: "I",
4: "IV",
5: "V",
9: "IX",
10: "X",
40: "XL",
50: "L",
90: "XC",
100: "C",
400: "CD",
500: "D",
900: "CM",
1000: "M"
}
self.sorted_nums = sorted(self.num_to_sym_map.keys(), reverse=True)

def convert(self, number):


result = ""
for num in self.sorted_nums:
while number >= num:
result += self.num_to_sym_map[num]
number -= num
return result

converter = RomanConverter()
print(converter.convert(int(input("Please enter a number: "))))
38

OUTPUT 1:
Please enter a number: 35
XXXV
OUTPUT 2:
Please enter a number: 994
CMXCIV
OUTPUT 3:
Please enter a number: 1995
MCMXCV
OUTPUT 4:
Please enter a number: 2015
MMXV
OUTPUT 5:
Please enter a number: 2242
MMCCXLII

RESULT:
Thus, the program to Convert an integer to roman numeral using class in
python was written and executed successfully.
39

Ex. No. 7.b SINGLE INHERITANCE AND MULTI-LEVEL


INHERITANCE
Date :

AIM:

To write a python program to perform single Inheritance and Multi Inheritance

ALGORITHM:
Single Inheritance
Step 1: Start the program
Step 2: Define a parent class with a method to display a message
Step 3: Define a child class that inherits from the parent class and has a method
to display a different message
Step 4: Create an instance of the child class
Step 5: Call the method in the child class to display the message
Step 6: Call the method in the parent class to display the message
Step 7: Stop the program
Multilevel Inheritance
Step 1: Start the program
Step 2: Define a grandparent class with a method to display a message
Step 3: Define a parent class that inherits from the grandparent class and has a
method to display a different message
Step 4: Define a child class that inherits from the parent class and has a method
to display a different message
Step 5: Create an instance of the child class
Step 6: Call the method in the grandparent class to display the message
Step 7: Call the method in the parent class to display the message
Step 8: Call the method in the child class to display the message
Step 9: Stop the program
40

PROGRAM:

# Single Inheritance
class parent:
def display(self):
print("PARENT")

class child(parent):
def show(self):
print("CHILD")

c1 = child()
c1.show()
c1.display()

PROGRAM:

# Multi-level Inheritance
class grandparent:
def gdisplay(self):
print("GRAND PARENT")

class parent(grandparent):
def pdisplay(self):
print("PARENT")

class child(parent):
def cdisplay(self):
print("CHILD")

c1 = child()
c1.gdisplay()
c1.pdisplay()
c1.cdisplay()
41

OUTPUT:
E:\pythonProject1>python singleinheritance.py
CHILD
PARENT

OUTPUT:
E:\pythonProject1>python multi-inheritance.py
GRAND PARENT
PARENT
CHILD

RESULT:
Thus, the program to perform single Inheritance and Multi Inheritance to
perform polymorphism in python was written and executed successfully.
42

Ex. No. 7.c POLYMORPHISM


Date :

AIM:

To write a python program to perform polymorphism

ALGORITHM:

Step 1: Start the program


Step 2: Define a dog class with a method to display a sound
Step 3: Define a cat class with a method to display a different sound
Step 4: Define a function that takes an animal type as a parameter and calls the
sound method for that type
Step 5: Create instances of the cat and dog classes
Step 6: Call the makesound function with the cat instance as the parameter
Step 7: Call the makesound function with the dog instance as the parameter
Step 8: Stop the program
43

PROGRAM:

# polymorphism.py
class dog:
def sound(self):
print("bow bow")

class cat:
def sound(self):
print("meow")

def makesound(animaltype):
animaltype.sound()

catobj = cat()
dogobj = dog()
makesound(catobj)
makesound(dogobj)
44

OUTPUT:
E:\pythonProject1\polymorphism.py
meow
bow bow

RESULT:
Thus, the program to perform polymorphism in python was written and
executed successfully.
45

Ex. No. 8 CREATE AND IMPORT MODULE


Date :

AIM:

To write a python program to define a module and import a specific function in


that module to another program.

ALGORITHM:

Step 1: Create a function called fibonacci in the math_tools module


Step 2: Define the variables n1 and n2 and initialize them to 0 and 1
respectively
Step 3: Print n1 and n2
Step 4: Create a for loop to iterate n times
Step 5: Within the for loop, calculate the next value in the fibonacci series as the
sum of n1 and n2
Step 6: If the next value is greater than or equal to the range, break out of the
loop
Step 7: Print the next value in the series
Step 8: Update the values of n1 and n2 to be the previous values of n2 and the
next value in the series respectively
Step 9: End the fibonacci function
Step 10: In the using_fibonacci module, import the fibonacci function from the
math_tools module
Step 11: Get the range value from the user input
Step 12: If the range value is less than 0, print an error message
Step 13: If the range value is valid, call the fibonacci function with the range
value as an argument
46

PROGRAM:
# maths_tools.py

def fibonacci(n):
n1=0
n2=1

print(n1)
print(n2)

for x in range(0,n):
n3 = n1 + n2
if n3 >= n:
break
print(n3,end = '\n')
n1=n2
n2=n3

using_fibonacci.py

from maths_tools import fibonacci

n = int(input("Enter range: "))


if n < 0:
print("Enter correct range!!")
else:
print("FIBONACCI SERIES")
fibonacci(n)
47

OUTPUT:
Enter range: 10
FIBONACCI SERIES
0
1
1
2
3
5
8

RESULT:
Thus, the program to define a module and import a specific function in that
module to another program in python was written and executed successfully.
48

Ex. No. 9 CREATE A SIMPLE CALCULATOR USING FUNCTION


Date :

AIM:

To write a python program to create a simple calculator using function

ALGORITHM:

Step 1: Start the program


Step 2: Define functions for addition, division, multiplication, and subtraction
that get input from the user and perform the respective operation
Step 3: Get input from the user for which operation to perform
Step 4: If the user selects 1, call the addition function and print the result
Step 5: If the user selects 2, call the division function and print the result
Step 6: If the user selects 3, call the multiplication function and print the result
Step 7: If the user selects 4, call the subtraction function and print the result
Step 8: If the user selects an invalid option, print an error message
Step 9: Stop the program
49

PROGRAM:
# Basic calculator
def sum():
a = int(input("Enter 1st No:"))
b = int(input("Enter 2nd No:"))
return a + b

def div():
a = int(input("Enter 1st No:"))
b = int(input("Enter 2nd No:"))
return a / b

def mul():
a = int(input("Enter 1st No:"))
b = int(input("Enter 2nd No:"))
return a * b

def sub():
a = int(input("Enter 1st No:"))
b = int(input("Enter 2nd No:"))
return a - b

print("Enter 1(sum)/2(div)/3(mul)/4(sub)")
i = int(input("Choice :"))
if i == 1:
print(sum())
elif i == 2:
print(div())
elif i == 3:
print(mul())
elif i == 4:
print(sub())
else:
print("Wrong Choice")
50

OUTPUT:
Enter 1(sum)/2(div)/3(mul)/4(sub)
Choice :4
Enter 1st No:5
Enter 2nd No:3
2

RESULT:
Thus, the program to create a simple calculator using function in python was
written and executed successfully.
51

Ex. No. 10.a DRAW STAR USING TURTLE


Date :

AIM:

To write a python program to draw star using turtle programming

ALGORITHM:

Step 1: Start the program


Step 2: Import the turtle and time modules
Step 3: Set up the screen with a specific size and background color
Step 4: Create a turtle object and set its pen size and starting position
Step 5: Create a list of colors to be used for the turtle's pen
Step 6: Begin a loop to draw the shape
Step 7: Set the pen color for the current iteration of the loop
Step 8: Move the turtle forward a certain distance
Step 9: Turn the turtle to the right by a certain angle
Step 10: Repeat the loop for the desired number of iterations
Step 11: Keep the screen open until the user closes it
Step 12: Stop the program
52

PROGRAM:
import turtle
import time
screen=turtle.Screen()
trtl=turtle.Turtle()
screen.setup(420,320)
screen.bgcolor('black')
clr=['red','green','blue','yellow','purple']
trtl.pensize(4)
trtl.penup()
trtl.setpos(-90,30)
trtl.pendown()
for i in range(5):
trtl.pencolor(clr[i])
trtl.forward(200)
trtl.right(144)

turtle.mainloop()
53

OUTPUT:

RESULT:
Thus, the program to draw star using turtle in python was written and executed
successfully.
54

Ex. No. 10.b DRAW SPIRAL HELIX USING TURTLE

Date :

AIM:

To write a python program to draw Spiral Helix Pattern using turtle


programming

ALGORITHM:

Step 1: Start the program


Step 2: Import the turtle module
Step 3: Set up the screen
Step 4: Set the turtle's speed and appearance
Step 5: Begin a loop to draw the shapes
Step 6: Draw a circle with a radius that increases by 5 for each iteration of the
loop
Step 7: Draw a circle with a radius that decreases by 5 for each iteration of the
loop
Step 8: Turn the turtle left by a certain angle for each iteration of the loop
Step 9: Repeat the loop for the desired number of iterations
Step 10: Keep the screen open until the user clicks to close it
Step 11: Stop the program
55

PROGRAM:
import turtle
loadWindow = turtle.Screen()

turtle.speed(0)
turtle.color("red")
turtle.pensize(3)
for i in range(45):
turtle.circle(5*i)
turtle.circle(-5*i)
turtle.left(i)

turtle.exitonclick()
56

OUTPUT:

RESULT:
Thus, the program to draw Spiral Helix Pattern using turtle in python was
written and executed successfully.
57

Ex. No. 10.c DRAW RAINBOW BENZENE USING TURTLE


Date :

AIM:

To write a python program to draw Rainbow Benzene using Turtle


Programming

ALGORITHM:
Step 1: Start the program
Step 2: Import the turtle module
Step 3: Create a list of colors to be used for the turtle's pen
Step 4: Set up the screen with a specific background color
Step 5: Create a turtle object and set its speed
Step 6: Begin a loop to draw the shapes
Step 7: Set the pen color for the current iteration of the loop using the modulo
operator
Step 8: Set the pen width for the current iteration of the loop
Step 9: Move the turtle forward a certain distance based on the current iteration
of the loop
Step 10: Turn the turtle left by a certain angle for each iteration of the loop
Step 11: Repeat the loop for the desired number of iterations
Step 12: Keep the screen open until the user closes it
Step 13: Stop the program
58

PROGRAM:
import turtle
colors= ['red','purple','blue','green','orange','yellow',]
t= turtle.Pen()
turtle.bgcolor('black')
t.speed(50)
for x in range(200):
t.pencolor(colors[x%6])
t.width(x/100+1)
t.forward(x)
t.left(59)

turtle.mainloop()
59

OUTPUT:

RESULT:
Thus, the program to draw Rainbow Benzene using Turtle in Python was
written and executed successfully.
60

Ex. No. 10.d DESIGN FOOTPRINT USING TURTLE


Date :

AIM:

To write a Python Program to Design footprint using turtle.

ALGORITHM:

Step 1: Start the program


Step 2: Import the turtle and time modules
Step 2: Set up the screen and create a turtle object
Step 3: Set the screen's background to a specific image file and the turtle's shape
and color
Step 4: Set a starting value for the turtle's movement distance and lift the pen to
move the turtle to a specific starting position
Step 5: Begin a loop to draw the shapes, incrementing the movement distance
and turning the turtle right by a certain angle each iteration
Step 6: Leave a stamp of the turtle's current position on the screen and move the
turtle forward the set distance
Step 7: Pause the program for a specific amount of time
Step 8: Repeat the loop for the desired number of iterations
Step 9: Keep the screen open until the user closes it
Step 10: Stop the program
61

PROGRAM:
import turtle
import time

screen=turtle.Screen()
trtl=turtle.Turtle()
screen.setup(976,553)
screen.bgpic('bg.png')
trtl.shape('turtle')
trtl.color('red','black')
s=20
trtl.penup()
trtl.setpos(30,30)
for i in range(28):
s=s+2
trtl.stamp()
trtl.forward(s)
trtl.right(25)
time.sleep(0.25)

turtle.mainloop()
62

OUTPUT:

RESULT:
Thus, the program to design footprint using turtle in python was written and
executed successfully.
63

Ex. No. 11 CREATE TURTLE PROGRAM USING FUNCTIONS


Date :

AIM:

To Create turtle program using functions in python

ALGORITHM:

Step 1: Start the program


Step 2: Import the turtle module
Step 3: Define a function to draw a square with a given size, color, and thickness
Step 4: Set the pen color and size using the given parameters
Step 5: Use a loop to make the turtle move in a square shape with the given size
Step 6: Create a turtle and set its position
Step 7: Draw a square using the draw_square function and the specified size, color,
and thickness
Step 8: Move the turtle and draw another square using the same function and
different size, color, and thickness
Step 9: Stop the program
64

PROGRAM:
functions_with_turtle.py
import turtle

def draw_square(t, size, color, thickness):


t.pencolor(color)
t.pensize(thickness)
# Make the turtle move in a square with the specified size
for i in range(4):
t.forward(size)
t.right(90)

# Create a turtle and set its position


t = turtle.Turtle()
t.penup()
t.goto(-100, 0)
t.pendown()

# Use the turtle to draw a square with a size of 100 pixels


draw_square(t, 100, "green", 5)

# Move the turtle and draw another square with a size of 150 pixels
t.penup()
t.forward(150)
t.pendown()
draw_square(t, 150, "red", 10)
65

OUTPUT:

RESULT:
Thus, the turtle program was created using functions in python and executed
successfully.
66

Ex. No. 12 DESIGN TEXT EDITOR USING PYTHON TKINTER(TK)


Date :

AIM:

To design a text editor using python tk.

ALGORITHM:

Step 1: Start the program


Step 2: Import the tkinter module
Step 3: Create the main window and set the title
Step 4: Create a text widget and add it to the main window
Step 5: Create a scrollbar widget and add it to the main window
Step 6: Link the scrollbar to the text widget
Step 7: Create a menu bar and add it to the main window
Step 8: Create a file menu and add it to the menu bar
Step 9: Create a function to save the contents of the text widget to a file
Step 10: Add a "Save" option to the file menu, linked to the save function
Step 11: Start the main event loop
Step 12: Stop the program
67

PROGRAM:
tkinder.py

import tkinter as tk

# create the main window


root = tk.Tk()
root.title("Text Editor")

# create a text widget to hold the user's text


text = tk.Text(root)
text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)

# create a scrollbar widget to scroll through the text


scrollbar = tk.Scrollbar(root)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)

# link the scrollbar to the text widget


text.config(yscrollcommand=scrollbar.set)
scrollbar.config(command=text.yview)

# create a menu bar and add it to the window


menubar = tk.Menu(root)
root.config(menu=menubar)

# create a file menu and add it to the menu bar


filemenu = tk.Menu(menubar)
menubar.add_cascade(label="File", menu=filemenu)

# add a "Save" option to the file menu


def save_text():
# save the contents of the text widget to a file
with open("text.txt", "w") as f:
f.write(text.get("1.0", tk.END))

filemenu.add_command(label="Save", command=save_text)

# start the main event loop


root.mainloop()
68

OUTPUT:

RESULT:
Thus, the program to design a text editor using python tk was written and
executed successfully.
69

Ex. No. 13.a CREATE, APPEND AND REMOVE LISTS IN PYTHON


Date :

AIM:

To create, append and remove lists in python.


.

ALGORITHM:

Step 1: Start the program


Step 2: Create an empty list called "my_list"
Step 3: Add elements 1, 2, 3, and 4 to the list using the append method
Step 4: Print the list
Step 5: Remove the first element from the list using the pop method
Step 6: Print the list again
Step 7: Stop the program
70

PROGRAM:

append_remove_list.py
my_list = []
# add some elements to the list
my_list.append(1)
my_list.append(2)
my_list.append(3)
my_list.append(4)

# print the list


print(my_list) # [1, 2, 3, 4]

# remove the first element from the list


my_list.pop(0)

# print the list again


print(my_list) # [2, 3, 4]
71

OUTPUT:

[1, 2, 3, 4]

[2, 3, 4]

RESULT:
Thus, the program to create, append and remove lists in python was written and
executed successfully.
72

Ex. No. 13.b TEST WHETHER TWO STRINGS ARE NEARLY EQUAL
Date :

AIM:

To test whether two strings are nearly equal


.
ALGORITHM:
Step 1: Start the program
Step 2: Get input for two strings from the user
Step 3: Initialize a counter for the number of matching characters
Step 4: Loop through each character in the first string
Step 5: Within the first loop, loop through each character in the second string
Step 6: Check if the characters match, if so increment the matching_chars counter and
break the inner loop
Step 7: Calculate the length of the longer string
Step 8: Calculate the similarity ratio as the number of matching characters divided by
the length of the longer string
Step 9: If the similarity ratio is greater than 0.5, print "The strings are nearly equal"
Step 10: If the similarity ratio is not greater than 0.5, print "The strings are not nearly
equal"
Step 11: Stop the program
73

PROGRAM:
string_comparision.py

# define the two strings to compare


string1 = input("Enter first string : ")
string2 = input("Enter second string : ")

# initialize the number of matching characters


matching_chars = 0

# loop through the characters in the first string


for c1 in string1:
# loop through the characters in the second string
for c2 in string2:
# if the characters match, increment the matching_chars counter
if c1 == c2:
matching_chars += 1
break # stop looping through characters in the second string

# calculate the length of the longer string


max_length = max(len(string1), len(string2))

# calculate the similarity ratio as the number of matching characters divided by the
length of the longer string
similarity = matching_chars / max_length

if similarity > 0.5:


print("The strings are nearly equal")
else:
print("The strings are not nearly equal")
74

OUTPUT 1:
Enter first string : Bharath University
Enter second string : Computer Science
The strings are not nearly equal

OUTPUT 2:
Enter first string : Bharath University
Enter second string : Bharath Uni
The strings are nearly equal

RESULT:
Thus, the program to test whether two strings are nearly equal was written
and executed successfully.
75

Ex. No. 14.a FIND ALL DUPLICATES AND UNIQUE IN THE LIST
Date :

AIM:

To write a python program to find all duplicates and unique elements in a list.

ALGORITHM:

Step 1: Start the program


Step 2: Create lists to store unique, duplicate and input elements
Step 3: Ask the user to enter the numbers
Step 4: Split the user input by spaces and add the numbers to the list
Step 5: Convert the list of strings to a list of integers
Step 8: Iterate over the list of numbers
Step 7: Check if the number is already in the unique list
Step 8: If the number is not in the unique list, add it to the unique list
Step 9: If the number is already in the unique list, add it to the duplicates list
Step 10: Print the unique numbers and duplicates
Step 11: Stop the program
76

PROGRAM:

list_unique_and_duplicates.py

# create an empty list to store unique elements


unique = []

# create an empty list to store duplicates


duplicates = []

# create an empty list to store the input numbers


numbers = []

# ask the user to enter the numbers


user_input = input("Enter the numbers, separated by a space: ")

# split the user input by spaces and add the numbers to the list
numbers = user_input.split()

# convert the list of strings to a list of integers


numbers = [int(number) for number in numbers]

# iterate over the list of numbers


for number in numbers:
# check if the number is already in the unique list
if number not in unique:
# if the number is not in the unique list, add it to the unique list
unique.append(number)
else:
# if the number is already in the unique list, it is a duplicate
# add it to the duplicates list
duplicates.append(number)

# print the unique numbers


print("Unique numbers: ", unique)

# print the duplicates


print("Duplicates: ", duplicates)
77

OUTPUT:

Enter the numbers, separated by a space: 4 5 5 5 7


Unique numbers: [4, 5, 7]
Duplicates: [5, 5]

RESULT:
Thus, the program to write a python program to find all duplicates and unique
elements in a list was written and executed successfully.
78

Ex. No. 14.b FIND MEAN, MEDIAN, MODE FOR THE GIVEN SET OF
NUMBERS IN A LIST
Date :

AIM:

To write a python program to find the mean, median and mode of a list.

ALGORITHM:

Step 1: Start the program


Step 2: Import the statistics module
Step 3: Get the list of numbers from the user
Step 4: Convert the list of numbers from a string to a list of integers
Step 5: Calculate the mean of the numbers using the mean function from the statistics
module
Step 6: Calculate the median of the numbers using the median function from the
statistics module
Step 7: Calculate the mode of the numbers using the mode function from the statistics
module
Step 8: Print the mean, median, and mode of the numbers
Step 9: Stop the program
79

PROGRAM:

Mean_median_mode.py

import statistics

# Get the list of numbers from the user


numbers = input("Enter a list of numbers, separated by a space: ")
# Convert the string of numbers into a list of numbers
numbers = numbers.split()
numbers = [int(number) for number in numbers]

mean = statistics.mean(numbers)
median = statistics.median(numbers)
mode = statistics.mode(numbers)

print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)
80

OUTPUT:

Enter a list of numbers, separated by a space: 4 5 6 7 7


Mean: 5.8
Median: 6
Mode: 7

RESULT:
Thus, the program to find mean, median, mode for the given set of numbers in
a list Was written and executed successfully.
81

Ex. No. 15 DEMONSTRATE WORKING WITH SET, TUPLES AND


COMMAND LINE ARGUMENTS
Date :

AIM:

To write a python program to demonstrate working with set, tuples and


command line arguments.

ALGORITHM:
Step 1: Start the program
Step 2: Import the sys module
Step 3: Print the first command line argument passed to the program
Step 4: If the first command line argument is 'set', create a set with values 1, 2, 3, 4,
and 5
Step 5: Print the values in the set
Step 6: Get input from the user for a number to add to the set and add it to the set
Step 7: Get input from the user for a number to remove from the set and remove it
from the set and print values in the set
Step 8: If the first command line argument is 'tuple', create a tuple with the days of
the week
Step 9: Print the tuple and its length
Step 10: Get input from the user for the index of an element in the tuple and print the
element
Step 11: If the first command line argument is not 'set' or 'tuple', print an error
message
Step 12: Stop the program
82

PROGRAM:

cmd_set_tuples.py

import sys

# Access a command line argument


print(sys.argv[1])

if sys.argv[1] == 'set':
numbers = {1, 2, 3, 4, 5}
print("The values in set are : ", numbers)

numbers.add(int(input('Enter a number to add to the set : ')))

numbers.remove(int(input("Enter a number to remove from the set : ")))

print("The values in set are : ", numbers)

elif sys.argv[1] == 'tuple':


my_tuple = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday", "Sunday")

print(my_tuple)
print("Length of the tuple is ", len(my_tuple))

print(my_tuple[int(input('Enter the index of the element to print : '))])

else:
print('Invalid command line argument')
83

OUTPUT:

RESULT:
Thus, the program to demonstrate working with set, tuples and command line
arguments was written and executed successfully.
84

Ex. No. 16 COUNT CHARACTERS IN A STRING AND STORE IN


DICTIONARY
Date :

AIM:
To write a program to Count the numbers of characters in the string and store
them in a dictionary data structure

ALGORITHM:

Step 1: Start the program


Step 2: Create an empty dictionary
Step 3: Get input for a string from the user
Step 4: Iterate through each character in the string
Step 5: Check if the character is already in the dictionary
Step 6: If the character is in the dictionary, increment its count
Step 7: If the character is not in the dictionary, add it to the dictionary with a count
of 1
Step 8: Print the dictionary with the characters and their counts
Step 9: Stop the program
85

PROGRAM:

dict={}
word = input("Enter the String : ")
for i in word:
if i in dict:
dict[i] += 1
else:
dict[i] = 1

print ("{characters:count}")

for key, val in dict.items():


print(f'{key} : {val}')
86

OUTPUT:

Enter the String : this is a python program


{characters:count}
t:2
h:2
i:2
s:2
:4
a:2
p:2
y:1
o:2
n:1
r:2
g:1
m:1

RESULT:
Thus, the program to count characters in a string and store in dictionary was
written and executed successfully.
87

Ex. No. 17.a PRINT EACH LINE OF A FILE IN REVERSE ORDER


Date :

AIM:
To write a program to print each line of a file in reverse order.

ALGORITHM:

Step 1: Start the program


Step 2: Get the name of the file from the user
Step 3: Open the file in read mode
Step 4: Read the contents of the file into a list of lines
Step 5: Iterate over the list of lines
Step 6: For each line, print the line reversed using slicing
Step 7: Close the file
Step 8: Stop the program
88

PROGRAM:

filename = input("Enter the file name : ")


file = open(filename, 'r')
print("The Reversed contents of the file : ")
lines = file.readlines()
for line in lines:
print(line[::-1])
89

OUTPUT:

Enter the file name :


showthis.txt
The Reversed contents of the file :

.kratS ynoT ma I !iH


eranoilliB-itluM a ma I

RESULT:
Thus, the program to print each line of a file in reverse order was written and
executed successfully.
90

Ex. No. 17.b PRINT ALL OF THE UNIQUE WORDS IN THE TEXT
FILE IN ALPHABETICAL ORDER
Date :

AIM:
To write a python program to print all of the unique words in the text file in
alphabetical order.

ALGORITHM:

Step 1: Start the program


Step 2: Prompt the user to enter the file name
Step 3: Read the file and store the contents in a variable
Step 4: Split the contents of the file into a list of words
Step 5: Print the list of words
Step 6: Sort the list of words
Step 7: Initialize an empty list for unique words
Step 8: Iterate through the list of words and add unique words to the unique list
Step 9: Print the unique words
Step 10: Stop the program
91

PROGRAM:

print("Enter the file name : ")


filename = input()
file = open(filename, 'r')

uniq = []
words = []

for i in file:
words = words + i.split()
print("The Contents of the file : ")
for word in words:
print(word, end=" ") words.sort()
for j in words:
if j in uniq:
continue
else:
uniq.append(j)

print("\n\nThe Unique words in that file : ")


for k in uniq:
print(k)
92

OUTPUT:

Enter the file name :


uniqtest.txt
The Contents of the file :
this is a python program welcome to python

The Unique words in that file :


a
is
program
python
this
to
welcome

RESULT:
Thus, the program to print all of the unique words in the text file in
alphabetical order was written and executed successfully.
93

Ex. No. 18.a COMPUTE THE NUMBER OF CHARACTERS, WORDS


AND LINES IN A FILE
Date :

AIM:
To write a python program to compute the number of characters, words and
lines in a text file.

ALGORITHM:

Step 1: Start the program


Step 2: Prompt the user for a file name and store it in a variable
Step 3: Open the file for reading
Step 4: Initialize variables for number of lines, words, and characters
Step 5: Loop through each line in the file
Step 6: Increment the number of lines by 1
Step 7: Split the line into words and add the number of words to the total number of
words
Step 8: Add the length of the line to the total number of characters
Step 9: Print the number of lines, words, and characters
Step 10: Stop the program
94

PROGRAM:
no_of_words = 0
no_of_lines = 0
no_of_chars = 0

f = input("Enter the file name : ")


file = open(f, 'r')

for l in file:
no_of_lines += 1
no_of_words += len(l.split())
no_of_chars += len(l)

print("Lines : ", no_of_lines)


print("Words : ", no_of_words)
print("Characters : ", no_of_chars)
95

OUTPUT:
Enter the file name : count.txt
Lines : 14
Words : 704
Characters : 4413

RESULT:
Thus, the program to compute the number of characters, words and lines in a
text file was written and executed successfully.
96

Ex. No. 18.b FIND THE NUMBER OF OCCURRENCES OF A LETTER


IN A TEXT FILE
Date :

AIM:

To write a python program to count the occurrences of a letter in a text file.

ALGORITHM:

Step 1: Start the program


Step 2: Get the file name from the user and open in read mode
Step 3: Get the letter to count from the user
Step 4: Initialize a count variable to 0
Step 5: Iterate through each line in the file
Step 6: Split the line into a list of words
Step 7: Iterate through each word in the list
Step 8: Iterate through each character in the word
Step 9: If the character matches the letter, increment the count variable
Step 10: Print the count variable
Step 11: Stop the program
97

PROGRAM:
count = 0

f = input("Enter the file name : ")


file = open(f, 'r')
letter = input("Enter the letter : ")

for l in file:
words = l.split()
for i in words:
for j in i:
if j == letter:
count += 1
print(count)
98

OUTPUT:
Enter the file name : letter.txt
Enter the letter : g
6

RESULT:
Thus, the program to count the occurrences of a letter in a text file was written
and executed successfully.
99

Ex. No. 19 READ CONTENT FROM ONE FILE AND WRITE IN


ANOTHER
Date :

AIM:
To write a python program to design file to take the contents of the first file
should be input and written to the second file.

ALGORITHM:

Step 1: Start the program


Step 2: Get the names of the first and second files from the user
Step 3: Open the first file in read mode and the second file in write mode
Step 4: Read the lines of the first file and store them in a list
Step 5: Loop through the list of lines and write each line to the second file
Step 6: Close the second file
Step 7: Open the second file in read mode and store the lines in a list and print it
Step 8: Stop the program
100

PROGRAM:

file1 = input("Enter the First File : ")


file2 = input("Enter the Second File : ")

file1con = open(file1, 'r')


file2con = open(file2, 'w')
file1lines = file1con.readlines()
for i in range(len(file1lines)):
file2con.write(file1lines[i])

file2con.close()

print("The contents of First File is copied to the Second File!!!")


file2con = open(file2, 'r')

file2lines = file2con.readlines()
print(file2lines)
101

OUTPUT:

Enter the First File : file1.txt


Enter the Second File : file2.txt

The contents of First File is copied to the Second File!!!


['Pain Konan Zetsu Orochimaru Sasori Itachi Kisame Deidara Kakuzu Hidan
Tobi']

RESULT:
Thus, the program to take the contents of the first file and write to the second
file was written and executed successfully.
102

Ex. No. 20 DEMONSTRATE EXCEPTION HANDLING


Date :

AIM :
To write a python program to demonstrate Exception Handling.

ALGORITHM:

Step 1: Start the program


Step 2: Ask the user to input a value for "a" and store it in a variable
Step 3: Ask the user to input a value for "b" and store it in a variable
Step 4: Try to divide "a" by "b" and store the result in a variable
Step 5: If a ZeroDivisionError occurs, print "Can't divide by zero" and the error
message
Step 6: If a ValueError occurs, print "Numbers Only" and the error message
Step 7: If no errors occur, print the result of the division
Step 8: Print "Exception Handling Works Correctly"
Step 9: Stop the program
103

PROGRAM:

try:
a = int(input("Enter a : "))
b = int(input("Enter b :))
c = a/b
print(a, "/", b, " = ", c)
except ZeroDivisionError:
print("Can't divide by zero..")
except ValueError:
print("Numbers Only!!")

print("Exception Handling Works Correctly!!")


104

OUTPUT 1:
Enter a :
23Enter
b:0
Can't divide by zero..
Exception Handling Works Correctly!!

OUTPUT 2:
Enter a : 23
Enter b : adv
Numbers
Only!!
Exception Handling Works Correctly!!

RESULT:
Thus, the program to demonstrate Exception Handling was written and
executed successfully.

You might also like