TU BCA Scripting Language Master Guide: Python Data Structures, File I/O & Regular Expressions (Lab Programs)

Author: Bhuban Subedi | Subject: Scripting Language (CACS253) | Semester: Fourth Semester


Scripting languages power automation workflows, system administration, web scraping, backend APIs, and artificial intelligence pipelines. In the Tribhuvan University BCA fourth semester, Scripting Language (CACS253) equips students with modern Python programming skills, string manipulation algorithms, file I/O operations, and pattern matching through Regular Expressions (Regex).

In the final 60-mark TU board examination and the 40-mark external laboratory viva, students are tested on Python List/Dictionary Comprehensions, Regex validation algorithms (e.g., validating Nepali mobile numbers and email addresses), and Exception-safe file processing.

In this guide, I will provide complete, production-ready Python programs designed for TU examination success.


1. Compiled vs. Scripting Languages

+-------------------+-----------------------------------+-----------------------------------+
| Feature           | Compiled Languages (e.g., C, C++) | Scripting Languages (e.g., Python)|
+-------------------+-----------------------------------+-----------------------------------+
| **Execution**     | Direct binary machine code output | Interpreted line-by-line via      |
|                   | via compiler (Ahead-of-Time).     | Virtual Machine (Bytecode + PVM). |
+-------------------+-----------------------------------+-----------------------------------+
| **Typing**        | Statically typed (Explicit decl). | Dynamically typed (Type inferred).|
+-------------------+-----------------------------------+-----------------------------------+
| **Development**   | Longer compile-build cycles,      | Rapid prototyping, clean syntax,  |
|                   | maximum CPU execution speed.      | extensive standard library.       |
+-------------------+-----------------------------------+-----------------------------------+

2. Python Data Structures: Lists, Tuples, Dictionaries & Sets

+---------------+---------------+---------------+---------------------------------------+
| Data Structure| Syntax        | Mutability    | Use Case & Key Property               |
+---------------+---------------+---------------+---------------------------------------+
| **List**      | `[1, 2, 3]`   | Mutable       | Ordered collection; allows duplicates.|
+---------------+---------------+---------------+---------------------------------------+
| **Tuple**     | `(1, 2, 3)`   | Immutable     | Fixed record coordinates; fast lookup.|
+---------------+---------------+---------------+---------------------------------------+
| **Dictionary**| `{'a': 1}`    | Mutable       | Key-Value pairs; unique hashable keys.|
+---------------+---------------+---------------+---------------------------------------+
| **Set**       | `{1, 2, 3}`   | Mutable       | Unordered collection of unique items. |
+---------------+---------------+---------------+---------------------------------------+

High-Scoring Exam Concept: List & Dictionary Comprehensions

# Filtering even numbers and squaring them in 1 line
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = [x**2 for x in numbers if x % 2 == 0]
print(f"Even Squares: {even_squares}")
# Output: [4, 16, 36, 64, 100]

# Dictionary Comprehension: Mapping students to letter grades
marks = {"Ram": 85, "Sita": 92, "Hari": 45, "Gita": 78}
status = {student: ("PASS" if score >= 50 else "FAIL") for student, score in marks.items()}
print(f"Student Results: {status}")

3. Regular Expressions (Regex) in Python: Lab Exam Code

In TU exams, writing a Python script to validate input strings using the re module is a recurring 5-to-10 mark question.

import re

def validate_nepal_contact_info(email, phone):
    """
    Validates email format and Nepal mobile phone numbers (+977-98XXXXXXXX or 98XXXXXXXX).
    """
    # Email Regex Pattern
    email_pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'

    # Nepal Mobile Phone Regex (NTC/Ncell: 984, 985, 986, 980, 981, 982 followed by 7 digits)
    phone_pattern = r'^(?:\+977[- ]?)?(?:98\d{8}|97\d{8})$'

    is_email_valid = bool(re.match(email_pattern, email))
    is_phone_valid = bool(re.match(phone_pattern, phone))

    return is_email_valid, is_phone_valid

# Practical Testing
test_email = "[email protected]"
test_phone = "+977-9841234567"

valid_email, valid_phone = validate_nepal_contact_info(test_email, test_phone)
print(f"Email '{test_email}' Valid: {valid_email}")
print(f"Phone '{test_phone}' Valid: {valid_phone}")

4. Exception-Safe File Handling & JSON Processing

import json

# Complete TU Lab Practical: Writing and Reading Structured JSON Data
student_data = [
    {"roll": 101, "name": "Bhuban Subedi", "semester": "Fourth", "gpa": 3.92},
    {"roll": 102, "name": "Aayush Sharma", "semester": "Fourth", "gpa": 3.75}
]

filename = "tu_bca_students.json"

# Writing to File with Context Manager
try:
    with open(filename, 'w', encoding='utf-8') as file:
        json.dump(student_data, file, indent=4)
    print(f"Successfully saved student records to {filename}")
except IOError as e:
    print(f"Error writing to file: {e}")

# Reading and Processing File
try:
    with open(filename, 'r', encoding='utf-8') as file:
        loaded_records = json.load(file)
        print("\n--- Processed Student List ---")
        for st in loaded_records:
            print(f"Roll: {st['roll']} | Name: {st['name']} | GPA: {st['gpa']}")
except FileNotFoundError:
    print("Requested file not found on disk.")

Frequently Asked Questions (FAQ)

Q1: What is the difference between re.match() and re.search()?

re.match() checks for a match only at the beginning of the string, while re.search() searches the entire string for the first location where the regex pattern produces a match.

Q2: What are *args and **kwargs in Python functions?

*args allows a function to accept any number of positional arguments (as a tuple), while **kwargs allows a function to accept any number of keyword arguments (as a dictionary).

LEAVE A REPLY

Please enter your comment!
Please enter your name here