Core & Advanced Python 3.12 Programming Online Mock Test (Free 50-MCQ Topic Practice)
Select any course and syllabus topic below to launch a timed topic MCQ engineering exam (up to 2 free attempts per topic daily) with instant code-level explanations.
Timed code-output & architecture MCQs with instant scorecard. Want spoken viva practice too?
Select Any IT Course (21 Courses • 100% Topics Covered)
Core & Advanced Python 3.12 Programming — Topic-Wise Mock Tests
Expand any module below to start a live timed MCQ exam across 116 Mock Test sets (max 2 free attempts per topic per day).
All Modules & Topics in Core & Advanced Python 3.12 Programming
Introduction to Programming
Programming concepts, step-by-step algorithms, flowcharts, dry-running, and structured problem-solving
Python Introduction
Python history, readability philosophy (PEP 8 / Zen of Python), backend/API/automation/data applications, and...
Python Installation
Installing Python 3.12 on Windows (`PATH` & `py` launcher) and Linux (`apt`/`pyenv`), verifying `python3` and...
Environment Setup
Configuring VS Code (Python + Pylance + Ruff extensions), PyCharm, integrated terminal, and selecting the work...
Python Execution
Interactive REPL mode vs `.py` script mode, source -> bytecode (`.pyc` in `__pycache__`) -> Python Virtual Mac...
Python Syntax
4-space block indentation rules (PEP 8), logical vs physical lines, docstrings, and meaningful single-line `#`...
Variables
Dynamic variable binding, object references, `snake_case` naming rules, multiple assignment, and tuple swappin...
Data Types
Built-in scalar types (`int` arbitrary precision, `float` IEEE-754, `complex`, `bool`, `str`, `NoneType`) and...
Type Conversion
Implicit numeric promotion (`int` -> `float`) vs explicit constructors (`int()`, `float()`, `str()`, `bool()`)...
Input and Output
Reading console text via `input()`, `print()` (`sep`, `end`, `flush`), and formatted f-string numeric/alignmen...
Operators
Arithmetic (`+`, `-`, `*`, `/` true division, `//` floor division, `%` modulo, `**` power), comparison, logica...
Bitwise Operators
Bitwise AND (`&`), OR (`|`), XOR (`^`), NOT (`~`), left shift (`<<`), and right shift (`>>`) on integers
Membership Operators
`in` and `not in` across strings, lists, tuples, sets, and dictionary keys, plus `O(1)` `set` vs `O(n)` `list`...
Identity Operators
`is` and `is not`, `id()` memory address checks, singleton `None` checks (`x is None`), vs `==` value comparis...
Operator Precedence
Python evaluation order (`**`, unary `-`, `* / // %`, `+ -`, shifts, bitwise, comparisons, `not`, `and`, `or`)...
Conditional Statements
`if`, `elif`, `else` branching, mutually exclusive grade/slab ladders, and concise conditional expressions (`x...
Strings
Unicode UTF-8 string literals, raw strings `r"..."`, multiline strings, positive `0..n-1` and negative `-1..-n...
String Slicing
Slice notation `s[start:stop:step]`, omitting bounds, negative steps `s[::-1]` reversal, and out-of-range slic...
String Methods
`upper()`, `lower()`, `casefold()`, `strip()`/`lstrip()`/`rstrip()`, `removeprefix()`, `removesuffix()`, `spli...
String Searching
`find()` / `rfind()` (`-1` on miss) vs `index()` / `rindex()` (`ValueError` on miss) and non-overlapping `coun...
String Validation
`startswith()` (accepting a tuple of prefixes!), `endswith()`, `isdigit()`, `isalpha()`, `isalnum()`, and `iss...
String Formatting
Modern f-strings `f"{expr}"`, debug `f"{var=}"`, numeric formatting `:.2f`, `:,`, ISO dates, vs `.format()` te...
String Immutability
Why `str` objects cannot be mutated in-place, `O(n^2)` loop `+=` concatenation penalty vs `O(n)` `"".join(part...
Lists
Dynamic array internals of `list`, literal/constructor creation, indexing, slicing, slice assignment, and `len...
List Operations
`append()` (`O(1)` amortized), `extend()`, `insert(0, x)` (`O(n)` shift!), and `remove(val)` (`ValueError` if...
List Methods
`pop()` (`O(1)` tail vs `O(n)` index), `clear()`, in-place `sort(key=..., reverse=...)` vs non-mutating `sorte...
List Comprehension
`[expr for x in iterable if cond]`, conditional transformations, flattening 2D matrices, and readability limit...
Tuples
Immutable fixed-structure `tuple` records, single-element trailing comma `(42,)`, tuple packing/unpacking, and...
Tuple Methods
`.count(value)`, `.index(value)`, memory efficiency of tuples vs lists (`sys.getsizeof`), and immutability of...
Sets
Hash-table backed `set` and immutable `frozenset`, `set()` empty set creation (NOT `{}`!), `O(1)` membership a...
Set Operations
Union (`|` / `.union()`), intersection (`&` / `.intersection()`), difference (`-`), symmetric difference (`^`)...
Set Methods
`add()`, `update()`, `discard()` (no error if missing) vs `remove()` (`KeyError` if missing), and `pop()`
Dictionaries
Insertion-ordered hash map (`dict`, guaranteed since Python 3.7+), hashable keys, `O(1)` read/write/delete, an...
Dictionary Methods
`.keys()`, `.values()`, `.items()` dynamic views, `.get(k, default)`, `.pop(k, default)`, `.setdefault()`, and...
Functions
`def` declaration, docstrings (PEP 257), single-responsibility design, invocation, and implicit `None` return
Function Parameters
Positional arguments, keyword arguments, positional-only (`/`) and keyword-only (`*`) parameter markers
Default Parameters
Default parameter evaluation at `def` definition time (ONCE!) and the `None` sentinel pattern for mutable defa...
Variable Arguments
Variadic positional `*args` (packed as `tuple`), variadic keyword `**kwargs` (packed as `dict`), and call-site...
Return Statements
Early-return guard clauses, returning multiple values via tuple packing/unpacking, and consistent return types
Variable Scope (LEGB)
Local -> Enclosing -> Global -> Built-in (LEGB) name resolution, `global` vs `nonlocal`, and why mutable globa...
Lambda Functions
Single-expression anonymous `lambda params: expr` functions for inline sort keys and callbacks vs named `def`...
Recursion
Base case + progress toward base case, call stack frames, `sys.getrecursionlimit()` (~1000 in CPython, no tail...
Higher-Order Functions
First-class functions passed as arguments (strategy/validator callbacks) and returned from factory functions
map() Function
Lazy iterator `map(func, *iterables)` transformation vs list/generator comprehensions
filter() Function
Lazy predicate filtering `filter(pred, iterable)`, `filter(None, iterable)` truthy filtering, vs comprehension...
functools.reduce()
`functools.reduce(fn, iterable, initializer)` cumulative folding vs Pythonic built-ins (`sum`, `min`, `max`, `...
Python Modules
Creating reusable `.py` modules, module namespace isolation, `sys.modules` import cache, and avoiding circular...
Python Packages
Multi-directory package hierarchy (`banking/models/`, `banking/services/`), `__init__.py`, `__all__`, and expl...
Import System
Absolute imports (`from app.services.auth import verify`), explicit relative imports, `sys.path`, and why `fro...
Main Execution Guard (__name__)
How Python sets `__name__ == "__main__"` on direct execution vs module path on `import`, protecting CLI entryp...
Python Standard Library
Practical backend usage of `os`, `sys`, `math`, `random`/`secrets`, and timezone-aware `datetime` (`datetime.n...
Exception Handling
`try` and `except SpecificError as exc:` blocks, exception hierarchy (`BaseException` vs `Exception`), and pre...
OOP Introduction
Procedural vs object-oriented design, coupling data + behavior, and the 4 OOP pillars in Python backend archit...
Classes
`class` statement, `CapWords` (`PascalCase`) PEP 8 naming, class namespace dictionary (`__dict__`), and docstr...
Objects
Class instantiation `obj = ClassName(...)`, unique object identity (`id(obj)`), `isinstance()`, and attribute...
Constructors (__init__)
Object initialization via `__init__(self, ...)` (vs `__new__` allocator), validating invariants at constructio...
self Instance Reference
How Python binds `instance.method(x)` to `Class.method(instance, x)` and why explicit `self` is first paramete...
Instance Variables
Object-specific attributes bound on `self.attr` inside `__init__`, dynamic attribute storage in `obj.__dict__`
Class Variables
Class-level attributes shared across all instances (`company_name`, constants), lookup fallback `obj.__dict__`...
Instance Methods
Behavior operating on `self` state, mutator vs query methods, and calling sibling methods via `self.`
Class Methods (@classmethod)
`@classmethod` decorator, `cls` class binding (subclass-aware!), and named alternative constructors (`from_dic...
Static Methods (@staticmethod)
`@staticmethod` decorator for namespace-grouped pure helper functions requiring neither `self` nor `cls`
Encapsulation
Public attributes, `_protected` convention, `__private` name mangling (`_ClassName__attr`), and invariant prot...
Single Inheritance
Deriving specialized `class Sub(Base):` (`is-a` relationship), `super().__init__(...)`, and extending base beh...
Multiple Inheritance
Inheriting from multiple bases `class View(AuthMixin, AuditMixin, BaseView):` and cooperative `super()` mixin...
Multilevel Inheritance
Chained `GrandParent -> Parent -> Child` hierarchies (`Exception -> BankingError -> InsufficientFundsError`) a...
Hierarchical Inheritance
Multiple sibling subclasses (`SavingsAccount`, `CurrentAccount`, `SalaryAccount`) sharing one common parent (`...
Polymorphism and Duck Typing
Method overriding across subtypes and Pythonic duck typing ("if it implements `.send()`, treat it as a sender"...
Abstraction
Separating WHAT a repository/gateway contract promises from HOW PostgreSQL, Redis, or JSON files implement it
abc Module (Abstract Base Classes)
`from abc import ABC, abstractmethod`, preventing instantiation of incomplete subclasses at instantiation time
Iterables
Objects implementing `__iter__` (or sequence `__getitem__`), reusable multi-pass containers (`list`, `dict`) v...
Iterators
Stateful Iterator Protocol (`__iter__` returning `self` + `__next__` raising `StopIteration` when exhausted)
iter() and next()
Manual iteration via `it = iter(obj)` and `next(it, default)` sentinel handling without `StopIteration` crashe...
Generators (yield)
Generator functions pausing frame state at `yield`, `yield from` delegation, and `O(1)` memory streaming
Generator Expressions
Lazy `(expr for x in iterable if cond)` parenthesized expressions passed directly into `sum()`, `any()`, `all(...
Function Decorators
`@decorator` syntactic sugar (`fn = decorator(fn)`), preserving `__name__`/`__doc__` metadata with `@functools...
Nested Decorators
Parameterized decorator factories (`@retry(max_attempts=3)`) and bottom-up composition order of stacked `@d1`...
Closures
Lexical scope capture (`__closure__` cell objects) and late-binding loop variable pitfalls in closures
Custom Context Managers (__enter__ and __exit__)
Class-based context manager protocol (`__enter__` resource acquisition, `__exit__(exc_type, exc_val, tb)` clea...
contextlib (@contextmanager)
`from contextlib import contextmanager, suppress, ExitStack` generator-based context managers (`try: yield res...
Advanced Comprehensions
Set comprehensions `{...}`, dict comprehensions `{k: v ...}`, and nested comprehensions with filtering
Extended Iterable Unpacking
Starred target unpacking `first, *middle, last = seq`, nested tuple unpacking, and `{**d1, **d2}` / `[*a, *b]`...
Walrus Operator (:=)
Assignment expressions `if (m := pattern.search(line)):` and `while (chunk := f.read(8192)):` avoiding duplica...
Structural Pattern Matching (match and case)
Python 3.10+ `match subject:` with sequence, mapping (`case {"type": "paid", "amount": amt}:`), class, OR (`|`...
Type Hints and Annotations
PEP 484/585/604 modern Python 3.12 syntax (`list[str]`, `dict[str, int]`, `str | None`), return `-> None`, and...
typing Module (List, Dict, Optional, Union, Callable)
`Any` vs `object`, `Literal`, `TypedDict`, `Final`, `Collections.abc.Callable`, and legacy `Optional`/`Union`/...
Python Execution Model
Source parsing -> AST -> code objects -> bytecode evaluation loop on the Python Virtual Machine stack frame
CPython Runtime Architecture
CPython reference interpreter vs PyPy/Cython, C extension ABI, and why NumPy/psycopg release the GIL in C code
Python Bytecode Compilation (dis)
Inspecting stack-machine opcodes (`LOAD_FAST`, `BINARY_OP`, `RETURN_VALUE`), `.pyc` caching, and Python 3.11+...
Memory Allocation in Python
Private CPython heap, `PyObject` header (`ob_refcnt` + `ob_type`), `pymalloc` small-object arenas, and `tracem...
Reference Counting
Immediate deterministic deallocation when `ob_refcnt` drops to `0`, inspecting `sys.getrefcount()`, and strong...
Cyclic Garbage Collection (gc)
Why reference cycles (`a.peer = b; b.peer = a`) never hit refcount `0`, generational `gc` (Gen 0/1/2), and `gc...
Mutable Object References in Memory
Shared references across containers, in-place mutation (`+=` on `list` calls `__iadd__`) vs rebinding (`+=` on...
Shallow vs Deep Copying in Memory
Memory graph topology of alias (`=`), shallow copy (`copy.copy`), and deep copy (`copy.deepcopy`) on nested st...
Global Interpreter Lock (GIL)
What the CPython GIL protects, why CPU-bound Python bytecode runs 1 thread at a time per process, and why I/O...
Threading Fundamentals
OS threads inside a single shared-memory process, main thread vs daemon threads, and preemptive context switch...
Creating and Managing Threads
`threading.Thread(target=..., args=...)`, `.start()`, `.join(timeout=...)`, and collecting results via thread-...
Thread Synchronization (Lock and RLock)
Mutual exclusion with `threading.Lock()` (`with lock:`), re-entrant `RLock()` when a locked method calls anoth...
Race Conditions
Check-then-act (`if balance >= amt: balance -= amt`) and read-modify-write (`counter += 1` is multiple bytecod...
Deadlocks and Prevention
Circular lock wait (`Thread 1 locks A -> waits B`, `Thread 2 locks B -> waits A`) and prevention via canonical...
Thread Pools (ThreadPoolExecutor)
`from concurrent.futures import ThreadPoolExecutor, as_completed`, `executor.submit()`, `executor.map()`, `Fut...
Multiprocessing (Process-Based Parallelism)
Separate OS processes, separate Python heaps + separate GILs for true multi-core CPU parallelism, `spawn` vs `...
Software Testing Fundamentals
Arrange-Act-Assert (AAA) structure, deterministic repeatability (no sleep/network/clock flakiness!), and catch...
Testing Pyramid (Unit, Integration, Functional)
Fast pure-Python Unit tests (70%) + real-DB/API Integration tests (25%) + end-to-end smoke workflows (5%)
Test-Driven Development (TDD) Fundamentals
Red (write failing test specifying requirement) -> Green (minimal passing implementation) -> Refactor (clean u...
Python Built-In unittest Framework
`unittest.TestCase`, `setUp`/`tearDown`, `self.assertEqual`/`assertRaises`, and why Django’s `django.test.Test...
Pytest Setup, Configuration and Execution
Installing `pytest` + `pytest-asyncio` + `pytest-cov`, configuring `[tool.pytest.ini_options]` in `pyproject.t...
Writing Expressive Pytest Test Functions
Descriptive `test_<unit>_<scenario>_<expected>()` naming (`test_apply_job_when_already_applied_returns_409`),...
Assertions and Exception Checks (pytest.raises)
Rich `pytest` diffing on dicts/lists, `pytest.approx()` for floats, and `with pytest.raises(InsufficientFundsE...
Reusable Test State with Pytest Fixtures
`@pytest.fixture(scope="function" | "module" | "session")` in `conftest.py`, composable dependency injection,...
Version Control Fundamentals
Distributed Version Control (DVCS), auditability, blame history, safe experimentation, and team rollback guara...
Git Architecture (Working Directory, Staging, Repository)
Three-tree model: Working Tree -> Staging Area (`.git/index`) -> Local `.git/objects` DAG (`blob`, `tree`, `co...
Git Installation and Configuration
`git config --global user.name`, `user.email`, `init.defaultBranch main`, `core.autocrlf` (Windows `true` vs L...
git init (Repository Initialization)
Initializing `.git` at project root, verifying repository boundaries, and immediate `.gitignore` creation befo...
git status (Inspecting Working Tree)
Interpreting untracked, unstaged, staged, ahead/behind remote tracking indicators before every commit
git add (Staging Changes)
Explicit file staging `git add src/models.py`, interactive hunk staging `git add -p`, and unstaging via `git r...
Want Unlimited PYTH Mock Exams + Weekend Live Mentorship With Working IT Pros?
Train live on weekends with active Working IT Professionals • All-Inclusive Fee: $21 USD All-Incl. (Includes 30-Day 100% Upgrade Credit)
Frequently Asked Questions — Topic-Wise Mock Tests
Are Core & Advanced Python Topic Mock Tests free on MockAttempt Tech Academy?
Yes! Visitors can attempt up to 2 free timed 50-MCQ Core & Advanced Python 3.12 Programming Mock Tests per topic daily across 116 topics with instant answers. Enrolled live-batch students (₹1,999 All-Inclusive) unlock unlimited daily attempts.
Can I also practice Spoken AI Interviews for Core & Advanced Python?
Yes — every Core & Advanced Python 3.12 Programming topic also includes up to 2 free daily Spoken MockAttempt AI Technical Interviews (https://mockattempt.com/ai-interviews/course/python-programming-training) with 4-axis voice evaluation.