Class Xi Ics Practical
Class Xi Ics Practical
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
try:
print(f"Addition: {addition}")
print(f"Subtraction: {subtraction}")
print(f"Multiplication: {multiplication}")
print(f"Division: {division}")
print(f"Modulus: {modulus}")
except ValueError:
Documentation
Program Overview
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
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
try:
if num < 1:
else:
sum_of_divisors = 0
if num % i == 0:
sum_of_divisors += i
if sum_of_divisors == num:
else:
except ValueError:
Documentation
Program Overview
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
try:
if num < 0:
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
sum_of_powers += int(digit) **
num_of_digits
if sum_of_powers == num:
else:
except ValueError:
Documentation
Program Overview
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.
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
try:
if num < 0:
else:
factorial = 1
# Calculate factorial
except ValueError:
Documentation
Program Overview
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
try:
if terms <= 0:
elif terms == 1:
print("Fibonacci Series: 0")
elif terms == 2:
else:
a, b = 0, 1
next_term = a + b
a, b = b, next_term
print(next_term)
except ValueError:
Documentation
Program Overview
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.
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
normalized_string = input_string.lower()
# Initialize pointers
left = 0
right = len(normalized_string) - 1
# Check for palindrome
is_palindrome = True
if normalized_string[left] !=
normalized_string[right]:
is_palindrome = False
break
left += 1
right -= 1
if is_palindrome:
print(f'"{input_string}" is a palindrome.')
else:
Documentation
Program Overview
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.
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
number_list.append(10)
number_list.sort()
number_list.reverse()
count_of_10 = number_list.count(10)
length_of_list = len(number_list)
Documentation
Program Overview
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.
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
try:
if rows <= 0:
else:
except ValueError:
Documentation
Program Overview
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.
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
Program
# fact.py
def fact(n):
if n < 0:
elif n == 0 or n == 1:
return 1
else:
result = 1
result *= i
return result
# main.py
try:
factorial_result = fact.fact(num)
except ValueError:
Documentation
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.
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
Program
if value == target:
return index
return -1
if arr[mid] == target:
return mid
left = mid + 1
else:
right = mid - 1
return -1
def find_lowest(arr):
return min(arr)
def selection_sort(arr):
for i in range(len(arr)):
min_index = i
min_index = j
# Main program
try:
lowest_number = find_lowest(numbers)
# Linear Search
if linear_result != -1:
else:
binary_result = binary_search(numbers,
target_binary)
if binary_result != -1:
else:
print(f"Binary Search: {target_binary} not
found.")
except ValueError:
Documentation
Program Overview
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.
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
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.
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
def read_file(filename):
try:
data = file.readlines()
return data
except FileNotFoundError:
file.write(data)
file.write(data)
def display_file_contents(filename):
contents = read_file(filename)
if isinstance(contents, list):
print("File Contents:")
print(line.strip())
else:
print(contents)
# Main program
filename = 'data.txt'
initial_data = "Alice,25,Engineer\nBob,30,Designer\
nCharlie,22,Developer\n"
write_file(filename, initial_data)
display_file_contents(filename)
# Append new data to the file
new_data = "David,28,Artist\n"
append_to_file(filename, new_data)
display_file_contents(filename)
Documentation
Program Overview
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.
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
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.
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
def read_file(filename):
try:
data = file.readlines()
return data
except FileNotFoundError:
file.writelines(lines)
def display_file_contents(filename):
contents = read_file(filename)
if isinstance(contents, list):
print("File Contents:")
print(line.strip())
else:
print(contents)
# Main program
filename = 'data_append.txt'
print("Original Contents:")
display_file_contents(filename)
new_lines = [
"Charlie,22,Developer\n",
"David,28,Artist\n",
"Eva,26,Scientist\n"
display_file_contents(filename)
Documentation
Program Overview
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.
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
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.
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
def read_file(filename):
try:
data = file.read()
return data
except FileNotFoundError:
words = text.split()
return words.count(word)
# Main program
filename = 'data.txt'
count = count_word_occurrences(file_contents,
word_to_count)
else:
print(file_contents)
Documentation
Program Overview
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.
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
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'.
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
def read_file(filename):
try:
data = file.read()
return data
except FileNotFoundError:
def find_words_starting_with_t(text):
words = text.split()
return t_words
# Function to append words to the file
file.write(word + '\n')
# Main program
input_filename = 'data.txt'
output_filename = 'words_starting_with_t.txt'
file_contents = read_file(input_filename)
t_words =
find_words_starting_with_t(file_contents)
append_to_file(output_filename, t_words)
print(file_contents)
Documentation
Program Overview
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'.
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
1.Initialize Stack:
o Create an empty list to represent the 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
stack.append(element)
def pop(stack):
if not stack:
return stack.pop()
def display_stack(stack):
if not stack:
print("Stack is empty.")
else:
stack = []
while True:
print("\nOptions:")
print("1. Push")
print("2. Pop")
print("4. Exit")
if choice == '1':
push(stack, element)
popped_element = pop(stack)
print(f"Popped element:
{popped_element}")
else:
print(popped_element)
break
else:
Documentation
Program Overview
Functions Overview
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
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.
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
def is_vowel(char):
stack.append(element)
def display_unique_vowels(word):
stack = []
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:
else:
Documentation
Program Overview
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.
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