Unit 1 of 1 · BCA Sem 3

Unit 1: Programming and data handling exercises

Python Programming Laboratory notes · PTU syllabus (UGSEC2508)

3 min read4 topics9 exam questions
On this page
  1. Unit summary
  2. Number and series programs
  3. Menu-driven string operations
  4. NumPy, dictionaries and tuples
  5. Files, exceptions and plots
  6. Key terms
  7. Quick revision
  8. Important questions

Unit summary

This lab practises Python through classic exercises: numbers and series, strings, NumPy arrays, dictionaries, tuples, files, exceptions and plotting. Each section gives model code you can adapt in the practical exam.

After this unit you can

  • Write programs on primes, powers and series
  • Manipulate strings with a menu-driven program
  • Use NumPy arrays, dictionaries and tuples
  • Copy files, handle exceptions and plot curves

PTU syllabus topics

  • Prime number check
  • power calculation
  • even/odd parameterized function
  • alternating series summation
  • menu-driven string operations (character frequency, replace, remove occurrences)
  • string search returning indices
  • NumPy array operations (fill, min/max, dot product, reshape)
  • letter-frequency dictionary
  • tuple operations (split, filter evens, concatenate, min/max)
  • alternate-line file copying
  • ZeroDivisionError handling
  • duplicate-detection exception
  • sine/cosine/polynomial/exponential curve plotting
  • monthly profit line plot
ClassificationLab programs by skill
Python lab
  • Logic

    Prime check, series sums, even/odd

  • Strings

    Frequency, replace, search

  • NumPy

    Fill, min/max, dot product, reshape

  • Files and errors

    Copying files, ZeroDivisionError

  • Plots

    Sine/cosine curves, profit line plot

1

Topic 1

Number and series programs

pythondef is_prime(n):
    if n < 2: return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0: return False
    return True

def even_odd(n): return "Even" if n % 2 == 0 else "Odd"

# Alternating series: 1 - 1/2 + 1/3 - ... up to n terms
n = 10
s = sum(((-1) ** (i + 1)) / i for i in range(1, n + 1))
print(round(s, 4))
print(pow(2, 10), 2 ** 10)    # power
2

Topic 2

Menu-driven string operations

pythons = input("String: ")
while True:
    ch = input("1 Frequency  2 Replace  3 Remove  4 Find  5 Exit: ")
    if ch == "1":
        c = input("Char: "); print(s.count(c))
    elif ch == "2":
        old, new = input("Old: "), input("New: "); s = s.replace(old, new); print(s)
    elif ch == "3":
        c = input("Char: "); s = s.replace(c, ""); print(s)
    elif ch == "4":
        sub = input("Find: ")
        print([i for i in range(len(s)) if s.startswith(sub, i)])   # all indices
    elif ch == "5":
        break
3

Topic 3

NumPy, dictionaries and tuples

pythonimport numpy as np
a = np.full((3, 3), 5); print(a.max(), a.min())
print(np.dot([1, 2, 3], [4, 5, 6]))            # 32
print(np.arange(12).reshape(3, 4))

text = "hello world"
freq = {}
for ch in text.replace(" ", ""):
    freq[ch] = freq.get(ch, 0) + 1
print(freq)

t = (4, 7, 10, 3, 8)
evens = tuple(x for x in t if x % 2 == 0)
print(t[:2], t[2:], evens, t + (1, 2), max(t), min(t))
4

Topic 4

Files, exceptions and plots

pythonwith open("in.txt") as src, open("out.txt", "w") as dst:
    for i, line in enumerate(src):
        if i % 2 == 0: dst.write(line)          # copy alternate lines

try:
    print(10 / int(input()))
except ZeroDivisionError:
    print("Division by zero!")

class DuplicateError(Exception): pass
nums = [3, 5, 3]
if len(nums) != len(set(nums)):
    raise DuplicateError("Duplicate values found")
pythonimport matplotlib.pyplot as plt, numpy as np
months = ["Jan", "Feb", "Mar", "Apr"]; profit = [20, 35, 30, 45]
plt.plot(months, profit, marker="o"); plt.title("Monthly profit"); plt.show()
x = np.linspace(-3, 3, 100)
plt.plot(x, x ** 2, label="polynomial"); plt.plot(x, np.exp(x), label="exponential")
plt.legend(); plt.show()

Key terms

List comprehension
Creating a list in one line with a loop and condition
dict.get(key, default)
Returns a value or a default if the key is missing
enumerate
Gives index and value while looping
Custom exception
A user-defined class inheriting from Exception

Quick revision

  • Check primes up to √n.
  • dict.get(ch, 0) + 1 counts frequencies.
  • Tuples are immutable; build new tuples for results.
  • enumerate helps copy alternate lines; set() detects duplicates.

Important exam questions

Practice questions written to the PTU exam pattern for this unit's syllabus: short answers (Section A style) and long answers (Sections B and C style).

Short-answer questions

  1. Q1.How do you find all indices of a substring?
  2. Q2.How is a character frequency dictionary built?
  3. Q3.How do you detect duplicates in a list?
  4. Q4.What does np.full do?
  5. Q5.How do you add markers to a line plot?

Long-answer questions

  1. Q1.Write a menu-driven program for string operations.
  2. Q2.Write programs to perform NumPy array operations including dot product and reshape.
  3. Q3.Write a program to copy alternate lines of a file and handle exceptions.
  4. Q4.Plot sine, cosine, polynomial and exponential curves and a monthly profit chart.

Stuck on this unit?

Message SBS on WhatsApp for help with Python Programming Laboratory, or to ask about studying BCA at Synetic.

WhatsApp us