Introduction to Software Systems
  • About
  • Introduction
  • Software Engineering
    • Software System
    • Software Product Development
    • Computer Networks
  • Terminal Programming
    • BASH - Basic Commands
    • BASH - Conditions and Loops
    • Worked-out Examples
    • Practice Questions
  • Databases
    • Structured Databases
      • SQL Queries
      • Worked-out Example
    • Unstructured Databases
      • NoSQL Queries
      • Worked-out Example
  • Object Oriented Programming
    • Python - Introduction
    • Python - Basic Concepts
    • Python - Inbuilt Datastructures
    • Python - Conditions and Loops
    • Python - Lambda, Functions, Class/Objects
    • Worked-out Examples
  • WEB TECHNOLOGIES
    • HTML
    • CSS
    • Native JavaScript - Basics
    • Native JavaScript - Conditional Statements and Loops
    • Native JavaScript - Data Structures
    • JavaScript - Scope, Functions, Type Conversion
Powered by GitBook
On this page
  1. Object Oriented Programming

Worked-out Examples

  1. Write a python program to reverse a string and check if it is a palindrome.

def reverse_string(input_str):
    """Reverses the input string."""
    return input_str[::-1]

def is_palindrome(input_str):
    """Checks if the input string is a palindrome."""
    reversed_str = reverse_string(input_str)
    return input_str.lower() == reversed_str.lower()

def main():
    input_str = input("Enter a string: ")
    reversed_str = reverse_string(input_str)
    
    print(f"Original String: {input_str}")
    print(f"Reversed String: {reversed_str}")
    
    if is_palindrome(input_str):
        print(f"'{input_str}' is a palindrome.")
    else:
        print(f"'{input_str}' is not a palindrome.")

if __name__ == "__main__":
    main()

  1. Write a python program to generate Lucas Series

def lucas_series(n):
    """Generates the Lucas series up to n terms."""
    series = [2, 1]
    
    # Generate the series up to n terms
    while len(series) < n:
        next_term = series[-1] + series[-2]
        series.append(next_term)
    
    return series

def main():
    n = int(input("Enter the number of terms: "))
    lucas_terms = lucas_series(n)
    
    print(f"The Lucas series up to {n} terms is: {lucas_terms}")

if __name__ == "__main__":
    main()
  1. Generate a Lucas Series using a Recursive Function

def lucas_recursive(n, memo={}):
    """Generates the nth term of the Lucas sequence recursively."""
    if n in memo:
        return memo[n]
    if n == 0:
        return 2
    elif n == 1:
        return 1
    else:
        memo[n] = lucas_recursive(n-1, memo) + lucas_recursive(n-2, memo)
        return memo[n]

def lucas_series(n):
    """Generates the Lucas series up to n terms using recursion."""
    return [lucas_recursive(i) for i in range(n)]

def main():
    n = int(input("Enter the number of terms: "))
    lucas_terms = lucas_series(n)
    
    print(f"The Lucas series up to {n} terms is: {lucas_terms}")

if __name__ == "__main__":
    main()
  1. How do I calculate Taxation using Python considering both Indian Old Regime Tax Slab and New Regime Tax Slab

def calculate_tax_old_regime(income):
    """Calculates tax under the old regime."""
    tax = 0
    if income <= 400000:
        return tax
    elif income <= 800000:
        tax += (income - 400000) * 0.05
    if income > 800000:
        if income <= 1200000:
            tax += (income - 800000) * 0.10
        elif income <= 1600000:
            tax += (1200000 - 800000) * 0.10
            tax += (income - 1200000) * 0.15
        elif income <= 2000000:
            tax += (1200000 - 800000) * 0.10
            tax += (1600000 - 1200000) * 0.15
            tax += (income - 1600000) * 0.20
        elif income <= 2400000:
            tax += (1200000 - 800000) * 0.10
            tax += (1600000 - 1200000) * 0.15
            tax += (2000000 - 1600000) * 0.20
            tax += (income - 2000000) * 0.25
        else:
            tax += (1200000 - 800000) * 0.10
            tax += (1600000 - 1200000) * 0.15
            tax += (2000000 - 1600000) * 0.20
            tax += (2400000 - 2000000) * 0.25
            tax += (income - 2400000) * 0.30
    return tax

def calculate_tax_new_regime(income):
    """Calculates tax under the new regime."""
    tax = 0
    if income <= 1200000:
        return tax
    elif income <= 1600000:
        tax += (income - 1200000) * 0.10
    elif income <= 2000000:
        tax += (1600000 - 1200000) * 0.10
        tax += (income - 1600000) * 0.15
    elif income <= 2400000:
        tax += (1600000 - 1200000) * 0.10
        tax += (2000000 - 1600000) * 0.15
        tax += (income - 2000000) * 0.20
    else:
        tax += (1600000 - 1200000) * 0.10
        tax += (2000000 - 1600000) * 0.15
        tax += (2400000 - 2000000) * 0.20
        tax += (income - 2400000) * 0.30
    return tax

def main():
    income = float(input("Enter your annual income: "))
    
    old_tax = calculate_tax_old_regime(income)
    new_tax = calculate_tax_new_regime(income)
    
    print(f"Tax under Old Regime: ₹{old_tax:.2f}")
    print(f"Tax under New Regime: ₹{new_tax:.2f}")

if __name__ == "__main__":
    main()
  1. Using Dictionaries read Name and Date of Birth as input and compute the age of all the people as of the program execution date.

from datetime import datetime

def calculate_age(birth_date):
    """Calculates the age based on the birth date."""
    today = datetime.today()
    age = today.year - birth_date.year - ((today.month, today.day) < (birth_date.month, birth_date.day))
    return age

def main():
    people = {}
    
    num_people = int(input("Enter the number of people: "))
    
    for i in range(num_people):
        name = input(f"Enter name of person {i+1}: ")
        dob_input = input(f"Enter date of birth for {name} (in YYYY-MM-DD format): ")
        
        # Convert input to datetime object
        dob = datetime.strptime(dob_input, "%Y-%m-%d")
        
        people[name] = dob
    
    print("\nPeople and their ages as of today:")
    
    for name, dob in people.items():
        age = calculate_age(dob)
        print(f"{name}: {age} years old")

if __name__ == "__main__":
    main()
  1. Compute SGPA by reading marks of 6 subjects in a given semester

def calculate_grade_point(marks):
    """Calculates the grade point based on the marks."""
    if marks >= 90:
        return 10
    elif marks >= 80:
        return 9
    elif marks >= 70:
        return 8
    elif marks >= 60:
        return 7
    elif marks >= 50:
        return 6
    elif marks >= 45:
        return 5
    elif marks >= 40:
        return 4
    else:
        return 0

def calculate_sgpa(marks_list):
    """Calculates the SGPA from a list of marks."""
    total_grade_points = sum(calculate_grade_point(marks) for marks in marks_list)
    sgpa = total_grade_points / len(marks_list)
    return sgpa

def main():
    subjects = ["Subject 1", "Subject 2", "Subject 3", "Subject 4", "Subject 5", "Subject 6"]
    marks_list = []
    
    for subject in subjects:
        while True:
            try:
                marks = float(input(f"Enter marks for {subject} (out of 100): "))
                if marks < 0 or marks > 100:
                    print("Marks must be between 0 and 100.")
                else:
                    marks_list.append(marks)
                    break
            except ValueError:
                print("Invalid input. Please enter a number.")
    
    sgpa = calculate_sgpa(marks_list)
    
    print(f"\nSGPA: {sgpa:.2f}")

if __name__ == "__main__":
    main()
  1. A Sample script to illustrate Tuples in Python

def main():
    # Creating a tuple
    fruits = ("Apple", "Banana", "Cherry")
    print("Tuple of fruits:", fruits)
    
    # Accessing tuple elements
    print("\nAccessing elements:")
    print("First fruit:", fruits[0])
    print("Last fruit:", fruits[-1])
    
    # Tuple slicing
    print("\nTuple slicing:")
    print("First two fruits:", fruits[:2])
    print("Last two fruits:", fruits[-2:])
    
    # Tuple concatenation
    more_fruits = ("Date", "Elderberry")
    all_fruits = fruits + more_fruits
    print("\nTuple concatenation:")
    print("All fruits:", all_fruits)
    
    # Tuple multiplication
    repeated_fruits = fruits * 2
    print("\nTuple multiplication:")
    print("Repeated fruits:", repeated_fruits)
    
    # Checking if an element exists in a tuple
    print("\nChecking if 'Banana' exists in the tuple:")
    print("Banana" in fruits)
    
    # Tuple is immutable
    try:
        fruits[0] = "Mango"
    except TypeError as e:
        print("\nTuples are immutable:")
        print(e)

if __name__ == "__main__":
    main()
  1. Read two sets of 30 random student roll numbers and store them in a SET. Print the UNION, INTERSECTION, DIFFERENCE, SYMMETRIC DIFFERENCE

import random

def generate_random_roll_numbers(n):
    """Generates a set of n unique random roll numbers."""
    roll_numbers = set()
    while len(roll_numbers) < n:
        roll_numbers.add(random.randint(1, 1000))  # Assuming roll numbers are between 1 and 1000
    return roll_numbers

def main():
    # Generate two sets of random roll numbers
    set1 = generate_random_roll_numbers(30)
    set2 = generate_random_roll_numbers(30)
    
    print("Set 1:", set1)
    print("Set 2:", set2)
    
    # Perform set operations
    union = set1.union(set2)
    intersection = set1.intersection(set2)
    difference1 = set1.difference(set2)
    difference2 = set2.difference(set1)
    symmetric_difference = set1.symmetric_difference(set2)
    
    print("\nSet Operations:")
    print("Union:", union)
    print("Intersection:", intersection)
    print("Difference (Set1 - Set2):", difference1)
    print("Difference (Set2 - Set1):", difference2)
    print("Symmetric Difference:", symmetric_difference)

if __name__ == "__main__":
    main()
PreviousPython - Lambda, Functions, Class/ObjectsNextHTML

Last updated 2 months ago