Python Program to Count Vowels and Consonants in a Text File
To count vowels and consonants in a Python text file, open the file in read mode (`'r'`), load its text using `read()`, and iterate character by character....
Verified Python scripts, File Handling, Stacks, MySQL queries, Pandas DataFrames & Computer Networks 5-mark case studies.
To count vowels and consonants in a Python text file, open the file in read mode (`'r'`), load its text using `read()`, and iterate character by character....
To count lines starting with a specific letter such as `'A'` in a Python text file, open the file in `'r'` mode and iterate through its lines. Skip blank l...
To count occurrences of `'Me'` and `'My'` in a text file for CBSE Class 12 CS (083), read the file, split the text into words with `split()`, strip surroun...
To read a text file line by line and display each word separated by `#` (classic CBSE 083 question), open the file in `'r'` mode, iterate over every line, ...
To display words shorter than 4 characters from a text file in Python, open the file in `'r'` mode, read its contents with `read()` or line iteration, and ...
To find the longest line in a Python text file, iterate over the opened file object or `readlines()`, strip trailing newline characters with `rstrip("\n")`...
To count uppercase letters, lowercase letters, and digits in a Python text file, open the file in `"r"` mode, iterate character by character over the conte...
To copy lines excluding a specific character or starting vowel into a new Python file, open the source file in `"r"` mode and the destination file in `"w"`...
To build a word frequency dictionary from a text file in Python, open the file with `with open(..., "r")`, read each line, split whitespace, normalize word...
In Python file handling, `tell()` returns the file pointer's current byte offset from the start, while `seek(offset, whence=0)` repositions it (`0` = start...
In CBSE Class 12 Computer Science (083), Python's `pickle` module stores structured objects like lists and dictionaries in binary files using serialization...
To search a binary file by roll number in CBSE CS 083, open the `.dat` file in `'rb'` mode, initialize `found = False`, and read each pickled record sequen...
To update a record in a binary file with `seek()` and `pickle`, open the file in `'rb+'` mode and save `pos = f.tell()` **before** every `pickle.load(f)` c...
Python binary files cannot erase bytes from the middle directly, so deleting a record safely requires the two-file copy-and-replace pattern. Open the sourc...
To copy records scoring above 75% from one binary file to another in CBSE CS 083, open the source `.dat` file in `'rb'` mode and the destination `.dat` fil...
To read and write Comma-Separated Values (CSV) files cleanly in Python for CBSE Class 12 (083), import the built-in `csv` module and always pass `newline='...
To search or filter employee records in a CSV file for CBSE Class 12 (083), open the file with `newline=''`, wrap it in `csv.reader()`, skip the header via...
`csv.DictReader(file)` reads the first row of a CSV file automatically as dictionary keys and yields each subsequent record as a `dict` mapping column head...
An absolute file path specifies the complete location starting from the root or drive letter (e.g., `r'C:\Data\marks.txt'` or `'/home/data/marks.txt'`), wh...
`pickle.load(file)` reads exactly one serialized Python object per call and raises `EOFError` when it hits the end of a binary file. Because binary files o...
A stack in CBSE Class 12 Computer Science (083) is a linear data structure following the Last-In, First-Out (LIFO) principle, where insertions and deletion...
To push even numbers from a Python list into a stack and pop them all, iterate through the source list and check `num % 2 == 0`. Whenever true, call `stack...
In CBSE 083 dictionary-to-stack problems, you traverse `emp_dict.items()` (or iterate keys) and test `salary > 50000` strictly using `>` rather than `>=`. ...
CBSE 083 Previous Year Questions (PYQs) frequently test stacks holding multi-field recordsβsuch as `[Book_No, Book_Title, Price]` or `[Room_No, Customer_Na...
A stack reverses data naturally because Last-In, First-Out (LIFO) outputs items in the exact opposite order they were pushed. To reverse a string's charact...
To check balanced brackets in Python, initialize an empty list as a LIFO stack and scan the expression left to right. Push every opening bracket `(`, `{`, ...
A stack is a linear data structure operating on the Last-In, First-Out (LIFO) rule, where insertion (`push`) and deletion (`pop`) occur strictly at one end...
To push only vowel-free words into a Python stack (a classic CBSE Class 12 CS 3-mark PYQ), iterate through each word in the input list, convert it to lower...
In CBSE Class 12 CS (083) dictionary-stack PYQs, `Push_element()` iterates over `dict.items()` (or keys) and pushes only keys whose mapped value satisfies ...
To score full marks on CBSE Class 12 CS (083) 3-mark stack dry-run questions, draw a 4-column trace table with `Step / Input`, `Operation`, `Stack State (B...
In Python, arguments are passed by object reference, meaning the parameter receives a reference to the caller's object rather than a separate copy. When an...
Python resolves variable names using the LEGB rule: Local, Enclosing, Global, and Built-in. Inside a function, reading a global variable works automaticall...
In Python function definitions, non-default parameters must precede all default parameters, otherwise Python raises a SyntaxError at compile time. During a...
Python evaluates default parameter expressions once when the def statement is executed, not each time the function is called. When you write def add_item(v...
A Python function can return only one object, yet writing return a, b, c automatically packs those comma-separated expressions into a single tuple (a, b, c...
Python executes top-level module statements sequentially from line 1, skipping function bodies defined with `def` until a call occurs. When a function is i...
In Python, `sorted(iterable, key=...)` and `list.sort(key=...)` pass each element through the `key` function once to compute a comparison proxy without mod...
Python executes the `try` suite first. If an exception occurs, the remaining lines in `try` are skipped and the first matching `except` block runs; `else` ...
Use `raise ExceptionType('message')` to explicitly trigger built-in errors like `ZeroDivisionError` or `ValueError` when business or input rules fail, and ...
In CBSE 083 probable-output questions, `random.randint(a, b)` returns an integer `N` with BOTH endpoints included (`a <= N <= b`), whereas `random.randrang...
Python string slicing uses `s[start:stop:step]`, where `start` is inclusive and `stop` is exclusive. When `step` is negative, Python walks right-to-left: o...
`split()` breaks a string at every separator occurrence (or consecutive whitespace by default) and returns a `list` of substrings without keeping the separ...
Assigning `b = a` creates an aliasβboth variables point to the same list object (`id(a) == id(b)`), so mutating `b` via `append()`, `pop()`, or index assig...
`append(x)` adds `x` as a single element at the end (increasing `len` by 1, even if `x` is a list), whereas `extend(iter)` unpacks each item of an iterable...
A Python tuple is immutable at its top levelβyou cannot reassign `t[i] = val` or append slotsβbecause it stores fixed object references. However, if a tupl...
In Python, dictionaries store insertion-ordered key-value pairs accessed in O(1) average time. Traverse keys with `for k in d` or unpack keys and values to...
To count character or word frequencies in Python without external modules, initialize an empty dictionary `freq = {}` and iterate through each character or...
In Python nested loops, the outer loop sets the row index while the inner loop completes all its iterations for every single outer step. Inside an inner lo...
Iterative binary search locates a target in a sorted list by maintaining `low = 0` and `high = len(arr) - 1`, looping `while low <= high:`. Each iteration ...
Bubble Sort repeatedly compares adjacent pairs `arr[j]` and `arr[j + 1]`, swapping out-of-order elements so the largest remaining value bubbles to the end ...
In CBSE Class 12 Computer Science (083) SQL, `SELECT` retrieves chosen columns while `WHERE` filters rows before output using relational or logical conditi...
SQL's `LIKE` operator performs string pattern matching inside `WHERE` clauses using two standard wildcards: `%` matches zero, one, or any sequence of chara...
In SQL, `NULL` represents a missing, unknown, or inapplicable valueβnever numeric `0` or an empty string `''`. Because `NULL` is not a concrete value, `col...
`SELECT DISTINCT` eliminates duplicate rows from query output, treating multiple `NULL` values in a column as one distinct entry; when multiple columns fol...
`COUNT(*)` counts every row in a table or group, including rows containing `NULL` values in one or more columns. By contrast, `COUNT(column_name)` ignores ...
In SQL, the WHERE clause filters individual rows from a table before any grouping takes place, and it cannot evaluate aggregate functions like COUNT(), SUM...
SQL aggregate functionsβSUM(), AVG(), MAX(), MIN(), and COUNT()βcollapse multiple rows inside each GROUP BY bucket into one summary value per group. SUM() ...
Data Definition Language (DDL) commandsβCREATE, ALTER, DROP, and TRUNCATEβdefine or modify a database's structural schema, including tables, columns, and c...
ALTER TABLE is a DDL command that modifies an existing table's structure without recreating it from scratch. Use ADD to insert a new column or constraint, ...
UPDATE ... SET modifies existing column values in selected rows without removing records. DELETE FROM removes specific rows matching a WHERE filter (or all...
In CBSE Class 12 SQL, an Equi-Join matches rows across two tables using an explicit equality condition (`=`) and retains every column from both tables, so ...
In SQL and relational algebra, the Cartesian Product (`CROSS JOIN` or comma-separated `FROM R, S` without a `WHERE` filter) pairs every row of table `R` wi...
In a relational table, every minimal attribute or attribute set that uniquely identifies each tuple is a Candidate Key. From the Candidate Keys, the databa...
In the relational model, a table is called a **Relation**, each column is an **Attribute**, each row is a **Tuple**, and the pool of permitted values for a...
SQL constraints enforce data integrity rules directly inside `CREATE TABLE` or `ALTER TABLE`. `NOT NULL` forbids missing values, `UNIQUE` forbids duplicate...
In CBSE Class 12 Computer Science 4-mark case studies, Student and Stream tables typically link through a foreign key such as StreamID. Use an equi-join wi...
Teacher and Department board questions combine single-table filtering with two-table equi-joins via DeptCode. Use WHERE for row-level criteria like HireDat...
Doctor and Patient SQL case studies test your ability to trace exact output rows across equi-joins, NATURAL JOIN, and aggregate queries linked by DocID. Be...
Product and Supplier inventory case studies link stock items to vendor cities via SupID. Compute total inventory worth per item using Price * Qty AS StockV...
Flight and Passenger SQL questions join route schedules with booking records using FlightNo. Filter routes by Origin and Destination using exact string lit...
Python connects to a MySQL server using the `mysql.connector` module through a four-step pipeline: establish a connection object via `mysql.connector.conne...
After executing a `SELECT` query, `fetchone()` retrieves the next single row as a tuple (or `None` when exhausted), `fetchmany(size)` returns a list of at ...
In Python's `mysql.connector`, `autocommit` is `False` by default, so Data Manipulation Language (DML) commands like `INSERT`, `UPDATE`, and `DELETE` run i...
Parameterized queries pass SQL structure and user data separately via `cur.execute(query, params)`, using `%s` as the placeholder token inside `mysql.conne...
MySQL string functions use 1-based indexing (the first character is position `1`, never `0`). `LEFT(str, n)` extracts the first `n` characters from the sta...
In MySQL, single-row string functions inspect or transform character values one record at a time. `INSTR(str, substr)` returns the 1-based starting index o...
MySQL math functions compute numeric transformations directly inside `SELECT` and `WHERE` clauses. `ROUND(n, d)` rounds `n` to `d` decimal places, or to th...
MySQL stores dates in standard `YYYY-MM-DD` format and provides single-row date functions to extract calendar components or read the current timestamp. `YE...
A SQL subquery is a `SELECT` statement nested inside parentheses within an outer query's `WHERE`, `FROM`, or `HAVING` clause. Single-row subqueries return ...
CBSE Class 12 IP 065 board exams routinely test single-row SQL functions in 1-to-3-mark output prediction questions. To solve them accurately, evaluate nes...
Network topology defines the physical and logical layout of connected devices and transmission links. For N nodes, Bus uses 1 shared backbone with terminat...
Computer networks are classified by geographical span into four tiers: PAN covers up to 10 meters around one person via Bluetooth or USB; LAN spans a room,...
Each networking device operates at a specific layer and solves a distinct problem: a Repeater regenerates weakened signals beyond 100 m; a Hub broadcasts i...
In CBSE Class 12 CS (083) 5-mark case studies, place the central server in the building housing the maximum number of computers (applying the 80-20 traffic...
To design the most economical cable layout in CBSE Class 12 CS (083) case studies, compute a Minimum Spanning Tree (connecting all buildings with the small...
Guided transmission media confine signals inside physical conductors across three main cable families: twisted pair, coaxial, and optical fiber. Twisted pa...
Unguided media broadcast electromagnetic waves through air or vacuum without physical cables. Radio waves (3 kHz to 1 GHz) travel omnidirectionally and pen...
Circuit switching establishes a dedicated, continuous physical path between sender and receiver before data flows, guaranteeing constant delay while wastin...
Application-layer protocols standardize how network software exchanges web pages, files, and email over TCP ports. HTTP (port 80) fetches stateless web res...
Modern internet sessions rely on four interlocking mechanisms: VoIP digitizes voice into UDP/RTP packets for real-time calling, DNS translates human domain...
A Pandas `Series` is a one-dimensional labeled array created with `pandas.Series(data, index=...)` that stores homogeneous or mixed values alongside an exp...
Pandas `Series` performs vectorized arithmetic element-by-element across aligned index labels without explicit loops, returning `NaN` wherever a label appe...
A Pandas `DataFrame` is a two-dimensional, size-mutable tabular structure with labeled rows (`index`) and labeled columns (`columns`). Passing a dictionary...
DataFrame attributes inspect structural metadata directly without parentheses. `df.shape` returns a `(rows, columns)` tuple, while `df.size` returns the to...
In Pandas, `.loc[row_label, col_label]` selects DataFrame rows and columns using explicit axis labels, whereas `.iloc[row_pos, col_pos]` selects strictly b...
Boolean indexing in Pandas selects DataFrame rows where a logical condition evaluates to `True`, producing a filtered subset without mutating the original ...
In Pandas, add or update a column with `df['Total'] = df['P'] + df['C']`, and append or modify a row using `df.loc[label] = values`. Rename headers or row ...
Pandas represents missing values as `NaN` (`np.nan`) or `None`. Detect missing entries with `df.isnull()` (boolean mask) and count them per column via `df....
In Pandas, `pd.read_csv(filepath)` imports tabular text into a DataFrame while `df.to_csv(filepath)` exports it back to disk. Key import parameters in CBSE...
CBSE Class 12 IP (065) output-prediction PYQs test exact DataFrame indexing, aggregation, and reshaping rules. Remember that `df.loc[a:b]` includes both en...
In Matplotlib (`matplotlib.pyplot`), `plt.plot(x, y, color, marker, linestyle, linewidth, label)` draws a line chart connecting ordered data points to show...
In Matplotlib, `plt.bar(x, height, width=0.8)` draws vertical rectangular bars to compare discrete categories, whereas `plt.barh(y, width, height=0.8)` ren...
A histogram created via `plt.hist(data, bins=10)` groups continuous numerical observations into contiguous intervals called bins and plots the frequency co...
Phishing deceives victims via forged emails or lookalike websites to steal passwords and OTPs. Ransomware encrypts user files and demands payment for the d...
A digital footprint is the permanent trail of data left behind whenever a user interacts online. An active digital footprint consists of information shared...
Free and Open Source Software (FOSS) grants users four core freedoms: running, studying, modifying, and redistributing source code, unlike proprietary soft...
Intellectual Property Rights (IPR) safeguard intangible creations of the human intellect through three distinct legal instruments in India. Copyright autom...
The Information Technology Act, 2000 (amended in 2008) is India's primary cyber law governing electronic contracts, digital signatures, and computer crimes...
Electronic waste (e-waste) consists of discarded electrical and computing hardware containing hazardous substances like lead, mercury, cadmium, and bromina...
CBSE Computer Science (083) and Informatics Practices (065) are both 100-mark subjects (70 theory + 30 practical) sharing Python and SQL fundamentals, yet ...
Book a free 60-minute diagnostic trial with IIT/NIT specialist mentors.