BCAMCABSc ITB.Tech CSE

Python — syllabus, exam questions and lab programs

Your scheme may call it Introduction to Programming using Python (BCA01010T).

GNDU's BCA scheme for the 2025 batch starts programming with Python rather than C, which is a better decision than it looks. You spend the first semester learning to think about a problem instead of fighting a compiler, and the things that used to take a month — getting a string to reverse, getting input to work — take an afternoon.

The paper is BCA01010T with its lab as BCA01011L, and the lab is the part worth taking seriously. The scheme spells out how it is examined: you write the answer on the answer sheet, then implement the same thing on the computer, both halves are marked, and a viva runs one-to-one beside you about the code you are writing at that moment. That format is unforgiving of memorised programs and generous to anybody who has actually typed things in and broken them.

So the honest advice for this paper is the least glamorous: do the exercises. All of them, on a machine, with the interpreter open. There are about ten areas in the lab list and each is an evening's work. Ten evenings across a semester is not a heavy ask, and it is the difference between a viva that goes well and one that does not.

We teach this

Python is one of the papers we teach at WebPrims

This is not only a page about Python. It is a subject we teach in a classroom on Majitha Road — tuition for Python, if that is the word you were searching for — and a good share of every batch is college students taking it alongside their own semester. Bring your scheme and we cover what is on it.

What that means in practice: the whole syllabus gets covered rather than the parts that make a good demo, you write code on a machine instead of copying it into a file, and the lab work gets done here rather than the night before submission.

What we will not say is that this guarantees you marks or a job. We do not run placements and we do not promise results. Come and sit in a class, decide for yourself.

₹4,500 / month— one rate, any subjectMon–Sat, batches at 11, 1, 3 and 5Majitha Road, Amritsar

The syllabus, unit by unit

What each unit actually contains, and whether it is there because it matters or because it is on the paper. Unit order and numbering vary between GNDU, PTU and your batch’s scheme — check your own before you plan a revision week.

1

The interpreter and the environment

Using the Python interactive interpreter, getting familiar with an IDE, running a script from a file, and the difference between the two.

Trivial to learn and explicitly in the lab list, so it will come up. Know how to do the same thing in the shell and in a file.

2

Fundamentals, data types and operators

Variables and dynamic typing, int, float, str and bool, type conversion, arithmetic, relational, logical, assignment, membership and identity operators, and input and output.

The base for everything else. The identity operator — is versus == — is a favourite viva question and catches most people.

3

Flow control and loops

if, else and elif; the while statement; for loops over a sequence and over range; loop patterns such as accumulation, search and counting; break, continue and the loop-else clause.

Loop patterns are named in the scheme, which means the examiner has them in mind. Be able to write a running total, a search and a counter without thinking.

4

Collections — list, tuple, dictionary

Creating and indexing each, slicing, mutability, the list methods, tuple packing and unpacking, dictionary keys, values and items, nesting, and comprehensions.

The single biggest unit in the lab list and the most useful thing in the paper. Dictionaries in particular are what make Python worth using.

5

Functions

Defining functions, parameters and arguments, default and keyword arguments, return values including multiple returns, scope and the global statement, and lambda.

Passing parameters and returning values are called out by name in the scheme. Expect to be asked to write one and then explain what happens to a list passed into it.

6

Modules

Importing a module, the from-import form, aliasing, writing your own module and importing it, and the standard library modules math, random and datetime.

Writing your own module is the part people skip. It is two files and five minutes, and it is in the exercise list.

7

Exception handling

try and except, catching specific exception types, else and finally, raising an exception, and the common built-in exceptions.

Short unit, reliably examined, and genuinely useful the first time a program meets input it did not expect.

8

Files

Opening files and the modes, reading whole files and line by line, writing and appending, the with statement, and organising data into and out of a file.

The scheme says 'reading, writing and organizing files', so expect a question that reads a file, does something with the contents and writes a result.

9

Basic NumPy and pandas

Creating an array, array operations against a plain list, creating a DataFrame, reading a CSV, selecting rows and columns, and simple aggregation.

The last item in the lab list and the one that opens a career rather than a paper. Do not treat it as an afterthought.

What is worth keeping after the exam

Revise all of it — the marks are the marks. But it is worth knowing which half of this paper you will still be using in two years, and which half exists because it is on the paper.

Stays with you

  • +Almost all of it — Python is the one first-year paper whose content you will still be using in five years
  • +Dictionaries and comprehensions, which shape how you write everything afterwards
  • +Exception handling, and the habit of deciding what happens when input is wrong
  • +pandas, which is the entry point to data work and to most automation jobs
  • +Reading and writing files, which is most of what a small script ever does

For the exam, and then gone

  • −Writing out the operator precedence table
  • −Reciting the differences between a list and a tuple as a definition rather than using them
  • −Flowcharts for programs you could simply write

Questions that come up year after year

Not a guess paper, and not a promise about what will be set. These are the questions this subject keeps asking because they are the ones that test whether you understood it.

  1. 01Write a program to check whether a number is prime
  2. 02Explain the difference between a list, a tuple and a dictionary with examples
  3. 03Write a program to count the frequency of each word in a file
  4. 04What is the difference between == and is?
  5. 05Write a program using a user-defined function to compute factorial
  6. 06Explain exception handling with try, except, else and finally
  7. 07Write a program to read a CSV with pandas and show the first five rows
  8. 08Explain list comprehension with an example

What students get wrong

From teaching this paper, not from a list somewhere. Each of these costs marks every year.

Wrong — Preparing for this paper the way you would prepare for a theory paper.

Right — The scheme says you write the answer and then implement it on a computer, with a viva about the code you are writing. Reading prepares you for half of that. Type the exercises in — it is the only preparation that covers both halves.

Wrong — Using a mutable default argument, such as def add(item, items=[]).

Right — That list is created once and shared by every call, so the second call sees the first call's data. Use None as the default and create the list inside. This is a standard viva question because it catches people who learned the syntax without the model behind it.

Wrong — Assuming a list passed into a function is copied.

Right — It is not. The function receives a reference, so appending inside the function changes the caller's list. Integers and strings behave differently because they are immutable — which is the real answer to 'is Python call by value or call by reference'.

Wrong — Comparing strings or small numbers with is because it happened to work.

Right — == compares values, is compares identity. Small integers and short strings are cached by the interpreter, so is appears to work and then fails on larger values. Use == for values, is only for None.

Lab file programs

These compile and run as written — type them in, break them, and fix them. Copying a program into a file you never ran is how a practical viva goes badly.

Word frequency from a file

Covers files, dictionaries, string methods and sorting in one program — four items from the lab list at once.

python
def word_frequency(path):
    counts = {}

    with open(path, "r", encoding="utf-8") as f:
        for line in f:
            for word in line.lower().split():
                word = word.strip(".,!?;:'\"()")
                if word:
                    counts[word] = counts.get(word, 0) + 1

    return counts


if __name__ == "__main__":
    try:
        counts = word_frequency("sample.txt")
    except FileNotFoundError:
        print("sample.txt not found - create it first")
    else:
        # Sort by count, highest first, then alphabetically for ties
        for word, n in sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:10]:
            print(f"{word:15} {n}")

Functions, parameters and return values

The exercise the scheme names directly, including the mutable-default trap the viva asks about.

python
def statistics(numbers):
    """Returns several values at once - a tuple, unpacked by the caller."""
    total = sum(numbers)
    return total, total / len(numbers), min(numbers), max(numbers)


def add_mark(mark, marks=None):
    """The correct pattern. A default of [] would be shared by every call."""
    if marks is None:
        marks = []
    marks.append(mark)
    return marks


def apply_bonus(marks, bonus=5):
    """A list argument is a reference: this changes the caller's list."""
    for i in range(len(marks)):
        marks[i] = min(marks[i] + bonus, 100)


marks = [78, 85, 61, 92]
total, average, lowest, highest = statistics(marks)
print(f"total={total} average={average:.2f} low={lowest} high={highest}")

apply_bonus(marks)
print("after bonus:", marks)          # the original list has changed

print(add_mark(70))                   # [70]
print(add_mark(80))                   # [80], not [70, 80]

A first look at NumPy and pandas

The last item in the lab list. Creates data rather than needing a file, so it runs anywhere.

python
import numpy as np
import pandas as pd

# NumPy: an array does arithmetic on every element at once
marks = np.array([78, 85, 61, 92, 55])
print("raw      :", marks)
print("scaled   :", marks * 1.1)
print("mean     :", marks.mean(), " max:", marks.max())

# pandas: a DataFrame is a table with named columns
df = pd.DataFrame({
    "roll_no": [101, 102, 103, 104, 105],
    "name":    ["Simran", "Harjot", "Navdeep", "Gurleen", "Arshdeep"],
    "city":    ["Amritsar", "Tarn Taran", "Amritsar", "Batala", "Amritsar"],
    "marks":   [78, 85, 61, 92, 55],
})

print("\nFirst three rows:")
print(df.head(3))

print("\nStudents who scored above 70:")
print(df[df["marks"] > 70][["name", "marks"]])

print("\nAverage marks per city:")
print(df.groupby("city")["marks"].mean().round(1))

# Writing it back out, which is the other half of 'organizing files'
df.to_csv("students.csv", index=False)
print("\nWritten to students.csv")

Long questions, answered the way they are marked

Not model answers to reproduce. What the examiner is checking for, and where the marks actually sit in each one.

Explain the difference between a list, a tuple and a dictionary.

A list is an ordered, mutable sequence written in square brackets and indexed by position. A tuple is ordered and immutable, written in round brackets, which makes it usable as a dictionary key and safe to pass around. A dictionary is a mapping from keys to values in curly brackets, looked up by key rather than by position, and its keys must be immutable. Give one line of code creating each and one operation on each — the examiner is checking you have used them, not that you can recite three definitions. Add why immutability matters, and the answer is complete.

What is the difference between == and is?

== asks whether two objects have the same value; is asks whether they are the same object in memory. For small integers and short strings the interpreter caches objects, so is appears to give the same answer as == and then stops doing so for larger values — which is exactly why the question is set. The rule to state: use == for comparing values, and is only for None. Demonstrating it with two lists holding identical contents makes the point in three lines.

Explain exception handling in Python with an example.

try holds the code that may fail; except catches a specific exception type and handles it; else runs only if nothing was raised; finally runs either way and is where cleanup goes. Catch specific exceptions rather than a bare except, which would also swallow a keyboard interrupt. Use a file that may not exist or an int() on bad input as the example, and show all four clauses in one program — an answer with try and except alone usually loses the marks for else and finally.

Is Python call by value or call by reference?

Neither, strictly — it passes a reference to the object, and what you observe depends on whether the object is mutable. Pass a list and append inside the function and the caller sees the change. Pass an integer or a string and reassign it inside the function and the caller sees nothing, because reassignment binds the local name to a new object rather than altering the old one. The phrase for it is call by object reference. Show both cases in one short program; that is what turns a memorised phrase into a full answer.

Difference between — the ones that get asked

Every one of these is a five-mark question somewhere on this syllabus, and the marks are rarely in the first line. They are in the consequences underneath it.

List vs Tuple

A list can be changed after it is created; a tuple cannot. Everything else follows from that one fact.

 listtuple
Syntax[1, 2, 3](1, 2, 3)
MutableYes — append, remove, change items in place.No. Once built, it is fixed.
MethodsAbout eleven, including append, insert, pop, sort, reverse.Two — count and index.
Memory and speedSlightly larger, slightly slower to iterate.Smaller and faster, because the size never changes.
Can be a dictionary keyNo — unhashable.Yes, provided everything inside it is also hashable.
Typical useA collection that grows or changes — a list of students.A fixed record of mixed things — a coordinate, a database row.

Where people lose the marks

The trap: a tuple being immutable does not make its contents immutable. ([1,2], 3) is a tuple whose first item is a list, and you can still append to that list. The tuple's structure is frozen, not the objects it points at.

List vs Dictionary

A list finds things by position. A dictionary finds things by name. If you are searching a list to find a matching item, you probably wanted a dictionary.

 listdict
Access byInteger index — items[0]Key — items["roll_no"]
Lookup costO(n) to find a value you did not know the position of.O(1) average, because it is hashed.
StoresValues.Key-value pairs.
DuplicatesAllowed.Keys must be unique; values need not be.
OrderingOrdered by position.Keeps insertion order since Python 3.7, but you do not index it by position.

Where people lose the marks

In a lab program, the moment you write a for loop over a list to find the item whose name matches, that is the signal to use a dictionary instead. It is also the single most common reason a student's program is slow.

Python 2 vs Python 3

Python 2 reached end of life on 1 January 2020 and receives no updates, not even security fixes. There is no situation in which a student should start a new program in it.

 Python 2Python 3
printA statement — print "hi"A function — print("hi")
Integer division5/2 gives 2.5/2 gives 2.5; 5//2 gives 2.
StringsASCII by default; a separate unicode type.Unicode by default; bytes is the separate type.
input()Evaluates what you type — a security problem. raw_input() is the safe one.Always returns a string. Convert it yourself.
SupportEnded January 2020.Current.

Where people lose the marks

This question survives in question papers long after it stopped mattering in practice. Answer it properly, then write every line of code you actually run in Python 3.

sort() vs sorted()

sort() rearranges the list you call it on and returns None. sorted() leaves the original alone and hands you a new sorted list.

 list.sort()sorted()
Changes the originalYes, in place.No.
ReturnsNone.A new list.
Works onLists only.Any iterable — tuples, strings, sets, dict keys.
MemoryNo extra list.Builds a second list.

Where people lose the marks

The bug this causes constantly: x = my_list.sort() sets x to None, and then the next line fails with a message about NoneType that does not mention sorting at all. If you want the result, use sorted().

Multiple choice, with the reason

Universities set an objective section and campus written rounds are almost nothing else. The answer is marked, and every one of them says why — an answer key you can only memorise is worth nothing in a viva.

  1. 01

    What does the expression [1, 2, 3] * 2 produce?

    • a[2, 4, 6]
    • b[1, 2, 3, 1, 2, 3]
    • c[[1,2,3], [1,2,3]]
    • dA TypeError

    Why — The * operator repeats a sequence rather than multiplying its contents. To multiply the elements you need a comprehension or NumPy — which is one reason NumPy is in the syllabus at all.

  2. 02

    Which of these cannot be used as a dictionary key?

    • aA string
    • bA tuple
    • cA list
    • dAn integer

    Why — Keys must be hashable, which in practice means immutable. A list can change after it is used as a key, so Python refuses it. A tuple of immutable values is fine.

  3. 03

    What is printed by: print(3 / 2, 3 // 2)

    • a1 1
    • b1.5 1
    • c1.5 1.5
    • d1 1.5

    Why — A single slash is true division and always gives a float; a double slash is floor division and discards the remainder. In Python 2 the single slash behaved like the double, which is why this is asked.

  4. 04

    A function defined as def add(item, items=[]) is dangerous because:

    • aLists cannot be default arguments
    • bThe same list is reused across every call
    • cIt will raise a TypeError
    • ditems shadows a built-in

    Why — The default is created once, when the function is defined, not on each call. The second call sees whatever the first call appended. Use None as the default and build the list inside.

  5. 05

    What does the 'with' statement do when opening a file?

    • aOpens it faster
    • bCloses it automatically, even if an exception is raised
    • cOpens it in read-write mode
    • dLoads the whole file into memory

    Why — It is a context manager: the file is closed when the block ends, whether it ended normally or through an exception. It is the reason try/finally around a file is rarely needed.

  6. 06

    Which clause of a try block runs whether or not an exception was raised?

    • aexcept
    • belse
    • cfinally
    • draise

    Why — finally always runs and is where cleanup belongs. else runs only when no exception was raised, which is the clause most answers forget to mention.

  7. 07

    Is Python call by value or call by reference?

    • aCall by value
    • bCall by reference
    • cCall by object reference
    • dIt depends on the Python version

    Why — A reference to the object is passed. Mutate a list inside a function and the caller sees it; rebind a name to a new integer and the caller does not. The phrase being tested is call by object reference.

  8. 08

    What is the output of: print(len({1, 2, 2, 3, 3, 3}))

    • a6
    • b3
    • c2
    • dA TypeError

    Why — Those curly brackets with no colons build a set, and a set discards duplicates. The same literal with key:value pairs would be a dictionary — a distinction worth being certain about in a viva.

Viva questions, and what a good answer sounds like

GNDU’s own scheme says the viva runs one-to-one beside the practical exam, about the code you are writing at that moment. These are the questions that get asked, and what the examiner is listening for in the reply.

“What is the difference between a list and a tuple, beyond the brackets?”

A list can be changed after creation, a tuple cannot. That immutability is why a tuple can be a dictionary key, and why passing one into a function guarantees it comes back unaltered.

“You wrote a loop. Could it be a comprehension?”

If the loop only builds a list from another sequence, yes, and the comprehension is usually clearer. If it does several things, or has a long body, the plain loop is the better code — knowing when not to use one is the real answer.

“What happens if you open a file that does not exist?”

A FileNotFoundError, which is a subclass of OSError. Catching it specifically rather than with a bare except is what the examiner is checking, because a bare except would also swallow a keyboard interrupt.

“Why does == sometimes agree with is and sometimes not?”

Because small integers and short strings are cached and reused by the interpreter, so two names happen to point at the same object. Create a larger value and the illusion breaks. Use == for values and is only for None.

“Show me what your program does with an empty input file.”

An honest answer walks the code: the loop body never runs, so whatever is being accumulated stays at its initial value — and if that is then divided by a count of zero, it raises ZeroDivisionError. Noticing that before being asked is the point.

“What is a module, and how is one of yours different from math?”

Any .py file is a module. math is part of the standard library and already on the path; yours is found because it sits beside the script being run. Importing it is identical in both cases.

Past the syllabus

Your paper stops somewhere, and a job interview does not. If you want the version of this subject that goes further than the scheme asks for, there is a full course for it.

CallWhatsAppFree demo