# Program 1: To find the roots of a quadratic equation including real, equal, and
complex root
import math
def get_coefficient(name):
while True:
try:
return float(input(f"Enter the coefficient {name}: "))
except ValueError:
print("Invalid input. Please enter a valid number.")
def find_roots(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2 * a)
root2 = (-b - math.sqrt(discriminant)) / (2 * a)
return ("real", root1, root2)
elif discriminant == 0:
root = -b / (2 * a)
return ("equal", root, root)
else:
real_part = -b / (2 * a)
imaginary_part = math.sqrt(-discriminant) / (2 * a)
return ("complex", real_part, imaginary_part)
def main():
Choice=True
while Choice :
a = get_coefficient("a")
b = get_coefficient("b")
c = get_coefficient("c")
root_type, root1, root2 = find_roots(a, b, c)
if root_type == "real":
print(f"The roots of the equation are real and distinct: {root1} and {root2}")
elif root_type == "equal":
print(f"The equation has equal roots: {root1} and {root2}")
else:
print(f"The roots of the equation are complex: {root1} + {root2}i and
{root1} - {root2}i")
while True:
rerun = input("Would you like to solve another quadratic equation?
(yes/no): ").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
# Program 2: To perform prime number operations-----------------------------
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def generate_primes_till(n):
return [x for x in range(2, n + 1) if is_prime(x)]
def generate_first_n_primes(n):
primes = []
num = 2
while len(primes) < n:
if is_prime(num):
primes.append(num)
num += 1
return primes
def get_number(prompt):
while True:
try:
num = int(input(prompt))
if num <= 0:
raise ValueError
return num
except ValueError:
print("Invalid input. Please enter a positive integer.")
def main():
Choice=True
while Choice:
num = get_number("Enter a number: ")
print(f"{num} is {'a prime number' if is_prime(num) else 'not a prime
number'}")
primes_till = generate_primes_till(num)
print(f"Prime numbers till {num}: {primes_till}")
first_n_primes = generate_first_n_primes(num)
print(f"First {num} prime numbers: {first_n_primes}")
while True:
rerun = input("Would you like to try for some other number ?(yes/no):
").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
# Program3: Print a pyramid and a reverse one of the same
height------------------------------------------
def print_pyramid(rows):
for i in range(rows):
print(' ' * (rows - i - 1) + '*' * (2 * i + 1))
def print_reverse_pyramid(rows):
for i in range(rows, 0, -1):
print(' ' * (rows - i) + '*' * (2 * i - 1))
def get_number_of_rows():
while True:
try:
rows = int(input("Enter the number of rows for the pyramid: "))
if rows <= 0:
raise ValueError("Number of rows must be a positive integer.")
return rows
except ValueError as e:
print(f"Invalid input: {e}. Please try again.")
def main():
Choice=True
while Choice:
try:
rows = get_number_of_rows()
print("\nPyramid:")
print_pyramid(rows)
print("\nReverse Pyramid:")
print_reverse_pyramid(rows)
except Exception as e:
print(f"An error occurred: {e}")
while True:
rerun = input("Would you like to try for a pyramid of different height ?
(yes/no): ").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
# Program 4: Program on strings--------------------------------------
def check_character_type(char):
if char.isalpha():
if char.isupper():
print(f"'{char}' is an uppercase letter.")
else:
print(f"'{char}' is a lowercase letter.")
elif char.isdigit():
digit_names = ['ZERO', 'ONE', 'TWO', 'THREE', 'FOUR', 'FIVE', 'SIX', 'SEVEN',
'EIGHT', 'NINE']
print(f"'{char}' is a numeric digit. It is '{digit_names[int(char)]}'.")
else:
print(f"'{char}' is a special character.")
def main():
Choice=True
while Choice:
char = input("Enter a single character: ")
if len(char) != 1:
print("Please enter exactly one character.")
else:
check_character_type(char)
while True:
rerun = input("Do you want to check another character? (yes/no):
").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
#Program 5:Operations on Strings-----------------------------------------------
def find_frequency(string, char):
return string.count(char)
def replace_character(string, old_char, new_char):
return string.replace(old_char, new_char)
def remove_first_occurrence(string, char):
return string.replace(char, '', 1)
def remove_all_occurrences(string, char):
return string.replace(char, '')
def get_user_input(prompt):
while True:
try:
user_input = input(prompt)
if not user_input:
raise ValueError("Input cannot be empty.")
return user_input
except ValueError as e:
print(f"Invalid input: {e}. Please try again.")
def main():
Choice=True
while Choice:
try:
string = get_user_input("Enter a string: ")
char = get_user_input("Enter a character to perform operations: ")
frequency = find_frequency(string, char)
print(f"Frequency of '{char}' in the string: {frequency}")
new_char = get_user_input("Enter a character to replace with: ")
replaced_string = replace_character(string, char, new_char)
print(f"String after replacing '{char}' with '{new_char}': {replaced_string}")
first_removed_string = remove_first_occurrence(string, char)
print(f"String after removing the first occurrence of '{char}':
{first_removed_string}")
all_removed_string = remove_all_occurrences(string, char)
print(f"String after removing all occurrences of '{char}':
{all_removed_string}")
except Exception as e:
print(f"An error occurred: {e}")
while True:
rerun = input("Do you want to perform operations on another string?
(yes/no): ").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
#Program 6: To swap first n characters of two
strings--------------------------------------------------------------------
def swap_first_n_characters(string1, string2, n):
if n > len(string1) or n > len(string2):
raise ValueError("The value of n cannot be greater than the length of either
string.")
new_string1 = string2[:n] + string1[n:]
new_string2 = string1[:n] + string2[n:]
return new_string1, new_string2
def get_user_input(prompt):
while True:
try:
user_input = input(prompt)
if not user_input:
raise ValueError("Input cannot be empty.")
return user_input
except ValueError as e:
print(f"Invalid input: {e}. Please try again.")
def get_positive_integer(prompt):
while True:
try:
user_input = int(input(prompt))
if user_input <= 0:
raise ValueError("Input must be a positive integer.")
return user_input
except ValueError as e:
print(f"Invalid input: {e}. Please try again.")
def main():
Choice=True
while Choice:
try:
string1 = get_user_input("Enter the first string: ")
string2 = get_user_input("Enter the second string: ")
n = get_positive_integer("Enter the number of characters to swap: ")
new_string1, new_string2 = swap_first_n_characters(string1, string2, n)
print(f"After swapping the first {n} characters:")
print(f"First string: {new_string1}")
print(f"Second string: {new_string2}")
except Exception as e:
print(f"An error occurred: {e}")
while True:
rerun = input("Do you want to perform operations on another string?
(yes/no): ").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
#Program 7:Returning the indices of characters in a list—-------------
def find_substring_indices(main_string, sub_string):
indices = []
for i in range(len(main_string) - len(sub_string) + 1):
if main_string[i:i+len(sub_string)] == sub_string:
indices.extend(range(i, i+len(sub_string)))
return indices if indices else -1
def main():
Choice=True
while Choice:
try:
main_string = input("Enter the main string: ")
sub_string = input("Enter the substring to find: ")
result = find_substring_indices(main_string, sub_string)
if result == -1:
print(f"'{sub_string}' not found in the main string.")
else:
print(f"Indices of occurrences of '{sub_string}' in the main string:
{result}")
except Exception as e:
print(f"An error occurred: {e}")
while True:
rerun = input("Do you want to check another string? (yes/no):
").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
#Program 8:To create a list of the cubes of only the even integers appearing in the
input list
#a. 'for' loop
def cubes_of_even_integers_for_loop(input_list):
even_cubes = []
for item in input_list:
if isinstance(item, int) and item % 2 == 0:
even_cubes.append(item ** 3)
return even_cubes
def main():
Choice=True
while Choice:
input_list = [int(x) for x in input("Enter a list of numbers separated by space:
").split()]
result_for_loop = cubes_of_even_integers_for_loop(input_list)
print("Cubes of even integers using for loop:", result_for_loop)
while True:
rerun = input("Do you want to process another list? (yes/no):
").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
#b. list comprehension
def cubes_of_even_integers_list_comprehension(input_list):
return [item ** 3 for item in input_list if isinstance(item, int) and item % 2 == 0]
def main():
Choice=True
while Choice:
input_list = [int(x) for x in input("Enter a list of numbers separated by space:
").split()]
result_list_comprehension =
cubes_of_even_integers_list_comprehension(input_list)
print("Cubes of even integers using list comprehension:",
result_list_comprehension)
while True:
rerun = input("Do you want to process another list? (yes/no):
").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
#Program 9: To read a file and print total no. of characters,words and lines
file_name = "input.txt"
def process_file(file_name):
try:
with open(file_name, 'r') as file:
lines = file.readlines()
total_characters = sum(len(line) for line in lines)
total_words = sum(len(line.split()) for line in lines)
total_lines = len(lines)
print(f"Total characters: {total_characters}")
print(f"Total words: {total_words}")
print(f"Total lines: {total_lines}")
# Calculate the frequency of each character in the file
char_frequency = {}
for line in lines:
for char in line:
char_frequency[char] = char_frequency.get(char, 0) + 1
print("\nCharacter frequencies:")
for char, freq in char_frequency.items():
print(f"'{char}': {freq}")
# Print the words in reverse order
print("\nWords in reverse order:")
for line in lines:
words = line.split()
reversed_words = ' '.join(reversed(words))
print(reversed_words)
# Copy even lines in 'File1.txt' and odd lines in 'File2.txt'
with open('File1.txt', 'w') as file1, open('File2.txt', 'w') as file2:
for index, line in enumerate(lines, start=1):
if index % 2 == 0:
file1.write(line)
else:
file2.write(line)
print("\nEven lines written to 'File1.txt' and odd lines written to 'File2.txt'.")
except FileNotFoundError:
print(f"The file '{file_name}' does not exist.")
def main():
while True:
process_file(file_name)
rerun = input("Do you want to process the file again? (yes/no):
").strip().lower()
if rerun != 'yes':
print("Thank you for using the file processor program. Goodbye!")
break
if __name__ == "__main__":
main()
Output:
#Program 10:WAP to define a class Point with coordinates x and y as
attributes----------
import math
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def distance(self, other):
return math.sqrt((self.x - other.x) ** 2 + (self.y - other.y) ** 2)
def main():
Choice=True
while Choice:
try:
x1 = float(input("Enter x-coordinate of the first point: "))
y1 = float(input("Enter y-coordinate of the first point: "))
x2 = float(input("Enter x-coordinate of the second point: "))
y2 = float(input("Enter y-coordinate of the second point: "))
point1 = Point(x1, y1)
point2 = Point(x2, y2)
print(point1)
print(point2)
print(f"Distance between {point1} and {point2} is
{point1.distance(point2)}")
except Exception as e:
print(f"An error occurred: {e}")
while True:
rerun = input("Do you want to create another pair of points? (yes/no):
").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
#Program 11:Write a function that prints a dictionary of cubes of corresponding
numbers------------------
def create_and_print_cubed_dict():
cubed_dict = {i: i**3 for i in range(1, 6)}
print(cubed_dict)
def main():
Choice=True
while Choice:
try:
create_and_print_cubed_dict()
except Exception as e:
print(f"An error occurred: {e}")
while True:
rerun = input("Do you want to create another dictionary? (yes/no):
").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
#Program 12:Operation on Tuple----------------------------
def print_half_tuple(t):
midpoint = len(t) // 2
print("First half:", t[:midpoint])
print("Second half:", t[midpoint:])
def even_values_tuple(t):
return tuple(x for x in t if x % 2 == 0)
def concatenate_tuples(t1, t2):
return t1 + t2
def find_max_min(t):
return max(t), min(t)
def main():
t1 = (1, 2, 5, 7, 9, 2, 4, 6, 8, 10)
t2 = (11, 13, 15)
Choice=True
while Choice:
try:
print("Original tuple:", t1)
# Part (a)
print_half_tuple(t1)
# Part (b)
even_tuple = even_values_tuple(t1)
print("Tuple with even values:", even_tuple)
# Part (c)
concatenated_tuple = concatenate_tuples(t1, t2)
print("Concatenated tuple:", concatenated_tuple)
# Part (d)
max_value, min_value = find_max_min(t1)
print(f"Maximum value in the tuple: {max_value}")
print(f"Minimum value in the tuple: {min_value}")
except Exception as e:
print(f"An error occurred: {e}")
while True:
rerun = input("Do you want to perform the operations again? (yes/no):
").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output:
#Program 13:Raise and handle exceptions------------------
def is_valid_name(name):
return all(char.isalpha() or char.isspace() for char in name)
def main():
Choice=True
while Choice:
try:
name = input("Enter your name: ")
if not is_valid_name(name):
raise ValueError("The name should contain only alphabetic characters
and spaces.")
print(f"Hello, {name}!")
except ValueError as e:
print(f"Invalid input: {e}")
while True:
rerun = input("Do you want to enter another name? (yes/no):
").strip().lower()
if rerun=='yes':
break
elif rerun =='no':
print("The program has been successfully executed\nThank you")
Choice=False
break
else:
print("Enter your choice only out of (yes/no) only")
if __name__ == "__main__":
main()
Output: