System Scripting Lab 11

Python Dictionary and Strings

Setup

mkdir lab11
cd lab11
idle3

Exercise 1: Student Dictionary with Shelve

import shelve

db = shelve.open("students_db")

while True:
    user_input = input("Enter Student ID (or 'k' to list, 'stop' to exit): ")

    if user_input.lower() == "stop":
        print("Program terminated.")
        break

    if user_input == "k":
        print("All Student IDs:")
        for key in db:
            print(key)
        continue

    student_id = user_input

    if student_id in db:
        print("Student:", student_id, db[student_id])
    else:
        name = input("Student not found. Enter name to add: ")
        db[student_id] = name
        print("Student added.")

db.close()

Key Concepts:

Exercise 2: Character Counting Function

def count_chars(text):
    result = {
        "a": text.count("a"),
        "i": text.count("i"),
        "space": text.count(" ")
    }
    return result

while True:
    text = input("Enter text (q to quit): ")

    if text == "q":
        print("Program ended.")
        break

    output = count_chars(text)
    print(output)

Key Concept: count() counts occurrences in string.

Exercise 3: String Type Checker

while True:
    text = input("Enter input (end to stop): ")

    if text == "end":
        print("Goodbye!")
        break

    if text.isdigit():
        print("This is a number")
    elif text.isalpha():
        print("This is a string")

        if text.islower():
            print("Uppercase:", text.upper())
        elif text.isupper():
            print("Lowercase:", text.lower())
    else:
        print("Combination of letters and numbers")

Key Functions:

Exercise 4: Theatre Management System (Dictionary + Shelve)

import shelve

db = shelve.open("theatre_db")

# Function to add members
def add_member():
    name = input("Enter member name: ")
    role = input("Enter role: ")
    db[name] = role
    print("Member added.")

# Function to display table
def display_table():
    try:
        left = int(input("Enter left width: "))
        right = int(input("Enter right width: "))
    except ValueError:
        print("Invalid input!")
        return

    print("\nFormatted Table:")
    print("-" * (left + right))

    for key in db:
        print(f"{key:<{left}} {db[key]:<{right}}")

# Menu system
while True:
    print("\n1. Add Member")
    print("2. Display Members")
    print("3. Exit")

    choice = input("Enter choice: ")

    if choice == "1":
        add_member()
    elif choice == "2":
        display_table()
    elif choice == "3":
        print("Exiting program...")
        break
    else:
        print("Invalid option")

db.close()

Key Concepts:

Key Exam Tips