MCAN-101
Programming Concept with Python
MCA Sem-I | MAKAUT University
Comprehensive Exam Notes with PYQ Analysis
⭐ = Frequently asked in Previous Year Questions
UNIT 1: Fundamentals of Computer (6L)
1.1 History & Basic Anatomy of Computer
• A computer is an electronic device that processes data according to a set of instructions
(program)
• Generations: Vacuum Tubes → Transistors → ICs → Microprocessors → AI/Quantum
1.2 Basic Anatomy of Computer System
⭐ PYQ: Explain the basic computer architecture with a diagram. (2023 PYQ, 5 marks)
A computer has 5 main components:
Term Meaning
Input Unit Accepts data from user (keyboard, mouse, scanner)
Output Unit Displays/prints results (monitor, printer, speakers)
CPU Brain of computer — contains ALU and CU
ALU Arithmetic & Logic Unit — performs calculations and
comparisons
Memory Stores data and instructions (RAM, ROM, HDD, SSD)
1.3 Primary & Secondary Memory
⭐ PYQ: Explain the computer memory hierarchy. (2023 PYQ, 5 marks)
Memory Hierarchy (fastest to slowest):
• Registers → Cache → RAM (Primary) → HDD/SSD (Secondary) → Optical/Tape (Tertiary)
• Primary Memory: RAM (volatile, fast) and ROM (non-volatile, read-only)
• Secondary Memory: Hard Disk, SSD, Pen Drive — non-volatile, large capacity
💡 Tip: RAM loses data on power off. ROM retains data. This is a common 1-mark question.
1.4 Number Systems
⭐ PYQ: Write differences between 1's and 2's complements in the binary number system. (2023 PYQ)
⭐ PYQ: What do you mean by Packed and Unpacked BCD? Explain with examples. (2023 PYQ)
4 Number Systems you must know:
Term Meaning
Decimal Base 10, digits 0–9. Example: 25
Binary Base 2, digits 0 and 1. Example: 11001
Octal Base 8, digits 0–7. Example: 31
Hexadecimal Base 16, digits 0–9 and A–F. Example: 19
1's Complement vs 2's Complement
Term Meaning
1's Complement Flip all bits. Example: 1010 → 0101
2's Complement Flip all bits then add 1. Example: 1010 → 0101 + 1 = 0110
Use of 2's Complement Used to represent negative numbers in computers
BCD — Binary Coded Decimal
• Packed BCD: 2 decimal digits stored in 1 byte. Example: 25 → 0010 0101
• Unpacked BCD: 1 decimal digit per byte with upper nibble = 0. Example: 25 → 0000 0010, 0000
0101
💡 Tip: Packed BCD is more memory-efficient.
1.5 IEEE-754 Floating Point
⭐ PYQ: Explain IEEE-754 floating point representation for 32 bit numbers. (2023 PYQ)
Term Meaning
16-bit (Half) 1 sign + 5 exponent + 10 mantissa bits
32-bit (Single) 1 sign + 8 exponent + 23 mantissa bits
64-bit (Double) 1 sign + 11 exponent + 52 mantissa bits
• Sign bit: 0 = positive, 1 = negative
• Exponent is stored with a bias (127 for 32-bit)
• Mantissa stores the fractional part of the number
1.6 Assembly Language, Compiler, Assembler
Term Meaning
Machine Language Binary instructions (0s and 1s). Fastest but hardest to write.
Assembly Language Uses mnemonics like MOV, ADD. Converted by Assembler.
High Level Language Python, C, Java. Converted by Compiler or Interpreter.
Compiler Converts entire HLL program to machine code at once.
Assembler Converts assembly code to machine code.
Interpreter Translates and executes HLL line by line (Python uses this).
UNIT 2: Programming Basics (2L)
2.1 Problem Analysis & Flowcharts
⭐ PYQ: Draw a flowchart and write an algorithm for merge sort. (2023 PYQ, 10 marks)
⭐ PYQ: Write the pseudocode for binary search. (2023 PYQ)
⭐ PYQ: How to express switch-case statements using flowchart? (2022 PYQ)
⭐ PYQ: How to express subroutine calls using flowchart? (2022 PYQ)
Steps in Problem Solving:
• 1. Problem Analysis — understand what is asked
• 2. Algorithm — step-by-step solution in English
• 3. Flowchart — graphical representation
• 4. Code — write in Python
• 5. Test — verify with examples
2.2 Flowchart Symbols
⭐ PYQ: Draw the input and output symbol for a flowchart. (2023 PYQ)
Term Meaning
Oval (Terminator) Start / End of program
Rectangle (Process) Calculation or assignment (e.g., x = a + b)
Parallelogram (I/O) Input (read) or Output (print) operations
Diamond (Decision) Yes/No condition (if-else, while loop)
Arrow Flow direction
Circle (Connector) Connects different parts of flowchart
2.3 Algorithm & Pseudocode
Binary Search Algorithm
• Works on sorted list. Repeatedly divides search space in half.
Algorithm BinarySearch(arr, target):
low = 0, high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target: return mid
elif arr[mid] < target: low = mid + 1
else: high = mid - 1
return -1 # not found
Merge Sort Algorithm
• Divide array into halves, sort each half, then merge them
Algorithm MergeSort(arr):
if len(arr) <= 1: return arr
mid = len(arr) // 2
left = MergeSort(arr[:mid])
right = MergeSort(arr[mid:])
return Merge(left, right)
💡 Tip: Merge Sort has time complexity O(n log n). Binary Search is O(log n).
UNIT 3: Variables and Expressions (4L)
3.1 Variables in Python
⭐ PYQ: Explain the difference between left hand side and right hand side of assignment with an example. (2022
PYQ)
⭐ PYQ: How to create a string variable in Python? (2023 PYQ)
⭐ PYQ: Explain the case sensitivity of Python. How to take console input. (2022 PYQ)
⭐ PYQ: Mention the points which should be followed while choosing mnemonic variable names. (2022 PYQ)
Variables are containers that store values. Python is dynamically typed (no need to declare type).
name = 'Aritra' # string variable
age = 22 # integer variable
gpa = 8.5 # float variable
is_student = True # boolean variable
Rules for Variable Names (Mnemonic Names)
• Must start with a letter or underscore (_), NOT a digit
• Can contain letters, digits, and underscores
• Cannot use Python keywords (if, else, for, while, etc.)
• Python is case-sensitive: Name ≠ name ≠ NAME
• Use meaningful names: student_name is better than sn
💡 Tip: Python is case-sensitive. 'Age' and 'age' are two different variables.
3.2 LHS vs RHS of Assignment
In x = a + b:
• RHS (Right Hand Side): a + b is evaluated FIRST
• LHS (Left Hand Side): the result is then stored in x
x = 10 # 10 stored in x
x = x + 1 # RHS: 10+1=11 evaluated first, then stored in x
print(x) # Output: 11
3.3 Operators in Python
Term Meaning
Arithmetic + - * / // % ** (addition, subtraction, division, modulo, power)
Comparison == != > < >= <= (returns True or False)
Logical and, or, not
Assignment = += -= *= /=
Bitwise & | ^ ~ << >>
⭐ PYQ: Explain the use of modulus operator in python. (2022 PYQ)
print(10 % 3) # Output: 1 (remainder when 10 divided by 3)
print(17 % 5) # Output: 2
# Use: check even/odd: if n % 2 == 0 → even
3.4 Console Input/Output
⭐ PYQ: How to print different types of variables? (2022 PYQ)
name = input('Enter name: ') # input() always returns string
age = int(input('Enter age: ')) # convert to int
print('Name:', name, 'Age:', age)
print(f'Hello {name}, you are {age} years old') # f-string
UNIT 4: Control Statements and Iteration (5L)
4.1 if / elif / else
⭐ PYQ: Write the types of control statements in Python. (2023 PYQ)
marks = int(input('Enter marks: '))
if marks >= 90:
print('Grade A')
elif marks >= 75:
print('Grade B')
elif marks >= 60:
print('Grade C')
else:
print('Fail')
4.2 Loops in Python
⭐ PYQ: Differentiate while and for loop. (2022 PYQ)
⭐ PYQ: Explain different types of loops in python with examples. (2023 PYQ)
while loop — runs while condition is True
i = 1
while i <= 5:
print(i) # prints 1 to 5
i += 1
for loop — iterates over a sequence
for i in range(1, 6): # 1,2,3,4,5
print(i)
fruits = ['apple', 'mango', 'banana']
for fruit in fruits:
print(fruit)
Nested Loops
for i in range(1, 4): # outer loop
for j in range(1, 4): # inner loop
print(i * j, end=' ')
print()
break, continue, pass, else in loops
Term Meaning
break Exits the loop immediately
continue Skips current iteration, goes to next
pass Does nothing — placeholder
else (in loop) Runs after loop finishes normally (without break)
for i in range(10):
if i == 5: break # stops at 5
if i % 2 == 0: continue # skip even
print(i) # prints 1, 3
⭐ PYQ: Write a Python program to print the even numbers from a given list. (2023 PYQ)
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even = [n for n in numbers if n % 2 == 0]
print(even) # Output: [2, 4, 6, 8, 10]
UNIT 5: Collections (2L)
5.1 Strings
⭐ PYQ: How do we convert the string to lowercase? (2022 PYQ)
s = 'Hello World'
print([Link]()) # hello world
print([Link]()) # HELLO WORLD
print(s[0]) # H (indexing)
print(s[0:5]) # Hello (slicing)
print(len(s)) # 11
5.2 List
⭐ PYQ: What is the difference between list and tuple in Python? Explain with example. (2022 PYQ)
⭐ PYQ: How to remove values from a Python array? Explain with example. (2023 PYQ)
lst = [10, 20, 30, 40, 50]
[Link](60) # add at end
[Link](20) # remove by value
[Link](0) # remove by index (index 0 = 10)
[Link]() # sort ascending
print(lst[1]) # access element
5.3 Tuple
• Tuple is IMMUTABLE — cannot change after creation
• Faster than list, used for fixed data
t = (10, 20, 30)
print(t[0]) # 10
# t[0] = 99 # ERROR! tuples are immutable
5.4 Dictionary
student = {'name': 'Aritra', 'age': 22, 'gpa': 8.5}
print(student['name']) # Aritra
student['college'] = 'MAKAUT' # add new key
del student['age'] # delete key
for key, val in [Link](): print(key, ':', val)
5.5 Set
• Set stores UNIQUE, UNORDERED elements
s = {1, 2, 3, 2, 1}
print(s) # {1, 2, 3} — duplicates removed
[Link](4) # add element
[Link](2) # remove element
5.6 Sorting: Selection Sort & Bubble Sort
Bubble Sort — Compare adjacent elements, swap if out of order
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
print(bubble_sort([64, 34, 25, 12, 22])) # [12, 22, 25, 34, 64]
Selection Sort — Find minimum and put in position
def selection_sort(arr):
for i in range(len(arr)):
min_idx = i
for j in range(i+1, len(arr)):
if arr[j] < arr[min_idx]:
min_idx = j
arr[i], arr[min_idx] = arr[min_idx], arr[i]
return arr
UNIT 6: Functions (2L)
6.1 Built-in Functions
print(len([1,2,3])) # 3
print(max(5, 10, 3)) # 10
print(abs(-7)) # 7
print(type(3.14)) # <class 'float'>
print(range(1, 6)) # range(1, 6)
6.2 User Defined Functions
⭐ PYQ: How does a function return values? (2022 PYQ)
⭐ PYQ: What happens when a function doesn't have a return statement? Is this valid? (2023 PYQ)
⭐ PYQ: How to set a default value in a function? (2023 PYQ)
def greet(name, msg='Hello'): # default parameter
return f'{msg}, {name}!'
print(greet('Aritra')) # Hello, Aritra!
print(greet('Aritra', 'Hi')) # Hi, Aritra!
def no_return():
x = 5 # no return statement
# Returns None by default — this IS valid in Python
💡 Tip: A function without a return statement returns None. This is valid Python.
6.3 Recursive Functions
⭐ PYQ: Write a Python function to check whether a number falls in a given range. (2023 PYQ)
⭐ PYQ: Write a Python function that accepts a string and calculate the number of upper case and lower case
letters. (2023 PYQ)
# Check if number is in range
def in_range(num, start, end):
return start <= num <= end
print(in_range(5, 1, 10)) # True
# Count upper and lower case
def count_cases(s):
upper = sum(1 for c in s if [Link]())
lower = sum(1 for c in s if [Link]())
return upper, lower
u, l = count_cases('Hello World')
print(f'Upper: {u}, Lower: {l}') # Upper: 2, Lower: 8
# Factorial using recursion
def factorial(n):
if n == 0: return 1
return n * factorial(n - 1)
print(factorial(5)) # 120
UNIT 7: File Management (4L)
7.1 Opening & Closing Files
⭐ PYQ: How do you delete a file? (2022 PYQ)
⭐ PYQ: Write a short note on flush() function. (2023 PYQ)
⭐ PYQ: Differentiate between Absolute Pathnames and Relative Pathnames. (2023 PYQ)
⭐ PYQ: Differentiate write() and writelines(). (2023 PYQ)
Term Meaning
'r' Read mode (default). File must exist.
'w' Write mode. Creates file or overwrites existing.
'a' Append mode. Adds to end of file.
'r+' Read and Write mode.
# Open and read file
f = open('[Link]', 'r')
content = [Link]()
[Link]()
# Better: use 'with' (auto-closes file)
with open('[Link]', 'r') as f:
content = [Link]()
print(content)
7.2 Read/Write Methods
Term Meaning
read() Reads entire file as single string
readline() Reads one line at a time
readlines() Returns list of all lines
write(s) Writes string s to file
writelines(lst) Writes a list of strings to file
tell() Returns current cursor position (in bytes)
seek(n) Moves cursor to position n
flush() Forces write buffer to disk immediately (without closing)
⭐ PYQ: Write a program to count the words 'to' and 'the' present in a text file '[Link]'. (2023 PYQ)
with open('[Link]', 'r') as f:
content = [Link]().lower()
words = [Link]()
count_to = [Link]('to')
count_the = [Link]('the')
print(f"'to' count: {count_to}")
print(f"'the' count: {count_the}")
⭐ PYQ: Write a program to display all lines in a file '[Link]' along with line/record number. (2023 PYQ)
with open('[Link]', 'r') as f:
for num, line in enumerate(f, start=1):
print(f'Line {num}: {line}', end='')
7.3 Absolute vs Relative Pathnames
Term Meaning
Absolute Path Full path from root. Example: C:/Users/Aritra/[Link] or
/home/aritra/[Link]
Relative Path Path relative to current directory. Example: ./data/[Link] or
../[Link]
7.4 Deleting Files
import os
[Link]('[Link]') # delete file
[Link]('myfolder') # delete empty folder
[Link]('[Link]', '[Link]') # rename file
UNIT 8: Errors and Exception Handling (2L)
8.1 Types of Errors
⭐ PYQ: Differentiate error and exception. (2023 PYQ)
⭐ PYQ: What is Index Out Of Range Error? (2023 PYQ)
Term Meaning
Syntax Error Code structure is wrong. Detected before running. Example:
missing colon
Runtime Error (Exception) Occurs during execution. Example: dividing by zero
Logical Error Code runs but gives wrong output. Hardest to detect.
8.2 Common Exceptions
Term Meaning
ZeroDivisionError Division by zero
IndexError List index out of range
ValueError Wrong value type. Example: int('abc')
TypeError Wrong data type for operation
FileNotFoundError File doesn't exist when opening
KeyError Dictionary key doesn't exist
NameError Variable not defined
⭐ PYQ: What type of error will you receive for the statement int('23 bottles')? (2022 PYQ)
int('23 bottles') # Raises ValueError
# Cannot convert a non-numeric string to int
8.3 try / except / finally
try:
x = int(input('Enter number: '))
result = 100 / x
print('Result:', result)
except ZeroDivisionError:
print('Cannot divide by zero!')
except ValueError:
print('Please enter a valid number!')
except Exception as e:
print('Error:', e)
finally:
print('This always runs') # Cleanup code
💡 Tip: finally block always executes — used for closing files, releasing resources.
⭐ PYQ: What are standard input, output and error streams? (2023 PYQ)
Term Meaning
stdin Standard Input — keyboard ([Link])
stdout Standard Output — screen ([Link])
stderr Standard Error — error messages ([Link])
UNIT 9: Classes and Objects (5L)
9.1 Creating a Class
⭐ PYQ: Define package in Python. (2023 PYQ)
⭐ PYQ: Give one example of the use of __Init__() function. (2023 PYQ)
⭐ PYQ: How can we create a constructor in Python programming? (2022 PYQ)
⭐ PYQ: How do you copy an object in Python? Give example. (2022 PYQ)
⭐ PYQ: Does multiple inheritance supported in Python? Explain with example. (2022 PYQ)
class Student:
# Constructor
def __init__(self, name, age):
[Link] = name # instance variable
[Link] = age
# Method
def display(self):
print(f'Name: {[Link]}, Age: {[Link]}')
# Create object
s1 = Student('Aritra', 22)
[Link]() # Name: Aritra, Age: 22
💡 Tip: __init__() is the constructor. 'self' refers to the current object — always first parameter.
9.2 Inheritance
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
print('Animal speaks')
class Dog(Animal): # inherits from Animal
def speak(self): # override method
print(f'{[Link]} says Woof!')
d = Dog('Buddy')
[Link]() # Buddy says Woof!
Multiple Inheritance
class A:
def hello(self): print('Hello from A')
class B:
def hi(self): print('Hi from B')
class C(A, B): # multiple inheritance
pass
obj = C()
[Link]() # Hello from A
[Link]() # Hi from B
9.3 Copying an Object
import copy
s1 = Student('Aritra', 22)
s2 = [Link](s1) # shallow copy
s3 = [Link](s1) # deep copy
# Shallow: copies object but nested objects share reference
# Deep: copies everything independently
9.4 RegEx Module
⭐ PYQ: Write the output: [Link]('aa[cde]?', 'aacde aa aadcde') (2023 PYQ)
import re
result = [Link]('aa[cde]?', 'aacde aa aadcde')
print(result) # ['aac', 'aa', 'aad']
# Explanation:
# 'aa[cde]?' means 'aa' followed by optionally c, d, or e
# 'aac' found, 'aa ' found (space not in [cde] so just 'aa'), 'aad' found
UNIT 10: Modules & Packages (2L)
10.1 Modules
⭐ PYQ: Which keyword is used to raise an error in Python? (2023 PYQ)
• A module is a .py file containing Python code (functions, classes, variables)
# Importing a module
import math
print([Link](16)) # 4.0
print([Link]) # 3.14159...
# Import specific function
from math import sqrt, pi
print(sqrt(25)) # 5.0
# Import with alias
import numpy as np
# raise keyword — manually raise an error
raise ValueError('Invalid input!') # raises error
10.2 Packages
A package is a folder of modules with a special __init__.py file.
Term Meaning
Module A single .py file. Example: math, os, random
Package A directory with __init__.py and multiple modules. Example:
numpy, pandas
Library Collection of packages. Example: NumPy, Pandas, Matplotlib
💡 Tip: import gives access to the module. from...import gives access to specific items.
# Function aliases
from math import factorial as fact
print(fact(5)) # 120
UNIT 11: NumPy & Data Analysis (6L)
11.1 NumPy — Numerical Python
⭐ PYQ: Find the most frequent value in a NumPy array. (2022 PYQ)
⭐ PYQ: Compute the covariance matrix of two given NumPy arrays. (2022 PYQ)
⭐ PYQ: Write a program to replace NaN values with the average of columns. (2022 PYQ)
⭐ PYQ: Write a program to get the eigenvalues of a matrix. (2022 PYQ)
import numpy as np
# Create array
arr = [Link]([1, 2, 3, 4, 5])
print([Link]) # (5,)
print([Link]) # int64
# 2D array (matrix)
matrix = [Link]([[1, 2], [3, 4]])
print([Link]) # (2, 2)
Important NumPy Operations
import numpy as np
# Most frequent value
arr = [Link]([1, 2, 2, 3, 2, 4])
unique, counts = [Link](arr, return_counts=True)
most_frequent = unique[[Link](counts)]
print(most_frequent) # 2
# Eigenvalues
matrix = [Link]([[4, 2], [1, 3]])
eigenvalues = [Link](matrix)
print(eigenvalues) # [5. 2.]
# Covariance matrix
a = [Link]([1, 2, 3, 4])
b = [Link]([4, 3, 2, 1])
cov = [Link](a, b)
print(cov)
Replace NaN values
import numpy as np
arr = [Link]([[1, 2, [Link]], [4, [Link], 6], [7, 8, 9]])
# Replace NaN with column mean
col_means = [Link](arr, axis=0)
inds = [Link]([Link](arr))
arr[inds] = [Link](col_means, inds[1])
print(arr)
11.2 Pandas
import pandas as pd
# Read CSV file
df = pd.read_csv('[Link]')
# Basic info
print([Link]()) # first 5 rows
print([Link]()) # statistics
print([Link]) # rows, columns
print([Link]().sum()) # count missing values
# Data cleaning
[Link]([Link](), inplace=True) # fill NaN with mean
11.3 Matplotlib Plots
import [Link] as plt
# Line plot
x = [1, 2, 3, 4, 5]
y = [2, 4, 6, 8, 10]
[Link](x, y)
[Link]('Line Plot')
[Link]('X'); [Link]('Y')
[Link]()
# Bar chart
[Link](['A', 'B', 'C'], [10, 20, 15])
[Link]()
# Histogram
import numpy as np
data = [Link](1000)
[Link](data, bins=30)
[Link]()
QUICK REVISION: Most Important PYQ Answers
Define Iterator
An iterator is an object that can be iterated (looped) over. It implements __iter__() and __next__()
methods. Example: for x in [1,2,3] uses a list iterator.
Explain [Link](-3, 2)
seek(offset, from) moves file cursor. seek(-3, 2) means: go 3 bytes back from end of file. Arguments:
0=beginning, 1=current, 2=end.
Get Random Number Between 0 and 1
import random
print([Link]()) # e.g. 0.7342
>>> 17 = n / print(n) — What happens?
>>> 17 = n # SyntaxError! Cannot assign to literal
# LHS must be a variable, not a value
>>> minutes = 645 / hours = minutes // 60 / print(hours)
minutes = 645
hours = 645 // 60 # floor division = 10
print(hours) # Output: 10
M39048458N divisible by 8 & 11 — Find M and N
For divisibility by 8: last 3 digits (58N) must be divisible by 8. For divisibility by 11: alternating sum must
be divisible by 11. Working through the constraints: M=0, N=4.
Write output: [Link]('aa[cde]?', 'aacde aa aadcde')
import re
print([Link]('aa[cde]?', 'aacde aa aadcde'))
# Output: ['aac', 'aa', 'aad']
All the best for your MCAN-101 exam, Aritra! 🎯
MAKAUT MCA Sem-I | Programming Concept with Python