[go: up one dir, main page]

0% found this document useful (0 votes)
44 views68 pages

Class Xi Ics Practical

Uploaded by

jcox71000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
44 views68 pages

Class Xi Ics Practical

Uploaded by

jcox71000
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 68

Program 1: Program to enter two numbers and print the

arithmetic operations like +,-,*, /, // and %.

Algorithm

1.Start.
2.Prompt the user to enter the first number and
store it.
3.Prompt the user to enter the second number and
store it.
4.Perform the following operations:
o Addition: num1 + num2
o Subtraction: num1 - num2
o Multiplication: num1 * num2
o Division: num1 / num2
o Floor Division: num1 // num2
o Modulus: num1 % num2
5.Print the results of each operation.
6.End.

Program

# Program to perform arithmetic operations on two


numbers

# Input from the user

try:

num1 = float(input("Enter the first number: "))

num2 = float(input("Enter the second number: "))

# Perform arithmetic operations

addition = num1 + num2

subtraction = num1 - num2

multiplication = num1 * num2


division = num1 / num2 if num2 != 0 else
'Undefined (division by zero)'

floor_division = num1 // num2 if num2 != 0 else


'Undefined (division by zero)'

modulus = num1 % num2 if num2 != 0 else


'Undefined (division by zero)'

# Print the results

print(f"Addition: {addition}")

print(f"Subtraction: {subtraction}")

print(f"Multiplication: {multiplication}")

print(f"Division: {division}")

print(f"Floor Division: {floor_division}")

print(f"Modulus: {modulus}")

except ValueError:

print("Invalid input! Please enter numeric


values.")

Documentation

Program Overview

This Python program prompts the user to enter two


numbers and performs various arithmetic operations:
addition, subtraction, multiplication, division,
floor division, and modulus. It handles exceptions
for invalid inputs and division by zero.
Code Breakdown

1.User Input
o The program begins by prompting the user to
enter two numeric values.
o The inputs are converted to float for
accurate arithmetic operations.

2.Arithmetic Operations
o The following operations are performed on the
two numbers:
 Addition (+): Calculates the sum of the
two numbers.
 Subtraction (-): Calculates the
difference between the two numbers.
 Multiplication (*): Calculates the
product of the two numbers.
 Division (/): Calculates the quotient.
Returns 'Undefined (division by zero)'
if the second number is zero.
 Floor Division (//): Calculates the
integer quotient. Returns 'Undefined
(division by zero)' if the second number
is zero.
 Modulus (%): Calculates the remainder.
Returns 'Undefined (division by zero)'
if the second number is zero.

3.Output
o The results of the arithmetic operations are
printed to the console.
o If the user inputs a non-numeric value, an
error message is displayed.

Error Handling

 The program uses a try-except block to catch


ValueError exceptions, which occur when the user
inputs non-numeric values. It informs the user to
enter valid numeric values.

Output
Program 2: Write a program to find whether an
inputted number is perfect or not

Algorithm

1.Start.
2.Prompt the user to enter a positive integer and
store it.
3.Initialize a variable to hold the sum of the
divisors.
4.Loop from 1 to half of the input number
(inclusive):
o For each number, check if it is a divisor of
the input number.
o If it is, add it to the sum of divisors.
5.After the loop, check if the sum of divisors is
equal to the input number.
o If they are equal, the number is perfect.
o Otherwise, it is not perfect.
6.Print the result.
7.End.

Program

# Program to check if a number is perfect

# Input from the user

try:

num = int(input("Enter a positive integer: "))

if num < 1:

print("Please enter a positive integer.")

else:

sum_of_divisors = 0

# Loop to find divisors


for i in range(1, num // 2 + 1):

if num % i == 0:

sum_of_divisors += i

# Check if the number is perfect

if sum_of_divisors == num:

print(f"{num} is a perfect number.")

else:

print(f"{num} is not a perfect number.")

except ValueError:

print("Invalid input! Please enter a numeric


value.")

Documentation

Program Overview

This Python program checks whether a given positive


integer is a perfect number. A perfect number is
defined as a number that is equal to the sum of its
proper divisors (excluding itself).

Code Breakdown

1.User Input
o The program prompts the user to enter a
positive integer.
o It converts the input to an integer and
checks if it's positive.

2.Finding Divisors
o A loop iterates from 1 to half of the input
number (inclusive).
o For each iteration, it checks if the loop
index (i) is a divisor of the input number.
o If it is, i is added to the sum_of_divisors.

3.Checking Perfection
o After the loop, the program checks if the
sum_of_divisors is equal to the input number.
o If they are equal, the number is identified
as perfect; otherwise, it is not.

4.Output
o The result is printed to the console.
o If the input is not a valid positive integer,
an error message is displayed.

Output
Program 3: Write a Program to check if the entered
number is Armstrong or not

Algorithm

1.Start.
2.Prompt the user to enter a positive integer and
store it.
3.Convert the number to a string to determine the
number of digits.
4.Initialize a variable to hold the sum of the
digits raised to the power of the number of
digits.
5.Loop through each digit in the number:
o Convert the digit back to an integer.
o Raise it to the power of the number of digits
and add it to the sum.
6.After the loop, check if the sum is equal to the
original number.
o If they are equal, the number is an Armstrong
number.
o Otherwise, it is not an Armstrong number.
7.Print the result.
8.End.

Program

# Program to check if a number is an Armstrong number

# Input from the user

try:

num = int(input("Enter a positive integer: "))

if num < 0:

print("Please enter a positive integer.")

else:
# Convert number to string to find the number
of digits

num_str = str(num)

num_of_digits = len(num_str)

sum_of_powers = 0

# Loop to calculate the sum of the digits


raised to the power of the number of digits

for digit in num_str:

sum_of_powers += int(digit) **
num_of_digits

# Check if the number is an Armstrong number

if sum_of_powers == num:

print(f"{num} is an Armstrong number.")

else:

print(f"{num} is not an Armstrong


number.")

except ValueError:

print("Invalid input! Please enter a numeric


value.")

Documentation

Program Overview

This Python program checks whether a given positive


integer is an Armstrong number. An Armstrong number
(or narcissistic number) for a given number of digits
is a number that is equal to the sum of its own
digits each raised to the power of the number of
digits.

Code Breakdown

1.User Input
o The program prompts the user to enter a
positive integer.
o It converts the input to an integer and
checks if it's non-negative.

2.Finding Number of Digits


o The number is converted to a string to
determine the number of digits.

3.Calculating the Sum of Powers


o A loop iterates through each digit in the
number.
o Each digit is raised to the power of the
number of digits and added to the
sum_of_powers.

4.Checking Armstrong Condition


o After the loop, the program checks if
sum_of_powers is equal to the original
number.
o If they are equal, the number is identified
as an Armstrong number; otherwise, it is not.

5.Output
o The result is printed to the console.
o If the input is not a valid positive integer,
an error message is displayed.

Output
Program 4: Write a Program to find factorial of the
entered number.

Algorithm

1.Start.
2.Prompt the user to enter a non-negative integer
and store it.
3.Initialize a variable to hold the factorial
result, starting with 1.
4.If the input number is 0 or 1, the factorial is
1.
5.Otherwise, loop from 2 to the input number
(inclusive):
o Multiply the result variable by the current
loop index.
6.Print the factorial result.
7.End

Program

# Program to find the factorial of a number

# Input from the user

try:

num = int(input("Enter a non-negative integer:


"))

if num < 0:

print("Please enter a non-negative integer.")

else:

factorial = 1

# Calculate factorial

for i in range(2, num + 1):


factorial *= i

# Output the result

print(f"The factorial of {num} is


{factorial}.")

except ValueError:

print("Invalid input! Please enter a numeric


value.")

Documentation

Program Overview

This Python program calculates the factorial of a


given non-negative integer. The factorial of a non-
negative integer nnn is the product of all positive
integers less than or equal to nnn, denoted as n!n!
n!.

Code Breakdown

1.User Input
o The program prompts the user to enter a non-
negative integer.
o It converts the input to an integer and
checks if it's non-negative.

2.Calculating Factorial
o A variable factorial is initialized to 1.
o If the input number is 0 or 1, the factorial
is directly set to 1.
o Otherwise, a loop iterates from 2 to the
input number (inclusive), multiplying the
factorial variable by each index.

3.Output
o The result is printed to the console.
o If the input is not a valid non-negative
integer, an error message is displayed.

Output
Program 5: Write a Program to enter the number of
terms and to print the Fibonacci Series

Algorithm

1.Start.
2.Prompt the user to enter the number of terms for
the Fibonacci series and store it.
3.Initialize the first two terms of the series (0
and 1).
4.If the number of terms is less than or equal to
0, print an appropriate message.
5.If the number of terms is 1, print the first term
(0).
6.If the number of terms is 2, print the first two
terms (0 and 1).
7.For more than 2 terms:
o Print the first two terms.
o Loop from 2 to the number of terms:
 Calculate the next term as the sum of
the last two terms.
 Print the next term and update the last
two terms.
8.End

# Program to print the Fibonacci series

# Input from the user

try:

terms = int(input("Enter the number of terms in


the Fibonacci series: "))

if terms <= 0:

print("Please enter a positive integer


greater than zero.")

elif terms == 1:
print("Fibonacci Series: 0")

elif terms == 2:

print("Fibonacci Series: 0, 1")

else:

print("Fibonacci Series: 0, 1", end=", ")

# Initialize the first two terms

a, b = 0, 1

# Loop to generate the Fibonacci series

for _ in range(2, terms):

next_term = a + b

print(next_term, end=", ")

a, b = b, next_term

# Print the last term without a trailing


comma

print(next_term)

except ValueError:

print("Invalid input! Please enter a numeric


value.")

Documentation
Program Overview

This Python program generates the Fibonacci series up


to a specified number of terms. The Fibonacci series
is a sequence where each number is the sum of the two
preceding ones, usually starting with 0 and 1.

Code Breakdown

1.User Input
o The program prompts the user to enter the
number of terms for the Fibonacci series.
o It converts the input to an integer and
checks if it is a positive integer.

2.Handling Special Cases


o If the input is less than or equal to 0, an
error message is printed.
o If the input is 1, it prints the first term
(0).
o If the input is 2, it prints the first two
terms (0 and 1).

3.Generating the Series


o For more than 2 terms, the program
initializes the first two terms (0 and 1).
o It then loops to calculate and print the next
terms in the series, updating the last two
terms accordingly.

4.Output
o The Fibonacci series is printed to the
console.
o If the input is not a valid integer, an error
message is displayed.

Output
Program 6: Write a Program to enter the string and to
check if it’s palindrome or not using loop.

Algorithm

1.Start.
2.Prompt the user to enter a string and store it.
3.Convert the string to lowercase to make the check
case-insensitive.
4.Initialize two pointers: one at the beginning of
the string and the other at the end.
5.Use a loop to compare characters at the two
pointers:
o If the characters are not equal, the string
is not a palindrome. Print a message and
exit.
o If the characters are equal, move the left
pointer forward and the right pointer
backward.
6.If all characters are equal, print a message
stating that the string is a palindrome.
7.End.

Program

# Program to check if a string is a palindrome

# Input from the user

input_string = input("Enter a string: ")

# Convert string to lowercase for case-insensitivity

normalized_string = input_string.lower()

# Initialize pointers

left = 0

right = len(normalized_string) - 1
# Check for palindrome

is_palindrome = True

while left < right:

if normalized_string[left] !=
normalized_string[right]:

is_palindrome = False

break

left += 1

right -= 1

# Output the result

if is_palindrome:

print(f'"{input_string}" is a palindrome.')

else:

print(f'"{input_string}" is not a palindrome.')

Documentation

Program Overview

This Python program checks whether a given string is


a palindrome. A palindrome is a string that reads the
same forwards and backwards, ignoring spaces,
punctuation, and case.

Code Breakdown

1.User Input
o The program prompts the user to enter a
string and stores it.

2.Normalization
o The input string is converted to lowercase to
ensure the check is case-insensitive.

3.Pointer Initialization
o Two pointers are initialized: one at the
start (left) and the other at the end (right)
of the string.

4.Checking for Palindrome


o A loop iterates as long as the left pointer
is less than the right pointer:
 It compares the characters at the two
pointers.
 If the characters are not equal, it sets
is_palindrome to False and breaks the
loop.
 If they are equal, the pointers are
moved inward.

5.Output
o After the loop, it checks the value of
is_palindrome:
 If it is still True, the string is a
palindrome; otherwise, it is not.
o The result is printed to the console.
Program 8: Write a Program to enter the numbers in a
list using split () and to use all the functions
related to list.

Algorithm

1.Start.
2.Prompt the user to enter numbers separated by
spaces.
3.Convert the input string into a list of numbers
using split().
4.Perform and display the results of the following
list operations:
o Append a number to the list.
o Insert a number at a specific position.
o Remove a number by value.
o Pop a number by index.
o Sort the list.
o Reverse the list.
o Count the occurrences of a number.
o Find the length of the list.
5.Print the final state of the list.
6.End.

Program

# Program to demonstrate various list functions

# Input from the user

input_list = input("Enter numbers separated by


spaces: ")

# Convert input string to a list of numbers

number_list = [float(num) for num in


input_list.split()]

# Display the original list


print(f"Original List: {number_list}")

# Append a number to the list

number_list.append(10)

print(f"List after appending 10: {number_list}")

# Insert a number at a specific position

number_list.insert(2, 5) # Inserting 5 at index 2

print(f"List after inserting 5 at index 2:


{number_list}")

# Remove a number by value

number_list.remove(5) # Removing the first


occurrence of 5

print(f"List after removing 5: {number_list}")

# Pop a number by index

popped_value = number_list.pop(0) # Popping the


first element

print(f"Popped value: {popped_value}")

print(f"List after popping the first element:


{number_list}")

# Sort the list

number_list.sort()

print(f"Sorted List: {number_list}")


# Reverse the list

number_list.reverse()

print(f"Reversed List: {number_list}")

# Count occurrences of a specific number

count_of_10 = number_list.count(10)

print(f"Occurrences of 10: {count_of_10}")

# Find the length of the list

length_of_list = len(number_list)

print(f"Length of the list: {length_of_list}")

# Final state of the list

print(f"Final List: {number_list}")

Documentation

Program Overview

This Python program takes a list of numbers from the


user, allows the user to perform various operations
on the list, and displays the results. It
demonstrates the use of different list functions such
as append(), insert(), remove(), pop(), sort(),
reverse(), and more.

Code Breakdown

1.User Input
o The program prompts the user to enter numbers
separated by spaces.
2.Converting Input
o The input string is split into individual
elements, and each element is converted to a
float to create a list of numbers.

3.Displaying Original List


o The original list of numbers is printed.

4.List Operations
o Append: A number (10) is added to the end of
the list.
o Insert: A number (5) is inserted at index 2.
o Remove: A number (5) is removed from the
list.
o Pop: The first element is removed and its
value is displayed.
o Sort: The list is sorted in ascending order.
o Reverse: The list is reversed.
o Count: The occurrences of a specific number
(10) are counted.
o Length: The length of the list is determined.

5.Final Output
o The program prints the final state of the
list after all operations.

Output
Program 9: Write a Program to enter the number and
print the Floyd’s Triangle in decreasing order

Algorithm

1.Start.
2.Prompt the user to enter a positive integer
(number of rows for Floyd's Triangle).
3.Initialize a counter to keep track of the current
number to be printed.
4.Create a loop that iterates from the entered
number down to 1 (for decreasing order).
o For each row, print the current row number of
elements in decreasing order.
o Update the counter to the next number.
5.End.

Program

# Program to print Floyd's Triangle in decreasing


order

# Input from the user

try:

rows = int(input("Enter the number of rows for


Floyd's Triangle: "))

if rows <= 0:

print("Please enter a positive integer.")

else:

# Initialize the counter

counter = (rows * (rows + 1)) // 2 # Total


numbers in the triangle
# Print Floyd's Triangle in decreasing order

for i in range(rows, 0, -1): # Start from


'rows' down to 1

for j in range(i): # Print 'i' numbers


in the current row

print(counter, end=" ")

counter -= 1 # Decrement the counter

print() # Move to the next line

except ValueError:

print("Invalid input! Please enter a numeric


value.")

Documentation

Program Overview

This Python program generates Floyd’s Triangle based


on a specified number of rows, displaying the numbers
in decreasing order. Floyd's Triangle is a right-
angled triangular array of natural numbers.

Code Breakdown

1.User Input
o The program prompts the user to enter a
positive integer indicating the number of
rows for Floyd's Triangle.

2.Input Validation
o If the input is less than or equal to zero,
an appropriate message is printed.

3.Counter Initialization
o The counter is initialized to the total
number of elements in the triangle using the
formula (rows×(rows+1))/2(\text{rows} \times
(\text{rows} + 1)) / 2(rows×(rows+1))/2.

4.Generating the Triangle


o The outer loop iterates from the number of
rows down to 1.
o For each row, an inner loop prints the
required number of elements (equal to the
current row number).
o The counter is decremented after printing
each number to display numbers in decreasing
order.

5.Output
o The program prints the Floyd's Triangle to
the console.
Program 10: Write a Program to find factorial of
entered number using user-defined module fact()

Algorithm

Algorithm for fact Module (fact.py)

1.Function Definition: Define the function fact(n).


2.Input Validation:
o If n<0n < 0n<0:
 Return "Factorial is not defined for
negative numbers."
o If n=0n = 0n=0 or n=1n = 1n=1:
 Return 1 (since 0!0!0! and 1!1!1! are
both 1).
3.Factorial Calculation:
o Initialize result to 1.
o For each integer iii from 2 to nnn
(inclusive):
 Multiply result by iii.
4.Return: Return the calculated result.

Algorithm for Main Program (main.py)

1.Import Module: Import the fact module.


2.User Input:
o Prompt the user to enter a non-negative
integer.
3.Input Validation:
o If the input is not a valid integer, display
an error message.
4.Call Function:
o Call the fact() function from the fact module
with the input number.
5.Display Output:
o Print the result of the factorial
calculation.

Program

# fact.py
def fact(n):

"""Calculate the factorial of a given number


n."""

if n < 0:

return "Factorial is not defined for negative


numbers."

elif n == 0 or n == 1:

return 1

else:

result = 1

for i in range(2, n + 1):

result *= i

return result

# main.py

import fact # Import the user-defined module

# Input from the user

try:

num = int(input("Enter a non-negative integer to


find its factorial: "))

# Call the fact function from the fact module

factorial_result = fact.fact(num)

# Output the result


print(f"The factorial of {num} is:
{factorial_result}")

except ValueError:

print("Invalid input! Please enter a non-negative


integer.")

Documentation

Module Overview (fact.py)

 Function: fact(n)
o Purpose: Calculates the factorial of a non-
negative integer nnn.
o Parameters:
 n: A non-negative integer.
o Returns: The factorial of nnn, or an error
message if nnn is negative.

Main Program Overview (main.py)

 Imports: The program imports the fact module.


 User Input: Prompts the user to enter a non-
negative integer.
 Function Call: Calls the fact function from the
fact module.
 Output: Displays the factorial result or an error
message for invalid input.

Output
Program 11: Write a Program to enter the numbers and
find Linear Search, Binary Search, Lowest Number and
Selection Sort using list/array code.

Algorithm

Algorithm for Linear Search

1.Function Definition: Define the function


linear_search(arr, target).
2.Loop: Iterate over each element in arr using its
index.
o If the current element is equal to target,
return the index.
3.Return: If the target is not found, return -1.

Algorithm for Binary Search

1.Function Definition: Define the function


binary_search(arr, target).
2.Initialize Pointers: Set left to 0 and right to
the last index of arr.
3.Loop: While left is less than or equal to right:
o Calculate mid as the average of left and
right.
o If arr[mid] equals target, return mid.
o If arr[mid] is less than target, move left to
mid + 1.
o If arr[mid] is greater than target, move
right to mid - 1.
4.Return: If the target is not found, return -1.

Algorithm for Finding the Lowest Number

1.Function Definition: Define the function


find_lowest(arr).
2.Return: Use the built-in min() function to return
the lowest number in arr.

Algorithm for Selection Sort

1.Function Definition: Define the function


selection_sort(arr).
2.Outer Loop: Iterate through each index i in arr.
3.Find Minimum:
o Initialize min_index to i.
o Inner loop: For each index j from i + 1 to
the end of arr, if arr[j] is less than
arr[min_index], update min_index.
4.Swap: Swap arr[i] with arr[min_index].
5.End.

Program

# Program to perform linear search, binary search,


find lowest number, and selection sort

# Function to perform linear search

def linear_search(arr, target):

for index, value in enumerate(arr):

if value == target:

return index

return -1

# Function to perform binary search

def binary_search(arr, target):

left, right = 0, len(arr) - 1

while left <= right:

mid = (left + right) // 2

if arr[mid] == target:

return mid

elif arr[mid] < target:

left = mid + 1

else:
right = mid - 1

return -1

# Function to find the lowest number

def find_lowest(arr):

return min(arr)

# Function to perform selection sort

def selection_sort(arr):

for i in range(len(arr)):

min_index = i

for j in range(i + 1, len(arr)):

if arr[j] < arr[min_index]:

min_index = j

arr[i], arr[min_index] = arr[min_index],


arr[i] # Swap

# Main program

try:

# Input from the user

input_numbers = input("Enter numbers separated by


spaces: ")

numbers = [float(num) for num in


input_numbers.split()]

# Perform selection sort


selection_sort(numbers)

print(f"Sorted List: {numbers}")

# Find the lowest number

lowest_number = find_lowest(numbers)

print(f"Lowest Number: {lowest_number}")

# Linear Search

target = float(input("Enter a number to search


using Linear Search: "))

linear_result = linear_search(numbers, target)

if linear_result != -1:

print(f"Linear Search: {target} found at


index {linear_result}.")

else:

print(f"Linear Search: {target} not found.")

# Binary Search (requires sorted list)

target_binary = float(input("Enter a number to


search using Binary Search: "))

binary_result = binary_search(numbers,
target_binary)

if binary_result != -1:

print(f"Binary Search: {target_binary} found


at index {binary_result}.")

else:
print(f"Binary Search: {target_binary} not
found.")

except ValueError:

print("Invalid input! Please enter numeric values


only.")

Documentation

Program Overview

This Python program allows users to enter a list of


numbers and performs several operations on it: linear
search, binary search, finding the lowest number, and
sorting the list using selection sort.

Functions Overview

1.Linear Search:
o Function: linear_search(arr, target)
o Purpose: Searches for a specified target in
arr and returns its index or -1 if not found.
o Parameters:
 arr: A list of numbers.
 target: The number to search for.
o Returns: Index of target in arr or -1.

2.Binary Search:
o Function: binary_search(arr, target)
o Purpose: Searches for a specified target in a
sorted arr and returns its index or -1 if not
found.
o Parameters:
 arr: A sorted list of numbers.
 target: The number to search for.
o Returns: Index of target in arr or -1.

3.Finding Lowest Number:


o Function: find_lowest(arr)
o Purpose: Finds and returns the lowest number
in arr.
o Parameters:
 arr: A list of numbers.
o Returns: The lowest number in arr.

4.Selection Sort:
o Function: selection_sort(arr)
o Purpose: Sorts arr in ascending order using
the selection sort algorithm.
o Parameters:
 arr: A list of numbers.
o Returns: The sorted list.

Output
Program 12: Write a Program to read data from data
file and show Data File Handling related functions
utility in python

Algorithm

Algorithm for File Handling Operations

1.Function read_file(filename):
o Input: filename (string) - the name of the
file to read.
o Process:
 Try to open the file in read mode.
 Read all lines from the file and store
them in a list.
 Return the list of lines.
 If the file is not found, return an
error message.

2.Function write_file(filename, data):


o Input:
 filename (string) - the name of the file
to write to.
 data (string) - the data to write to the
file.
o Process:
 Open the file in write mode (this will
overwrite the existing content).
 Write the provided data to the file.

3.Function append_to_file(filename, data):


o Input:
 filename (string) - the name of the file
to append to.
 data (string) - the data to append to
the file.
o Process:
 Open the file in append mode.
 Write the provided data to the file.

4.Function display_file_contents(filename):
o Input: filename (string) - the name of the
file to display.
o Process:
 Call read_file() to get the contents of
the file.
 If the contents are valid (not an error
message), print each line.

5.Main Program:
o Define the filename (data.txt).
o Write initial data to the file (if desired).
o Read and display the contents of the file.
o Append new data to the file.
o Read and display the updated contents of the
file.

Program

# Program to demonstrate data file handling in Python

# Function to read data from the file

def read_file(filename):

try:

with open(filename, 'r') as file:

data = file.readlines()

return data

except FileNotFoundError:

return "File not found."

# Function to write data to the file

def write_file(filename, data):

with open(filename, 'w') as file:

file.write(data)

# Function to append data to the file


def append_to_file(filename, data):

with open(filename, 'a') as file:

file.write(data)

# Function to display contents of the file

def display_file_contents(filename):

contents = read_file(filename)

if isinstance(contents, list):

print("File Contents:")

for line in contents:

print(line.strip())

else:

print(contents)

# Main program

filename = 'data.txt'

# Write initial data to the file

initial_data = "Alice,25,Engineer\nBob,30,Designer\
nCharlie,22,Developer\n"

write_file(filename, initial_data)

# Display the original contents

display_file_contents(filename)
# Append new data to the file

new_data = "David,28,Artist\n"

append_to_file(filename, new_data)

# Display the updated contents

display_file_contents(filename)

Documentation

Program Overview

This Python program demonstrates various file


handling operations, including reading from a file,
writing to a file, appending to a file, and
displaying the contents of a file. It utilizes four
key functions to perform these operations.

Functions Overview

1.Function: read_file(filename)
o Purpose: Reads the contents of a specified
file.
o Parameters:
 filename: The name of the file to read.
o Returns: A list of lines from the file or an
error message if the file is not found.

2.Function: write_file(filename, data)


o Purpose: Writes data to a specified file,
overwriting any existing content.
o Parameters:
 filename: The name of the file to write
to.
 data: The string data to write to the
file.

3.Function: append_to_file(filename, data)


o Purpose: Appends data to a specified file
without overwriting existing content.
o Parameters:
 filename: The name of the file to append
to.
 data: The string data to append to the
file.

4.Function: display_file_contents(filename)
o Purpose: Displays the contents of a specified
file.
o Parameters:
 filename: The name of the file to
display.
o Returns: None. Prints the contents of the
file to the console.

Output

Test.txt
Program 13: Write a Program to read data from data
file in append mode and use writeLines function
utility in python.

Algorithm

Algorithm for File Handling with writelines()

1.Function read_file(filename):
o Input: filename (string) - the name of the
file to read.
o Process:
 Try to open the file in read mode.
 Read all lines from the file and store
them in a list.
 Return the list of lines.
 If the file is not found, return an
error message.

2.Function append_lines_to_file(filename, lines):


o Input:
 filename (string) - the name of the file
to append to.
 lines (list of strings) - a list of
strings to append to the file.
o Process:
 Open the file in append mode.
 Use file.writelines(lines) to write the
list of strings to the file.

3.Function display_file_contents(filename):
o Input: filename (string) - the name of the
file to display.
o Process:
 Call read_file() to get the contents of
the file.
 If the contents are valid (not an error
message), print each line.

4.Main Program:
o Define the filename (data_append.txt).
o Read and display the original contents of the
file.
o Define new lines to append to the file.
o Call append_lines_to_file() to append the new
lines.
o Read and display the updated contents of the
file.

Program

# Program to demonstrate reading and appending data


to a file using writelines

# Function to read data from the file

def read_file(filename):

try:

with open(filename, 'r') as file:

data = file.readlines()

return data

except FileNotFoundError:

return "File not found."

# Function to append multiple lines to the file using


writelines

def append_lines_to_file(filename, lines):

with open(filename, 'a') as file:

file.writelines(lines)

# Function to display contents of the file

def display_file_contents(filename):
contents = read_file(filename)

if isinstance(contents, list):

print("File Contents:")

for line in contents:

print(line.strip())

else:

print(contents)

# Main program

filename = 'data_append.txt'

# Display the original contents

print("Original Contents:")

display_file_contents(filename)

# New data to append

new_lines = [

"Charlie,22,Developer\n",

"David,28,Artist\n",

"Eva,26,Scientist\n"

# Append new lines to the file


append_lines_to_file(filename, new_lines)

# Display the updated contents

print("\nUpdated Contents After Appending:")

display_file_contents(filename)

Documentation

Program Overview

This Python program demonstrates how to read data


from a file, append multiple lines to the file using
the writelines() function, and display the updated
file contents.

Functions Overview

1.Function: read_file(filename)
o Purpose: Reads the contents of a specified
file.
o Parameters:
 filename: The name of the file to read.
o Returns: A list of lines from the file or an
error message if the file is not found.

2.Function: append_lines_to_file(filename, lines)


o Purpose: Appends multiple lines to a
specified file using the writelines()
function.
o Parameters:
 filename: The name of the file to append
to.
 lines: A list of strings (each string
represents a line) to append to the
file.

3.Function: display_file_contents(filename)
o Purpose: Displays the contents of a specified
file.
o Parameters:
 filename: The name of the file to
display.
o Returns: None. Prints the contents of the
file to the console.

Data_append.txt

Output
Program 14: Write a Program to read data from data
file in read mode and count the particular word
occurrences in given string, number of times in
python.

Algorithm

Algorithm for Counting Word Occurrences

1.Function read_file(filename):
o Input: filename (string) - the name of the
file to read.
o Process:
 Try to open the file in read mode.
 Read the entire contents of the file and
return it as a single string.
 If the file is not found, return an
error message.

2.Function count_word_occurrences(text, word):


o Input:
 text (string) - the text in which to
count the occurrences.
 word (string) - the word to count.
o Process:
 Split the text into words.
 Count the number of times word appears
in the list of words.
o Returns: The count of occurrences of the
specified word.

3.Main Program:
o Define the filename (data.txt).
o Read the contents of the file using
read_file().
o Ask the user to input a word to count.
o Call count_word_occurrences() to get the
count.
o Print the count.

Program
# Program to read data from a file and count
occurrences of a particular word

# Function to read data from the file

def read_file(filename):

try:

with open(filename, 'r') as file:

data = file.read()

return data

except FileNotFoundError:

return "File not found."

# Function to count occurrences of a word in the


given text

def count_word_occurrences(text, word):

# Split the text into words

words = text.split()

# Count occurrences of the specified word

return words.count(word)

# Main program

filename = 'data.txt'

# Read the contents of the file


file_contents = read_file(filename)

if file_contents != "File not found.":

# Ask the user for the word to count

word_to_count = input("Enter the word to count


its occurrences: ")

count = count_word_occurrences(file_contents,
word_to_count)

print(f"The word '{word_to_count}' occurs {count}


times in the file.")

else:

print(file_contents)

Documentation

Program Overview

This Python program reads data from a specified text


file and counts the occurrences of a particular word
entered by the user.

Functions Overview

1.Function: read_file(filename)
o Purpose: Reads the contents of a specified
file.
o Parameters:
 filename: The name of the file to read.
o Returns: The entire content of the file as a
string or an error message if the file is not
found.

2.Function: count_word_occurrences(text, word)


o Purpose: Counts how many times a specified
word appears in a given text.
o Parameters:
 text: The text in which to search for
the word.
 word: The word to count.
o Returns: The number of occurrences of the
specified word in the text.

Data.txt

Output
Program 15: Write a Program to read data from data
file in read mode and append the words starting with
letter ‘T’ in a given file in python

Algorithm

Algorithm for Appending Words Starting with 'T'

1.Function read_file(filename):
o Input: filename (string) - the name of the
file to read.
o Process:
 Try to open the file in read mode.
 Read the entire contents of the file and
return it as a single string.
 If the file is not found, return an
error message.

2.Function find_words_starting_with_t(text):
o Input: text (string) - the text from which to
find words.
o Process:
 Split the text into words.
 Filter the list of words to include only
those that start with the letter 'T'
(case-insensitive).
o Returns: A list of words that start with 'T'.

3.Function append_to_file(filename, words):


o Input:
 filename (string) - the name of the file
to append to.
 words (list of strings) - the list of
words to append.
o Process:
 Open the file in append mode.
 Write each word from the list to the
file, each followed by a newline.

4.Main Program:
o Define the input filename (data.txt) and the
output filename (words_starting_with_t.txt).
o Read the contents of the input file using
read_file().
o Call find_words_starting_with_t() to get
words starting with 'T'.
o Call append_to_file() to write those words to
the output file.

Program

# Program to read data from a file and append words


starting with 'T' to another file

# Function to read data from the file

def read_file(filename):

try:

with open(filename, 'r') as file:

data = file.read()

return data

except FileNotFoundError:

return "File not found."

# Function to find words starting with 'T'

def find_words_starting_with_t(text):

# Split the text into words

words = text.split()

# Filter words that start with 'T' or 't'

t_words = [word for word in words if


word.lower().startswith('t')]

return t_words
# Function to append words to the file

def append_to_file(filename, words):

with open(filename, 'a') as file:

for word in words:

file.write(word + '\n')

# Main program

input_filename = 'data.txt'

output_filename = 'words_starting_with_t.txt'

# Read the contents of the input file

file_contents = read_file(input_filename)

if file_contents != "File not found.":

# Find words starting with 'T'

t_words =
find_words_starting_with_t(file_contents)

# Append the words to the output file

append_to_file(output_filename, t_words)

print(f"Words starting with 'T' have been


appended to '{output_filename}'.")
else:

print(file_contents)

Documentation

Program Overview

This Python program reads data from a specified text


file, identifies words that start with the letter
'T', and appends those words to another specified
text file.

Functions Overview

1.Function: read_file(filename)
o Purpose: Reads the contents of a specified
file.
o Parameters:
 filename: The name of the file to read.
o Returns: The entire content of the file as a
string or an error message if the file is not
found.

2.Function: find_words_starting_with_t(text)
o Purpose: Finds all words that start with the
letter 'T' in the given text.
o Parameters:
 text: The text in which to search for
words.
o Returns: A list of words that start with 'T'.

3.Function: append_to_file(filename, words)


o Purpose: Appends a list of words to a
specified file.
o Parameters:
 filename: The name of the file to append
to.
 words: A list of words to append to the
file.
o Returns: None. The function writes the words
to the file.

Data.txt
Output

Words_starting_with_t.txt
Program 17: Write a Python program to implement all
basic operations of a stack, such as adding element
(PUSH operation), removing element (POP operation)
and displaying the stack elements (Traversal
operation) using lists.

Algorithm

Algorithm for Stack Operations

1.Initialize Stack:
o Create an empty list to represent the stack.

2.Function push(stack, element):


o Input:
 stack (list): The stack to which the
element will be added.
 element: The element to add to the
stack.
o Process:
 Append the element to the end of the
list (stack).

3.Function pop(stack):
o Input:
 stack (list): The stack from which the
element will be removed.
o Process:
 Check if the stack is empty:
 If empty, return an error message.
 If not empty, remove the last
element from the stack using pop()
and return it.

4.Function display_stack(stack):
o Input: stack (list): The stack to display.
o Process:
 Print the elements of the stack. If the
stack is empty, print a message
indicating that it is empty.

5.Main Program:
o Initialize an empty stack.
o Provide options for the user to push, pop, or
display the stack.
o Use a loop to allow multiple operations until
the user decides to exit.

Program

# Program to implement basic stack operations using


lists

# Function to push an element onto the stack

def push(stack, element):

stack.append(element)

print(f"{element} has been pushed onto the


stack.")

# Function to pop an element from the stack

def pop(stack):

if not stack:

return "Stack is empty. Cannot pop."

return stack.pop()

# Function to display the stack

def display_stack(stack):

if not stack:

print("Stack is empty.")

else:

print("Stack elements:", stack)


# Main program

stack = []

while True:

print("\nOptions:")

print("1. Push")

print("2. Pop")

print("3. Display Stack")

print("4. Exit")

choice = input("Choose an option (1-4): ")

if choice == '1':

element = input("Enter the element to push:


")

push(stack, element)

elif choice == '2':

popped_element = pop(stack)

if popped_element != "Stack is empty. Cannot


pop.":

print(f"Popped element:
{popped_element}")

else:

print(popped_element)

elif choice == '3':


display_stack(stack)

elif choice == '4':

print("Exiting the program.")

break

else:

print("Invalid choice. Please try again.")

Documentation

Program Overview

This Python program implements a stack using a list


and provides basic operations such as push, pop, and
display. The user can interact with the program to
perform stack operations until they choose to exit.

Functions Overview

1.Function: push(stack, element)


o Purpose: Adds an element to the top of the
stack.
o Parameters:
 stack: The stack (list) to which the
element will be added.
 element: The element to be added.
o Returns: None. Prints a message indicating
the element has been added.

2.Function: pop(stack)
o Purpose: Removes and returns the top element
of the stack.
o Parameters:
 stack: The stack (list) from which the
element will be removed.
o Returns: The removed element or an error
message if the stack is empty.

3.Function: display_stack(stack)
o Purpose: Displays the current elements in the
stack.
o Parameters:
 stack: The stack (list) to display.
o Returns: None. Prints the elements of the
stack or a message if it is empty.

Output
Program 18: Write a program to display unique vowels
present in the given word using Stack.

Algorithm

Algorithm for Displaying Unique Vowels Using a Stack

1.Initialize Stack:
o Create an empty list to represent the stack
for storing unique vowels.

2.Function is_vowel(char):
o Input: char (string) - a character to check.
o Process:
 Check if the character is one of the
vowels (a, e, i, o, u) in a case-
insensitive manner.
o Returns: True if the character is a vowel,
False otherwise.

3.Function push(stack, element):


o Input:
 stack (list): The stack to which the
vowel will be added.
 element: The vowel to add to the stack.
o Process:
 If the element is not already in the
stack, append the element to the stack.

4.Function display_unique_vowels(word):
o Input: word (string) - the word from which to
extract unique vowels.
o Process:
 Iterate through each character in the
word.
 If the character is a vowel, call push()
to add it to the stack.
o Returns: The stack containing unique vowels.

5.Main Program:
o Prompt the user to enter a word.
o Call display_unique_vowels() to get the
unique vowels.
o Print the unique vowels stored in the stack.

Program

# Program to display unique vowels present in a given


word using Stack

# Function to check if a character is a vowel

def is_vowel(char):

return char.lower() in 'aeiou'

# Function to push an element onto the stack if it's


unique

def push(stack, element):

if element not in stack:

stack.append(element)

# Function to display unique vowels from the given


word

def display_unique_vowels(word):

stack = []

for char in word:

if is_vowel(char):

push(stack, char)

return stack

# Main program
word = input("Enter a word: ")

unique_vowels = display_unique_vowels(word)

if unique_vowels:

print("Unique vowels present in the word:",


unique_vowels)

else:

print("No vowels present in the word.")

Documentation

Program Overview

This Python program uses a stack to display unique


vowels present in a given word. It checks each
character in the word and stores unique vowels in the
stack, which are then displayed to the user.

Functions Overview

1.Function: is_vowel(char)
o Purpose: Checks if a given character is a
vowel.
o Parameters:
 char: A character to check.
o Returns: True if the character is a vowel;
False otherwise.

2.Function: push(stack, element)


o Purpose: Adds a vowel to the stack if it is
not already present.
o Parameters:
 stack: The stack (list) to which the
vowel will be added.
 element: The vowel to be added.
o Returns: None. The function modifies the
stack in place.

3.Function: display_unique_vowels(word)
o Purpose: Extracts unique vowels from the
given word.
o Parameters:
 word: The word from which to extract
unique vowels.
o Returns: The stack containing unique vowels.

Output

You might also like