Python practical 24HCS4181 (3)
Python practical 24HCS4181 (3)
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 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:
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: ")
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:
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:
def main():
Choice=True
while Choice:
try:
string = get_user_input("Enter a string: ")
char = get_user_input("Enter a character to perform operations: ")
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:
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: ")
def main():
Choice=True
while Choice:
try:
main_string = input("Enter the main string: ")
sub_string = input("Enter the substring to find: ")
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:
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}")
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})"
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 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:
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: