Data Structure Practical

 Aim - Write a Python program to calculate the gross salary of an employee

Source Code - 

print("SALARY PROGRAM")

name= str(input("Enter name of employee:"))

basic=float(input("Enter Basic Salary :"))

da=float(basic*0.70)

hra=float(basic*0.10)

ta=float(basic*0.30)

grosspay=float(basic+da+hra+ta)

print("\n\n")

print(" NAME OF EMPLOYEE : ",name)

print(" BASIC SALARY : ",basic)

print(" DEARNESS ALLOW. : ",da)

print(" HOUSE RENT ALLOW.: ",hra)

print(" TRAVEL ALLOW. : ",ta)

print(" GROSS PAYMENT : ",grosspay)

 

Aim - Develop a Python program to manage a task list using lists and tuples, including adding, removing, updating, and sorting tasks.

Source Code -

task = ['cleaning', 'cycling'] 

# Add elements to the list 

task_add = ['studying', 'playing', 'gym'] 

task.extend(task_add) 

print("Add:", task) 

# Remove an element from the list 

task.remove('playing')   

print("Remove:", task) 

# Update the item at index 1 

task[1] = 'running'   

print("Update:", task) 

# Sort elements based on length 

task.sort(key=len) 

print("Sort:", task)


Aim - Create a Python code to demonstrate the use of sets and perform set operations (union, intersection, difference) to manage student enrollments in multiple courses / appearing for multiple entrance exams like CET, JEE, NEET etc.

Source Code - 

# Example enrollment sets 

cet_students = {"Alice", "Bob", "Charlie", "David"} 

jee_students = {"Bob", "Eve", "Frank", "Charlie"} 

neet_students = {"Alice", "Eve", "Grace", "Charlie"} 

#Perform  Union Operation  

all_students = (cet_students).union(jee_students).union(neet_students) 

print("Union (All Students):", all_students) 

#Perform  Intersection Operation  

common_students =  (cet_students).intersection(jee_students).intersection(neet_students) 

print("Intersection (Common Students):", common_students) 

# Perform difference operations 

diff_cet = cet_students.difference(jee_students.union(neet_students)) 

diff_jee = jee_students.difference(cet_students.union(neet_students)) 

diff_neet = neet_students.difference(cet_students.union(jee_students)) 

print("Students for to CET:", diff_cet) 

print("Students for to JEE:", diff_jee) 

print("Students for to NEET:", diff_neet)


Aim - Develop a Python program that takes a numerical input and identifies whether it is even or odd, utilizing conditional statements and loops.

Source Code - 

 def check_even_odd(): 

    while True: 

        try: 

            num = int(input("Enter a number (or type '0' to exit): ")) 

            if num == 0: 

                print("Exiting the program. Goodbye!") 

                break 

            elif num % 2 == 0: 

                print(f"{num} is an even number.") 

            else: 

                print(f"{num} is an odd number.") 

        except ValueError: 

            print("Invalid input! Please enter a valid integer.") 

 

# Run the function 

check_even_odd()

 

Aim - Using function, write a Python program to analyze the input number is prime or not.

Source Code -

def is_prime(n): 

    """Function to check if a number is prime""" 

    if n <= 1: 

        return False 

    for i in range(2, int(n**0.5) + 1): 

        if n % i == 0: 

            return False 

    return True 

 # Taking user input 

num = int(input("Enter a number: ")) 

 # Checking and displaying the result 

if is_prime(num): 

    print(f"{num} is a prime number.") 

else: 

    print(f"{num} is not a prime number.")


Aim - Demonstrate the use of a Python debugger (e.g., pdb or an IDE with debugging capabilities) on a sample program with intentional errors. Guide students on setting breakpoints, stepping through code, and examining variable values

Source Code - 

def add(a, b):

    result = a + b

    return result

def main():

    x = 10

    y = 20

    import pdb; pdb.set_trace()  # <- Debugger starts here

    total = add(x, y)

    print("Total:", total)


main()


Aim - Write a Python script that prompts the user to enter their phone number and email ID. It then employs Regular Expressions to verify if these inputs adhere to standard phone number and email address formats.

Source Code -

import re 

 

def validate_phone(phone): 

    phone_pattern = re.compile(r"^\+?[0-9]{1,3}?[-.\s]?\(?[0-9]{1,4}?\)?[-.\s]?[0-9]{1,4}[-.\s]?[0

9]{1,9}$") 

    return bool(phone_pattern.match(phone)) 

 

def validate_email(email): 

    email_pattern = re.compile(r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$") 

    return bool(email_pattern.match(email)) 

 

def main(): 

    phone = input("Enter your phone number: ") 

    email = input("Enter your email ID: ") 

     

    if validate_phone(phone): 

        print("Valid phone number") 

    else: 

        print("Invalid phone number") 

     

    if validate_email(email): 

        print("Valid email address") 

    else: 

        print("Invalid email address") 

 

if __name__ == "__main__": 

    main() 


Aim: Develop a Python script to create two arrays of the same shape and perform element-wise addition, subtraction, multiplication, and division. Calculate the dot product and cross product of two vectors

Source Code -

import numpy as np 

# Creating two arrays of the same shape (2x3 for demonstration) 

arr1 = np.array([[1, 2, 3], [4, 5, 6]]) 

arr2 = np.array([[7, 8, 9], [10, 11, 12]]) 

print("Array 1:") 

print(arr1) 

print("\nArray 2:") 

print(arr2) 

# Element-wise addition 

addition = arr1 + arr2 

print("\nElement-wise Addition:") 

print(addition) 

# Element-wise subtraction 

subtraction = arr1 - arr2 

print("\nElement-wise Subtraction:") 

print(subtraction) 

# Element-wise multiplication 

multiplication = arr1 * arr2 

print("\nElement-wise Multiplication:") 

print(multiplication) 

# Element-wise division 

division = arr1 / arr2 

print("\nElement-wise Division:") 

print(division) 

# Dot product of two vectors (flatten the arrays for 1D vectors) 

dot_product = np.dot(arr1.flatten(), arr2.flatten()) 

print("\nDot Product of flattened vectors:") 

print(dot_product) 

# Cross product (only for 3-dimensional vectors, so we'll use 3 elements from each array) 

cross_product = np.cross(arr1[0], arr2[0])  # Using the first row as 3D vectors 

print("\nCross Product of the first row vectors:") 

print(cross_product)  



Aim - Write a Python program that takes two numbers as input and performs division. Implement exception handling to manage division by zero and invalid input errors gracefully.

Source Code -

def divide_numbers (): 
    try: 
        num1 = float(input("Enter the first number: ")) 
        num2 = float(input("Enter the second number: ")) 
        result = num1 / num2 
    except ValueError: 
        print("Error: Invalid input. Please enter numeric values.") 
except ZeroDivisionError: 
print("Error: Division by zero is not allowed.") 
else: 
print(f"Result: {result}") 
finally: 
print("Execution completed.") 
if __name__ == "__main__": 
divide_numbers()

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.