Python Record With Front Page and Result
Python Record With Front Page and Result
(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited
in the………………………………………………………………………………laboratory of
Date: Date:
Register No :
INDEX
Pg
Exp.No. DATE EXPERIMENT NAME MARK SIGN
No.
Nehru Institute of Technology
(Autonomous)
Approved by AICTE, New Delhi & Affiliated to Anna University, Chennai
Recognized by UGC with Section 2(f), Accredited by NAAC with A+, NBA Accredited
Average
Exp No: 1
Find Minimum in a List
Date :
AIM:
To find the minimum value in a list of numbers.
ALGORITHM:
Step-1. Initialize a variable min_value with the first element of the list.
Step-2. Iterate through the remaining elements of the list.
Step-3. For each element, if it's smaller than min_value, update min_value to
that element.
Step-4. After iterating through all elements, min_value will hold the
minimum value in the list.
PROGRAM:
1
OUTPUT:
RESULT:
2
Exp No: 2
Insert a Card in a List of Sorted Cards
Date :
AIM:
To insert a card into a list of sorted cards while keeping the list sorted.
ALGORITHM:
Step-1. Start by identifying the correct position where the new card should be
inserted to maintain the sorted order.
Step-2. Iterate through the sorted list.
Step-3. Compare the value of the new card with each card in the sorted list
until you find a card with a greater value or reach the end of the list.
Step-4. Once you find the correct position, insert the new card at that index
in the list.
Step-5. The list remains sorted with the new card inserted.
PROGRAM:
3
15 sorted_cards = [2, 4, 6, 8, 10]
16 new_card = 5
17 insert_card(sorted_cards, new_card)
18
19 print("Sorted cards after inserting", new_card, ":", sorted_cards)
OUTPUT:
RESULT:
4
Exp No: 3
Guess an Integer Number in a Range
Date :
AIM:
To create a program that guesses an integer number within a specified range.
ALGORITHM:
Step-1. Define the range within which the number should be guessed.
Step-2. Initialize a variable to store the guessed number.
Step-3. Use a guessing strategy to narrow down the range of possible
numbers until the correct number is guessed.
Step-4. Output the guessed number.
PROGRAM:
5
OUTPUT:
RESULT:
Thus, the program that guesses an integer number within a specified range has been
successfully created
6
Exp No: 4
Towers of Hanoi
Date :
AIM:
To solve the Towers of Hanoi problem for a given number of disks, moving
them from one peg to another, obeying the rules of the game.
ALGORITHM:
Step-1. Define three pegs: source (where the disks start), auxiliary (a spare
peg), and destination (where the disks should end up).
Step-2. Recursively move the top n-1 disks from the source peg to the
auxiliary peg, using the destination peg as a temporary location.
Step-3. Move the largest disk from the source peg to the destination peg.
Step-4. Recursively move the n-1 disks from the auxiliary peg to the
destination peg, using the source peg as a temporary location.
PROGRAM:
7
14 destination_peg = "C"
15 print("Steps to solve the Towers of Hanoi with", n, "disks:")
16 towers_of_hanoi(n, source_peg, auxiliary_peg, destination_peg)
OUTPUT:
RESULT:
8
Exp No: 5
Exchange the Values of Two Variables
Date :
AIM:
The aim of this program is to exchange the values of two variables.
ALGORITHM:
Step-1. Start
Step-2. Initialize two variables, a and b, with some values.
Step-3. Print the values of a and b before swapping.
Step-4. Exchange the values of a and b using a temporary variable.
Step-5. Print the values of a and b after swapping.
Step-6. Stop
PROGRAM:
9
16 print("a = ", a)
17 print("b = ", b)
OUTPUT:
RESULT:
10
Exp No: 6
Circulate the Values of n Variables
Date :
AIM:
The aim of this program is to circulate the values of n variables.
ALGORITHM:
Step-1. Start
Step-2. Initialize n variables with some values.
Step-3. Print the values of all variables before circulating.
Step-4. Circulate the values of the variables.
Step-5. Print the values of all variables after circulating.
Step-6. Stop
PROGRAM:
11
OUTPUT:
RESULT:
12
Exp No: 7
Distance between Two points
Date :
AIM:
To calculate the distance between two points in a two-dimensional space.
ALGORITHM:
Step-1. Given two points with coordinates (x1, y1) and (x2, y2),
Step-2. where (x1, y1) represents the coordinates of the first point and (x2,
y2) represents the coordinates of the second point.
Step-3. Use the Euclidean distance formula to calculate the distance between
the two points
Step-4. Distance = ?((x2 - x1)^2 + (y2 - y1)^2)
PROGRAM:
13
OUTPUT:
RESULT:
14
Exp No: 8
Simple Square root, Exponentiation
Date :
AIM:
To calculate the square root and exponentiation of a number using Python.
ALGORITHM:
Step-1. Square Root: Use the math.sqrt() function from the math module
Step-2. to calculate the square root of a number.
Step-3. Exponentiation: Use the ** operator to perform exponentiation in
Python.
Step-4. For example, a ** b calculates a^b.
PROGRAM:
15
OUTPUT:
RESULT:
16
Exp No: 9
Voter’s Age Validation
Date :
AIM:
To validate whether a person's age qualifies them to vote.
ALGORITHM:
Step-1. Prompt the user to input their age.
Step-2. Check if the age is greater than or equal to the minimum voting age
(usually 18 years old).
Step-3. If the age meets the criteria, display a message indicating that the
person is eligible to vote.
Step-4. If the age does not meet the criteria, display a message indicating that
the person is not eligible to vote.
PROGRAM:
17
OUTPUT:
RESULT:
18
Exp No: 10
Pyramid Pattern
Date :
AIM:
The aim of this program is to print a pyramid pattern using iterative loops and
conditionals.
ALGORITHM:
Step-1. Start
Step-2. Prompt the user to input the number of rows for the pyramid pattern.
Step-3. Generate and print the pyramid pattern using iterative loops and
conditionals.
Step-4. Stop
PROGRAM:
1 # A Python Program for Pyramid Pattern
2 # Print a pyramid pattern of asterisks
3 rows = int(input("Enter the number of rows for the pyramid pattern: "))
4
5 for i in range(1, rows + 1):
6 print(" " * (rows - i) + "* " * i)
19
OUTPUT:
RESULT:
20
Exp No: 11
Binary Search
Date :
AIM:
The aim of this program is to do binary search in a list of numbres.
ALGORITHM:
Step-1. Given a sorted array and a target value to search.
Step-2. Set two pointers, low and high, initially pointing to the first and last
elements of the array, respectively.
Step-3. While low is less than or equal to high, do:
Step-4. Calculate the middle index as (low + high) // 2.
Step-5. If the middle element is equal to the target, return its index.
Step-6. If the middle element is greater than the target, update high to mid -
1.
Step-7. If the middle element is less than the target, update low to mid + 1.
Step-8. If the target is not found in the array, return -1.
21
PROGRAM:
01 # A Python Program for Binary Search
02
03 def binary_search(arr, target):
04 low = 0
05 high = len(arr) - 1
06
07 while low <= high:
08 mid = (low + high) // 2
09 if arr[mid] == target:
10 return mid
11 elif arr[mid] < target:
12 low = mid + 1
13 else:
14 high = mid - 1
15
16 return -1
17
18 # Example usage:
19 arr = [2, 3, 5, 7, 9, 11, 13]
20 print (arr)
21 target = int(input("Enter the target element: "))
22 result = binary_search(arr, target)
23
24 if result != -1:
25 print("Element ", target, " is present at index ", result)
26 else:
27 print("Element ", target, " is not present in the array.")
28
22
OUTPUT:
RESULT:
23
Exp No: 12
Linear Search
Date :
AIM:
The aim of this program is to search for a target value in a list using the linear
search algorithm.
ALGORITHM:
Step-1. Given a list and a target value to search.
Step-2. Iterate through each element in the list:
Step-3. If the current element is equal to the target, return its index.
Step-4. If the target is not found in the list, return -1.
PROGRAM:
01 # A Python Program for Linear Search
02 def linear_search(arr, target):
03 for index in range(len(arr)):
04 if arr[index] == target:
05 return index
06 return -1
07
08 # Example usage:
09 arr = [10, 20, 30, 40, 50]
10 print(arr)
11 target = int(input("Enter Target Element: "))
12 result = linear_search(arr, target)
13
14 if result != -1:
15 print("Element ", target, " is present at index ", result)
16 else:
17 print("Element ", target, " is not present in the list.")
18
24
OUTPUT:
RESULT:
Thus, search for a target value in a list using the linear search algorithm is
completed successfully
25
Exp No: 13
Simple Sorting
Date :
AIM:
The aim of this program is to sort a list of numbers using the bubble sort
algorithm.
ALGORITHM:
Step-1. Given a list of numbers.
Step-2. Repeat the following steps for each element in the list:
Step-3. Iterate through the list from the beginning to the end.
Step-4. Compare each pair of adjacent elements.
Step-5. If the current element is greater than the next element, swap them.
Step-6. Repeat step 2 until no swaps are needed (the list is sorted).
PROGRAM:
01 # A Python Program for Bubble Sort
02 def bubble_sort(arr):
03 n = len(arr)
04 for i in range(n):
05 for j in range(0, n - i - 1):
06 if arr[j] > arr[j + 1]:
07 arr[j], arr[j + 1] = arr[j + 1], arr[j]
08
09 # Example usage:
10 arr = [64, 34, 25, 12, 22, 11, 90]
11 print("The Given array is:", arr)
12 bubble_sort(arr)
13 print("Sorted array is:", arr)
26
OUTPUT:
RESULT:
Thus, the program is to sort a list of numbers using the bubble sort algorithm is
completed successfully
27
Exp No: 14
Word Count
Date :
AIM:
The aim of this program is to count the occurrences of each word in a given
text.
ALGORITHM:
Step-1. Given a string of text.
Step-2. Split the text into words using spaces as delimiters.
Step-3. Create an empty dictionary to hold the word counts.
Step-4. Iterate through each word in the list:
Step-5. If the word is already in the dictionary, increment its count.
Step-6. If the word is not in the dictionary, add it with a count of 1.
Step-7. Return the dictionary with word counts.
PROGRAM:
01 # A Python Program for Word Count
02 def word_count(text):
03 words = text.split()
04 word_counts = {}
05
06 for word in words:
07 word = word.lower() # Optional: Normalize to lowercase
08 if word in word_counts:
09 word_counts[word] += 1
10 else:
11 word_counts[word] = 1
12
13 return word_counts
14
15 # Example usage:
16 text = "This is a test. This test is only a test."
17 print("The Given Text :", text)
18 result = word_count(text)
19
20 print("Word Counts: ", result)
28
OUTPUT:
RESULT:
Thus, the program is to count the occurrences of each word in a given text is
completed successfully
29
Exp No: 15
Copy File
Date :
AIM:
The aim of this task is to create a Python program that copies the contents of
one file to another using an algorithm that reads the content from the source
file and writes it to the destination file.
ALGORITHM:
Step-1. Open the Source File: Open the file that you want to copy from in
read mode.
Step-2. Read the Contents: Read the content of the source file.
Step-3. Open/Create the Destination File: Open the file that you want to copy
to in write mode. If the file does not exist, it will be created.
Step-4. Write the Contents: Write the content read from the source file to the
destination file.
Step-5. Close Both Files: Close both the source and destination files to
ensure all data is properly written and resources are released.
30
PROGRAM:
01 # A Python Program to Copy a File
02 def copy_file(source_file, destination_file):
03 try:
04 # Open the source file in read mode
05 with open(source_file, 'r') as src:
06 # Read the content from the source file
07 content = src.read()
08
09 # Open the destination file in write mode
10 with open(destination_file, 'w') as dst:
11 # Write the content to the destination file
12 dst.write(content)
13
14 print(f"File copied successfully from {source_file} to
{destination_file}.")
15 except FileNotFoundError:
16 print(f"Error: The file {source_file} does not exist.")
17 except IOError as e:
18 print(f"An I/O error occurred: {e}")
19
20 # Example usage
21 source_file = 'Exp-15.py'
22 destination_file = 'destination.txt'
23 copy_file(source_file, destination_file)
24
31
OUTPUT:
RESULT:
32
Exp No: 16
VOTER’S AGE VALIDATION
Date :
AIM:
The aim of this task is to create a Python program that validates whether a
person is eligible to vote based on their age. The typical voting age is 18 years
and older. The program will take the person's birth year as input, calculate
their age, and determine if they are eligible to vote.
ALGORITHM:
Step-1. Input the Birth Year: Prompt the user to enter their birth year.
Step-2. Calculate the Current Year: Get the current year from the system.
Step-3. Calculate the Age: Subtract the birth year from the current year to
determine the person's age.
Step-4. Check Eligibility:
Step-5. If the age is 18 or older, the person is eligible to vote.
Step-6. If the age is less than 18, the person is not eligible to vote.
Step-7. Display the Result: Print a message indicating whether the person is
eligible to vote or not.
33
PROGRAM:
01 # A Python Program to Validate Age of Voter From YOB
02 from datetime import datetime
03
04 def is_eligible_to_vote(birth_year):
05 current_year = datetime.now().year
06 age = current_year - birth_year
07
08 if age >= 18:
09 return True, age
10 else:
11 return False, age
12
13 def main():
14 try:
15 birth_year = int(input("Enter your year of birth: "))
16 eligible, age = is_eligible_to_vote(birth_year)
17
18 if eligible:
19 print(f"You are {age} years old. You are eligible to vote.")
20 else:
21 print(f"You are {age} years old. You are not eligible to vote.")
22 except ValueError:
23 print("Invalid input. Please enter a valid year.")
24
25 if __name__ == "__main__":
26 main()
34
OUTPUT:
RESULT:
35
Exp No: 17
MARKS RANGE VALIDATION
Date :
AIM:
The aim of this task is to create a Python program that validates whether a
given mark falls within a specified range. Typically, marks are expected to be
within the range of 0 to 100. The program will take the mark as input and
determine if it is valid based on this range.
ALGORITHM:
Step-1. Input the Mark: Prompt the user to enter their mark.
Step-2. Check if the Mark is a Number: Validate that the input is a number.
Step-3. Validate the Mark:
Step-4. If the mark is within the range of 0 to 100, it is valid.
Step-5. If the mark is outside this range, it is invalid.
Step-6. Display the Result: Print a message indicating whether the mark is
valid or not.
36
PROGRAM:
01 # A Python Program to Validate Marks
02 def is_valid_mark(mark):
03 # Check if the mark is within the valid range
04 return 0 <= mark <= 100
05
06 def main():
07 try:
08 # Prompt the user to enter their mark
09 mark = float(input("Enter your mark: "))
10
11 # Validate the mark
12 if is_valid_mark(mark):
13 print(f"The mark {mark} is valid.")
14 else:
15 print(f"The mark {mark} is invalid. Marks should be between 0
and 100.")
16 except ValueError:
17 print("Invalid input. Please enter a numeric value.")
18
19 if __name__ == "__main__":
20 main()
37
`
OUTPUT:
RESULT:
38