Programming in Python
Comprehensive exam revision notes for BCA-202N Unit 2 (Operators, Expressions & Creating Python Programs). Includes Section A (2M), Section B (5M), and Section C (15M) questions, answers, and diagrams.
Programming in Python
Operators, Expressions & Creating Python Programs
Core Definitions & Key Concepts
What is the difference between / and // operators in Python
/ is True Division, always returning a float (e.g., 7 / 2 = 3.5). // is Floor Division, returning the greatest integer less than or equal to the quotient (e.g., 7 // 2 = 3, -7 // 2 = -4).
What does the exponentiation operator ** do
** raises the left operand to the power of the right operand: e.g., 2 ** 3 = 8 and 16 ** 0.5 = 4.0.
== and is in Python
== tests value equality (whether both objects hold identical data). is tests identity equality (whether both variables point to the exact same memory address, id(a) == id(b)).
Membership operators in and not in
Membership operators test whether a specified element is present in a collection (string, list, tuple, dictionary, set): e.g., 'a' in 'apple' yields True.
What are bitwise operators in Python
Bitwise operators work directly on binary bits: & (AND), | (OR), ^ (XOR), ~ (Bitwise NOT / inversion), << (Left shift), >> (Right shift).
Short-circuit evaluation in Python logical operators
In a and b, if a is False, b is not evaluated (result is False). In a or b, if a is True, b is not evaluated (result is True).
What is the ternary conditional expression in Python
Syntax: val_if_true if condition else val_if_false
Example: status = 'Adult' if age >= 18 else 'Minor'.
What does the pass statement do in Python
pass is a null statement used as a syntactic placeholder where code is syntactically required but no action is needed (e.g., empty function or class stub).
Conceptual & Architectural Analysis
Operator Precedence and Associativity in Python with a Hierarchy Table
Operator Precedence (Highest to Lowest)
| Level | Operators | Description | Associativity | |
|---|---|---|---|---|
| 1 | () | Parentheses (grouping) | Left to Right | |
| 2 | ** | Exponentiation | Right to Left | |
| 3 | +x, -x, ~x | Unary plus, minus, bitwise NOT | Right to Left | |
| 4 | *, /, //, % | Multiplication, division, floor div, modulo | Left to Right | |
| 5 | +, - | Addition, Subtraction | Left to Right | |
| 6 | <<, >> | Bitwise Shifts | Left to Right | |
| 7 | & | Bitwise AND | Left to Right | |
| 8 | ^ | Bitwise XOR | Left to Right | |
| 9 | ` | ` | Bitwise OR | Left to Right |
| 10 | ==, !=, <, >, is, in | Comparisons, Identity, Membership | Left to Right | |
| 11 | not | Logical NOT | Right to Left | |
| 12 | and | Logical AND | Left to Right | |
| 13 | or | Logical OR | Left to Right | |
| 14 | =, +=, -=, etc. | Assignment operators | Right to Left |
Python List Comprehensions with Syntax, Performance, and Practical Examples
List Comprehensions
List comprehension provides a concise syntax to create new lists based on existing iterables.
Syntax: [expression for item in iterable if condition]
1# 1. Squares of even numbers from 1 to 202even_squares = [x**2 for x in range(1, 21) if x % 2 == 0]3print("Even Squares:", even_squares)4
5# 2. String manipulation: uppercase words6words = ["mjpru", "bca", "python", "exam"]7uppercase = [w.upper() for w in words if len(w) > 3]8print("Filtered Uppercase:", uppercase)Performance Advantage: List comprehensions run at C-speed inside the Python interpreter, substantially outperforming traditional for loops with .append() calls.
Dictionary and Set Comprehensions with Code Examples
Dictionary and Set Comprehensions
- Dict Comprehension:
{key_expr: val_expr for item in iterable if condition} - Set Comprehension:
{expr for item in iterable if condition}
1# Dictionary of number to its cube2cubes_dict = {n: n**3 for n in range(1, 6)}3print("Cubes:", cubes_dict) # {1: 1, 2: 8, 3: 27, 4: 64, 5: 125}4
5# Inverting a dictionary (swapping key and value)6original = {"a": 1, "b": 2, "c": 3}7inverted = {v: k for k, v in original.items()}8print("Inverted:", inverted) # {1: 'a', 2: 'b', 3: 'c'}9
10# Set comprehension (unique word lengths)11sentence = "Python is an interpreted elegant programming language"12word_lengths = {len(word) for word in sentence.split()}13print("Word Lengths:", word_lengths)How Python Internally Implements Integer Caching (Small Integer Optimization)
Python pre-allocates and caches small integers in the range `[-5, 256]` during interpreter startup in CPython.
- Any assignment to an integer within
[-5, 256]reuses the existing cached memory address. - Integers outside this range instantiate brand-new object instances in memory:
1a = 2502b = 2503print(a is b) # True (Both point to identical cached CPython object)4
5x = 10006y = 10007print(x is y) # False (Distinct heap allocations, though x == y is True)In-Depth Analysis & Implementation
Write a Complete Menu-Driven Program in Python Demonstrating Arithmetic, Bitwise, Logical, and Relational Operators
"""
MJPRU Bareilly BCA Examination Model Program: Unit 2
Menu-Driven Demonstration of All Major Python Operators
"""
def show_arithmetic(a, b):
print("\n--- Arithmetic Operations ---")
print(f"{a} + {b} = {a + b}")
print(f"{a} - {b} = {a - b}")
print(f"{a} * {b} = {a * b}")
print(f"{a} / {b} = {a / b:.4f} (True Float Division)")
print(f"{a} // {b} = {a // b} (Floor Division)")
print(f"{a} % {b} = {a % b} (Remainder/Modulo)")
print(f"{a} ** {b} = {a ** b} (Power)")
def show_bitwise(a, b):
print("\n--- Bitwise Operations (Integer Level) ---")
print(f"{a} & {b} = {a & b} (Binary: {bin(a & b)})")
print(f"{a} | {b} = {a | b} (Binary: {bin(a | b)})")
print(f"{a} ^ {b} = {a ^ b} (Binary: {bin(a ^ b)})")
print(f"~{a} = {~a} (Inversion)")
print(f"{a} << 1 = {a << 1} (Left Shift - Multiplies by 2)")
print(f"{a} >> 1 = {a >> 1} (Right Shift - Divides by 2)")
def main():
print("="*50)
print(" PYTHON OPERATORS COMPREHENSIVE SUITE")
print("="*50)
num1 = int(input("Enter first integer (a): "))
num2 = int(input("Enter second integer (b): "))
show_arithmetic(num1, num2)
show_bitwise(num1, num2)
if __name__ == "__main__":
main()String Slicing, Methods, and Immutability in Python with Full Code
String Slicing and Manipulation Guide
Strings in Python are immutable sequences of Unicode characters.
Slicing Syntax: string[start : stop : step]
1text = "MJPRU University Bareilly"2
3# 1. Slicing Demonstrations4print("Substring [0:5]:", text[0:5]) # 'MJPRU'5print("Step slicing [::2]:", text[::2]) # Every 2nd char6print("Reverse string [::-1]:", text[::-1]) # 'yllieraB ytisrevinU URPJM'7
8# 2. Key String Methods9print("Lower:", text.lower())10print("Title Case:", text.title())11print("Count 'i':", text.count('i'))12print("Find 'Univ':", text.find('University')) # Returns index 613print("Replace:", text.replace("Bareilly", "Uttar Pradesh"))14
15# 3. Splitting and Joining16tokens = text.split(" ")17print("Tokens:", tokens)18joined = "-".join(tokens)19print("Joined:", joined)20
21# 4. Immutability Proof22try:23 text[0] = 'K' # TypeError: 'str' object does not support item assignment24except TypeError as e:25 print("\nProof of Immutability Caught:", e)Write a Program to Solve the Matrix Multiplication Problem in Python using Nested Lists and List Comprehensions
1# Matrix Multiplication in Python without External Libraries2
3def multiply_matrices(A, B):4 # A is m x k, B is k x n5 rows_A = len(A)6 cols_A = len(A[0])7 rows_B = len(B)8 cols_B = len(B[0])9 10 if cols_A != rows_B:11 raise ValueError("Matrix multiplication impossible: cols of A must equal rows of B!")12 13 # Method 1: Traditional nested loops14 result = [[0 for _ in range(cols_B)] for _ in range(rows_A)]15 for i in range(rows_A):16 for j in range(cols_B):17 for k in range(cols_A):18 result[i][j] += A[i][k] * B[k][j]19 return result20
21# Test Matrices22mat1 = [23 [1, 2, 3],24 [4, 5, 6]25] # 2x326
27mat2 = [28 [7, 8],29 [9, 1],30 [2, 3]31] # 3x232
33prod = multiply_matrices(mat1, mat2)34print("Product Matrix (2x2):")35for row in prod:36 print(" ", row)37# Output:38# [31, 19]39# [85, 55]Important Exam Points & Quick Revision
Practice // vs /, is vs ==, bitwise operations, and list comprehension syntax; these are regular university exam targets.
100% left on this page — finishing it closes the gap for Operators, Expressions & Creating Python Programs.
Operators, Expressions & Creating Python Programs still counts as a weak topic until you finish this note and answer its questions.
Practise this unitTest Your Understanding
Now that you've read through these notes, practice unit MCQs to identify weak points and solidify your learning before exams.