Python Assignment Solutions - Mid Semester Exam
Python Assignment Solutions - Mid Semester Exam
python
# Mutable Examples
my_list = [1, 2, 3]
print("Original list:", my_list)
my_list[0] = 10 # Modifying existing list
print("Modified list:", my_list)
# Immutable Examples
my_string = "Hello"
# my_string[0] = 'h' # This would cause an error
new_string = my_string.replace('H', 'h') # Creates new string
print("Original string:", my_string)
print("New string:", new_string)
my_tuple = (1, 2, 3)
# my_tuple[0] = 10 # This would cause an error
print("Tuple remains:", my_tuple)
python
def comprehensive_calculator():
print("=== Comprehensive Operations Calculator ===")
# Arithmetic Operations
print("\n1. ARITHMETIC OPERATIONS:")
print(f"Addition: {num1} + {num2} = {num1 + num2}")
print(f"Subtraction: {num1} - {num2} = {num1 - num2}")
print(f"Multiplication: {num1} * {num2} = {num1 * num2}")
if num2 != 0:
print(f"Division: {num1} / {num2} = {num1 / num2}")
print(f"Floor Division: {num1} // {num2} = {num1 // num2}")
print(f"Modulus: {num1} % {num2} = {num1 % num2}")
else:
print("Division by zero not allowed")
print(f"Exponentiation: {num1} ** {num2} = {num1 ** num2}")
# Relational Operations
print("\n2. RELATIONAL OPERATIONS:")
print(f"{num1} == {num2}: {num1 == num2}")
print(f"{num1} != {num2}: {num1 != num2}")
print(f"{num1} > {num2}: {num1 > num2}")
print(f"{num1} < {num2}: {num1 < num2}")
print(f"{num1} >= {num2}: {num1 >= num2}")
print(f"{num1} <= {num2}: {num1 <= num2}")
# Assignment Operations
print("\n5. ASSIGNMENT OPERATIONS:")
result = num1
print(f"result = {num1}: {result}")
result += num2
print(f"result += {num2}: {result}")
result -= num2
print(f"result -= {num2}: {result}")
result *= num2
print(f"result *= {num2}: {result}")
if num2 != 0:
result /= num2
print(f"result /= {num2}: {result}")
python
class LibraryManagement:
def __init__(self):
self.books = {
'Python Programming': 5,
'Data Structures': 3,
'Web Development': 4,
'Machine Learning': 2
}
self.borrowed_books = []
def display_menu(self):
print("\n=== LIBRARY MANAGEMENT SYSTEM ===")
print("1. Add New Book")
print("2. Borrow a Book")
print("3. Return a Book")
print("4. Display All Available Books")
print("5. Exit")
def add_book(self):
book_name = input("Enter book name: ").strip()
try:
quantity = int(input("Enter quantity: "))
if book_name in self.books:
self.books[book_name] += quantity
else:
self.books[book_name] = quantity
print(f"✅ Successfully added {quantity} copies of '{book_name}'")
except ValueError:
print("❌ Please enter a valid quantity")
def borrow_book(self):
book_name = input("Enter book name to borrow: ").strip()
if book_name in self.books and self.books[book_name] > 0:
self.books[book_name] -= 1
self.borrowed_books.append(book_name)
print(f"✅ Successfully borrowed '{book_name}'")
else:
print("❌ Book not available or out of stock")
def return_book(self):
book_name = input("Enter book name to return: ").strip()
if book_name in self.borrowed_books:
self.borrowed_books.remove(book_name)
if book_name in self.books:
self.books[book_name] += 1
else:
self.books[book_name] = 1
print(f"✅ Successfully returned '{book_name}'")
else:
print("❌ This book was not borrowed from our library")
def display_books(self):
print("\n📚 AVAILABLE BOOKS:")
print("-" * 40)
if self.books:
for book, quantity in self.books.items():
status = "Available" if quantity > 0 else "Out of Stock"
print(f"{book}: {quantity} copies ({status})")
else:
print("No books available")
def run(self):
while True:
self.display_menu()
try:
choice = int(input("Enter your choice (1-5): "))
if choice == 1:
self.add_book()
elif choice == 2:
self.borrow_book()
elif choice == 3:
self.return_book()
elif choice == 4:
self.display_books()
elif choice == 5:
print("Thank you for using Library Management System!")
break
else:
print("❌ Invalid choice! Please select 1-5")
except ValueError:
print("❌ Please enter a valid number")
python
def set_operations():
print("=== SET OPERATIONS ===")
print(f"\nSet 1: {set1}")
print(f"Set 2: {set2}")
# Check relationships
print("\n=== SET RELATIONSHIPS ===")
if set1.issubset(set2):
print("Set 1 is a SUBSET of Set 2")
elif set1.issuperset(set2):
print("Set 1 is a SUPERSET of Set 2")
elif set1.isdisjoint(set2):
print("Set 1 and Set 2 are DISJOINT (no common elements)")
else:
print("Sets have some common elements but neither is subset/superset")
python
def analyze_list(numbers):
"""
Find maximum, second maximum, smallest, and N-largest values from a list
"""
if not numbers:
return "Empty list provided"
# Results dictionary
results = {}
# Maximum value
results['maximum'] = max(numbers)
# Second maximum
if len(unique_nums) >= 2:
results['second_maximum'] = unique_nums[1]
else:
results['second_maximum'] = "Only one unique value exists"
# Smallest value
results['smallest'] = min(numbers)
return results
# Main program
def main():
print("=== LIST ANALYSIS PROGRAM ===")
except ValueError:
print("Please enter valid integers only")
Python is considered beginner-friendly due to its design philosophy that emphasizes code readability and
simplicity. The language uses English-like syntax that makes it intuitive for new programmers to
understand and write code.
5. Cross-Platform Compatibility
Write once, run anywhere
python
# Modifying elements
my_list[0] = 10
print("After modification:", my_list)
# Adding elements
my_list.append(6)
print("After adding element:", my_list)
# Removing elements
my_list.remove(2)
print("After removing element:", my_list)
# Extending list
my_list.extend([7, 8])
print("After extending:", my_list)
python
# Tuples cannot be changed after creation
my_tuple = (1, 2, 3, 4, 5)
print("Original tuple:", my_tuple)
python
def demonstrate_operators():
print("=== PYTHON OPERATORS DEMONSTRATION ===")
# 1. ARITHMETIC OPERATORS
print("\n1. ARITHMETIC OPERATORS:")
print(f" Addition: {num1} + {num2} = {num1 + num2}")
print(f" Subtraction: {num1} - {num2} = {num1 - num2}")
print(f" Multiplication: {num1} * {num2} = {num1 * num2}")
if num2 != 0:
print(f" Division: {num1} / {num2} = {num1 / num2}")
print(f" Floor Division: {num1} // {num2} = {num1 // num2}")
print(f" Modulus: {num1} % {num2} = {num1 % num2}")
else:
print(" Division operations skipped (division by zero)")
# 2. COMPARISON OPERATORS
print("\n2. COMPARISON OPERATORS:")
print(f" Equal to: {num1} == {num2} → {num1 == num2}")
print(f" Not equal to: {num1} != {num2} → {num1 != num2}")
print(f" Greater than: {num1} > {num2} → {num1 > num2}")
print(f" Less than: {num1} < {num2} → {num1 < num2}")
print(f" Greater than or equal: {num1} >= {num2} → {num1 >= num2}")
print(f" Less than or equal: {num1} <= {num2} → {num1 <= num2}")
# 3. LOGICAL OPERATORS
print("\n3. LOGICAL OPERATORS:")
bool1 = bool(num1) # Convert to boolean
bool2 = bool(num2)
print(f" bool({num1}) = {bool1}")
print(f" bool({num2}) = {bool2}")
print(f" AND: {bool1} and {bool2} = {bool1 and bool2}")
print(f" OR: {bool1} or {bool2} = {bool1 or bool2}")
print(f" NOT: not {bool1} = {not bool1}")
print(f" NOT: not {bool2} = {not bool2}")
# 4. ASSIGNMENT OPERATORS
print("\n4. ASSIGNMENT OPERATORS:")
result = num1
print(f" result = {num1} → result = {result}")
result += num2
print(f" result += {num2} → result = {result}")
result -= num2
print(f" result -= {num2} → result = {result}")
result *= num2
print(f" result *= {num2} → result = {result}")
if num2 != 0:
result //= num2
print(f" result //= {num2} → result = {result}")
result **= 2
print(f" result **= 2 → result = {result}")
except ValueError:
print("❌ Please enter valid integers only!")
except Exception as e:
print(f"❌ An error occurred: {e}")
python
class BankingSystem:
def __init__(self):
self.accounts = {}
self.current_account = None
def display_menu(self):
print("\n" + "="*40)
print(" BANKING SOFTWARE SYSTEM")
print("="*40)
print("1. Create Account")
print("2. Login to Account")
print("3. Deposit Funds")
print("4. Withdraw Cash")
print("5. View Balance")
print("6. Account Statement")
print("7. Logout")
print("8. Exit System")
print("="*40)
def create_account(self):
print("\n--- CREATE NEW ACCOUNT ---")
account_no = input("Enter account number: ")
if account_no in self.accounts:
print("❌ Account already exists!")
return
self.accounts[account_no] = {
'name': name,
'balance': initial_deposit,
'transactions': [f"Account created with initial deposit: ₹{initial_deposit}"]
}
def login(self):
print("\n--- LOGIN TO ACCOUNT ---")
account_no = input("Enter account number: ")
self.current_account = account_no
print(f"✅ Login successful! Welcome, {self.accounts[account_no]['name']}")
return True
def deposit(self):
if not self.current_account:
print("❌ Please login first!")
return
if amount <= 0:
print("❌ Please enter a valid amount!")
return
self.accounts[self.current_account]['balance'] += amount
self.accounts[self.current_account]['transactions'].append(
f"Deposited: ₹{amount}"
)
except ValueError:
print("❌ Please enter a valid numeric amount!")
def withdraw(self):
if not self.current_account:
print("❌ Please login first!")
return
if amount <= 0:
print("❌ Please enter a valid amount!")
return
current_balance = self.accounts[self.current_account]['balance']
self.accounts[self.current_account]['balance'] -= amount
self.accounts[self.current_account]['transactions'].append(
f"Withdrawn: ₹{amount}"
)
except ValueError:
print("❌ Please enter a valid numeric amount!")
def view_balance(self):
if not self.current_account:
print("❌ Please login first!")
return
account = self.accounts[self.current_account]
print(f"\n--- ACCOUNT BALANCE ---")
print(f"Account Number: {self.current_account}")
print(f"Account Holder: {account['name']}")
print(f"Current Balance: ₹{account['balance']}")
def account_statement(self):
if not self.current_account:
print("❌ Please login first!")
return
account = self.accounts[self.current_account]
print(f"\n--- ACCOUNT STATEMENT ---")
print(f"Account Number: {self.current_account}")
print(f"Account Holder: {account['name']}")
print(f"Current Balance: ₹{account['balance']}")
print("\nTransaction History:")
print("-" * 30)
def logout(self):
if self.current_account:
print(f"✅ Logged out successfully from account {self.current_account}")
self.current_account = None
else:
print("❌ No user currently logged in!")
def run(self):
print("Welcome to Banking Software System!")
while True:
self.display_menu()
try:
choice = int(input("Enter your choice (1-8): "))
if choice == 1:
self.create_account()
elif choice == 2:
self.login()
elif choice == 3:
self.deposit()
elif choice == 4:
self.withdraw()
elif choice == 5:
self.view_balance()
elif choice == 6:
self.account_statement()
elif choice == 7:
self.logout()
elif choice == 8:
print("Thank you for using Banking Software System!")
break
else:
print("❌ Invalid choice! Please select 1-8")
except ValueError:
print("❌ Please enter a valid number!")
except KeyboardInterrupt:
print("\n\nSystem interrupted. Goodbye!")
break
python
def set_theory_operations():
print("=== SET THEORY OPERATIONS ===")
print(f"\nSet A: {sorted(set_a)}")
print(f"Set B: {sorted(set_b)}")
print("="*50)
# Relationship Tests
print("\n🔸 SET RELATIONSHIPS:")
# Subset test
if set_a.issubset(set_b):
print("✅ Set A is a SUBSET of Set B (A ⊆ B)")
elif set_b.issubset(set_a):
print("✅ Set B is a SUBSET of Set A (B ⊆ A)")
else:
print("❌ Neither set is a subset of the other")
# Superset test
if set_a.issuperset(set_b):
print("✅ Set A is a SUPERSET of Set B (A ⊇ B)")
elif set_b.issuperset(set_a):
print("✅ Set B is a SUPERSET of Set A (B ⊇ A)")
else:
print("❌ Neither set is a superset of the other")
# Disjoint test
if set_a.isdisjoint(set_b):
print("✅ Sets A and B are DISJOINT (A ∩ B = ∅)")
else:
print("❌ Sets A and B are NOT disjoint (they share common elements)")
# Additional Information
print(f"\n🔸 ADDITIONAL INFORMATION:")
print(f"Size of Set A: {len(set_a)}")
print(f"Size of Set B: {len(set_b)}")
print(f"Size of Union: {len(set_a.union(set_b))}")
print(f"Size of Intersection: {len(set_a.intersection(set_b))}")
python
def analyze_integer_list():
print("=== INTEGER LIST ANALYSIS ===")
try:
# Get input from user
print("Enter integers separated by spaces:")
numbers_input = input().split()
numbers = [int(x) for x in numbers_input]
if not numbers:
print("❌ Empty list provided!")
return
if len(unique_numbers) >= 2:
second_highest = unique_numbers[1]
print(f"🥈 Second Highest Element: {second_highest}")
else:
print("🥈 Second Highest Element: Only one unique value exists")
# Additional statistics
print(f"\n📊 ADDITIONAL STATISTICS:")
print(f"Total elements: {len(numbers)}")
print(f"Unique elements: {len(unique_numbers)}")
print(f"Sum of all elements: {sum(numbers)}")
print(f"Average: {sum(numbers)/len(numbers):.2f}")
except ValueError:
print("❌ Please enter valid integers only!")
except Exception as e:
print(f"❌ An error occurred: {e}")
Python prioritizes developer productivity and code readability over execution speed, making it
fundamentally different from statically-typed, compiled languages like Java and C++.
1. Syntax Simplicity
python
greet("World")
java
// Java - More verbose
public class HelloWorld {
public static void main(String[] args) {
greet("World");
}
python
java
3. Memory Management
python
cpp
4. Interpreted vs Compiled
python
# Python - Run directly
print("Hello World") # Execute immediately with python script.py
cpp
python
java
python
def demonstrate_mutability():
print("=== IMMUTABLE STRINGS vs MUTABLE LISTS ===")
# Adding elements
original_list.append(6)
print(f"After appending: {original_list}")
print(f"Same list ID: {id(original_list)}")
# Removing elements
original_list.remove(2)
print(f"After removing 2: {original_list}")
print(f"Same list ID: {id(original_list)}")
# Extending list
original_list.extend([7, 8])
print(f"After extending: {original_list}")
print(f"Same list ID: {id(original_list)}")
# PERFORMANCE COMPARISON
print("\n🔸 PERFORMANCE IMPLICATIONS:")
# Run demonstration
if __name__ == "__main__":
demonstrate_mutability()
python
def comprehensive_operator_evaluation():
print("="*60)
print(" COMPREHENSIVE PYTHON OPERATOR EVALUATION")
print("="*60)
try:
# Get user input
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# 1. ARITHMETIC OPERATORS
print("\n🔹 1. ARITHMETIC OPERATORS")
print("-" * 30)
print(f"{'Operation':<20} {'Expression':<15} {'Result'}")
print("-" * 30)
print(f"{'Addition':<20} {f'{num1} + {num2}':<15} {num1 + num2}")
print(f"{'Subtraction':<20} {f'{num1} - {num2}':<15} {num1 - num2}")
print(f"{'Multiplication':<20} {f'{num1} * {num2}':<15} {num1 * num2}")
if num2 != 0:
print(f"{'Division':<20} {f'{num1} / {num2}':<15} {num1 / num2:.4f}")
print(f"{'Floor Division':<20} {f'{num1} // {num2}':<15} {num1 // num2}")
print(f"{'Modulus':<20} {f'{num1} % {num2}':<15} {num1 % num2}")
else:
print(f"{'Division':<20} {'N/A (÷0)':<15} {'Undefined'}")
# 2. RELATIONAL/COMPARISON OPERATORS
print("\n🔹 2. RELATIONAL/COMPARISON OPERATORS")
print("-" * 40)
print(f"{'Operation':<25} {'Expression':<10} {'Result'}")
print("-" * 40)
print(f"{'Equal to':<25} {f'{num1} == {num2}':<10} {num1 == num2}")
print(f"{'Not equal to':<25} {f'{num1} != {num2}':<10} {num1 != num2}")
print(f"{'Greater than':<25} {f'{num1} > {num2}':<10} {num1 > num2}")
print(f"{'Less than':<25} {f'{num1} < {num2}':<10} {num1 < num2}")
print(f"{'Greater than or equal':<25} {f'{num1} >= {num2}':<10} {num1 >= num2}")
print(f"{'Less than or equal':<25} {f'{num1} <= {num2}':<10} {num1 <= num2}")
# 3. LOGICAL OPERATORS
print("\n🔹 3. LOGICAL OPERATORS")
print("-" * 40)
bool1, bool2 = bool(num1), bool(num2)
print(f"{'Boolean Values:':<25} num1={bool1}, num2={bool2}")
print(f"{'Logical AND':<25} {f'{bool1} and {bool2}':<10} {bool1 and bool2}")
print(f"{'Logical OR':<25} {f'{bool1} or {bool2}':<10} {bool1 or bool2}")
print(f"{'Logical NOT (num1)':<25} {f'not {bool1}':<10} {not bool1}")
print(f"{'Logical NOT (num2)':<25} {f'not {bool2}':<10} {not bool2}")
# 5. ASSIGNMENT OPERATORS
print("\n🔹 5. ASSIGNMENT OPERATORS")
print("-" * 40)
print("Demonstrating with a variable 'x' starting with num1:")
x = num1
print(f"{'Simple Assignment':<25} x = {num1:<10} → x = {x}")
x += num2
print(f"{'Addition Assignment':<25} x += {num2:<9} → x = {x}")
x -= num2
print(f"{'Subtraction Assignment':<25} x -= {num2:<9} → x = {x}")
x *= num2
print(f"{'Multiplication Assignment':<25} x *= {num2:<9} → x = {x}")
if num2 != 0:
x /= num2
print(f"{'Division Assignment':<25} x /= {num2:<9} → x = {x:.4f}")
x //= 2
print(f"{'Floor Division Assignment':<25} x //= 2{'':<8} → x = {x}")
x %= 3
print(f"{'Modulus Assignment':<25} x %= 3{'':<8} → x = {x}")
x **= 2
print(f"{'Exponent Assignment':<25} x **= 2{'':<8} → x = {x}")
# 7. IDENTITY OPERATORS
print("\n🔹 7. IDENTITY OPERATORS")
print("-" * 30)
a, b = num1, num1
c = num2
print(f"a = {a}, b = {b}, c = {c}")
print(f"a is b: {a is b}")
print(f"a is c: {a is c}")
print(f"a is not c: {a is not c}")
except ValueError:
print("❌ Error: Please enter valid numeric values!")
except Exception as e:
print(f"❌ An unexpected error occurred: {e}")
# 1. NUMERIC TYPES
print("🔸 1. NUMERIC TYPES")
print("-" * 30)
# Integer
integer_var = 42
print(f"Integer: {integer_var} (type: {type(integer_var).__name__})")
# Float
float_var = 3.14159
print(f"Float: {float_var} (type: {type(float_var).__name__})")
# Complex
complex_var = 3 + 4j
print(f"Complex: {complex_var} (type: {type(complex_var).__name__})")
# 2. SEQUENCE TYPES
print(f"\n🔸 2. SEQUENCE TYPES")
print("-" * 30)
# String
string_var = "Hello, Python!"
print(f"String: '{string_var}' (type: {type(string_var).__name__})")
# List
list_var = [1, 2, 3, "mixed", True]
print(f"List: {list_var} (type: {type(list_var).__name__})")
# Tuple
tuple_var = (10, 20, 30, "immutable")
print(f"Tuple: {tuple_var} (type: {type(tuple_var).__name__})")
# 3. MAPPING TYPE
print(f"\n🔸 3. MAPPING TYPE")
print("-" * 30)
# Dictionary
dict_var = {"name": "Alice", "age": 30, "city": "New York"}
print(f"Dictionary: {dict_var} (type: {type(dict_var).__name__})")
# 4. SET TYPES
print(f"\n🔸 4. SET TYPES")
print("-" * 30)
# Set
set_var = {1, 2, 3, 4, 5}
print(f"Set: {set_var} (type: {type(set_var).__name__})")
# Frozenset
frozenset_var = frozenset([1, 2, 3, 4])
print(f"Frozenset: {frozenset_var} (type: {type(frozenset_var).__name__})")
# 5. BOOLEAN TYPE
print(f"\n🔸 5. BOOLEAN TYPE")
print("-" * 30)
# Boolean
bool_var_true = True
bool_var_false = False
print(f"Boolean True: {bool_var_true} (type: {type(bool_var_true).__name__})")
print(f"Boolean False: {bool_var_false} (type: {type(bool_var_false).__name__})")
# 6. NONE TYPE
print(f"\n🔸 6. NONE TYPE")
print("-" * 30)
# NoneType
none_var = None
print(f"None: {none_var} (type: {type(none_var).__name__})")
# String operations
print(f"String length: {len(string_var)}")
print(f"String uppercase: {string_var.upper()}")
# List operations
list_var.append("new_item")
print(f"List after append: {list_var}")
# Dictionary operations
dict_var["occupation"] = "Engineer"
print(f"Dictionary after adding key: {dict_var}")
# Set operations
set_var.add(6)
print(f"Set after adding element: {set_var}")
# Type checking
print(f"\nType checking examples:")
print(f"isinstance(42, int): {isinstance(42, int)}")
print(f"isinstance(3.14, float): {isinstance(3.14, float)}")
print(f"isinstance([1,2,3], list): {isinstance([1,2,3], list)}")
python
import math
def solve_quadratic():
print("=== QUADRATIC EQUATION SOLVER ===")
print("Solves equations of the form: ax² + bx + c = 0")
print("="*50)
try:
# Input coefficients
a = float(input("Enter coefficient a: "))
b = float(input("Enter coefficient b: "))
c = float(input("Enter coefficient c: "))
# Calculate discriminant
discriminant = b**2 - 4*a*c
print(f"\nDiscriminant (Δ) = b² - 4ac = {b}² - 4({a})({c}) = {discriminant}")
# Verification
print(f"\nVerification:")
verify1 = a * root1**2 + b * root1 + c
verify2 = a * root2**2 + b * root2 + c
print(f"For root1: {a}×({root1:.4f})² + {b}×({root1:.4f}) + {c} = {verify1:.6f}")
print(f"For root2: {a}×({root2:.4f})² + {b}×({root2:.4f}) + {c} = {verify2:.6f}")
elif discriminant == 0:
print("✅ Discriminant = 0: One repeated real root")
root = -b / (2*a)
print(f"\nRepeated Root = -{b} / (2×{a}) = {root:.4f}")
# Verification
print(f"\nVerification:")
verify = a * root**2 + b * root + c
print(f"{a}×({root:.4f})² + {b}×({root:.4f}) + {c} = {verify:.6f}")
real_part = -b / (2*a)
imaginary_part = math.sqrt(abs(discriminant)) / (2*a)
# Additional information
print(f"\n📊 ADDITIONAL INFORMATION:")
print(f"Vertex x-coordinate: {-b/(2*a):.4f}")
print(f"Vertex y-coordinate: {a*(-b/(2*a))**2 + b*(-b/(2*a)) + c:.4f}")
if a > 0:
print("Parabola opens upward (minimum point)")
else:
print("Parabola opens downward (maximum point)")
except ValueError:
print("❌ Error: Please enter valid numeric values for coefficients!")
except Exception as e:
print(f"❌ An unexpected error occurred: {e}")
while True:
try:
print("\n" + "="*50)
print(" ROBUST QUADRATIC EQUATION SOLVER")
print("="*50)
# Solve equation
result = solve_quadratic_equation(a, b, c)
print(result)
except KeyboardInterrupt:
print("\n\nProgram interrupted. Goodbye!")
break
result = []
result.append(f"Equation: {a}x² + {b}x + {c} = 0")
if a == 0:
if b == 0:
if c == 0:
return "\n".join(result + ["✅ Identity: 0 = 0 (infinite solutions)"])
else:
return "\n".join(result + [f"❌ Contradiction: 0 = {c} (no solution)"])
else:
root = -c / b
return "\n".join(result + [
"✅ Linear equation (a = 0)",
f"Solution: x = {root:.4f}"
])
discriminant = b**2 - 4*a*c
result.append(f"Discriminant = {discriminant}")
if discriminant > 0:
root1 = (-b + math.sqrt(discriminant)) / (2*a)
root2 = (-b - math.sqrt(discriminant)) / (2*a)
result.extend([
"✅ Two distinct real roots:",
f"Root 1 = {root1:.6f}",
f"Root 2 = {root2:.6f}"
])
elif discriminant == 0:
root = -b / (2*a)
result.extend([
"✅ One repeated real root:",
f"Root = {root:.6f}"
])
else:
real = -b / (2*a)
imag = math.sqrt(abs(discriminant)) / (2*a)
result.extend([
"✅ Two complex conjugate roots:",
f"Root 1 = {real:.6f} + {imag:.6f}i",
f"Root 2 = {real:.6f} - {imag:.6f}i"
])
return "\n".join(result)
python
def find_hcf_lcm():
print("=== HCF AND LCM CALCULATOR ===")
print("Using Loop Constructs")
print("="*40)
try:
# Input two numbers
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
print("Steps:")
while temp_num2 != 0:
remainder = temp_num1 % temp_num2
print(f"Step {step}: {temp_num1} = {temp_num2} × {temp_num1 // temp_num2} + {remainder}")
temp_num1, temp_num2 = temp_num2, remainder
step += 1
hcf_euclidean = temp_num1
print(f"✅ HCF using Euclidean Algorithm: {hcf_euclidean}")
smaller = min