Syntax Recap — Python
14 topic(s) — definitions, syntax, and examples.
Definition
Python is dynamically typed. Variables are created upon assignment. Built-in numeric types include int, float, and complex. Conversion functions include int(), float(), str().
Purpose
Used for storing values, performing arithmetic operations, and parsing user inputs.
General Syntax
Example
Reads two numbers as strings from keyboard, casts them to integers with `int()`, and computes $m^n$ using exponent operator `**`.
Definition
Python supports arithmetic (+, -, *, /, //, %, **), relational (==, !=, <, >), logical (and, or, not), and assignment operators.
Purpose
Used for calculating mathematical series, evaluating truth conditions, and loop progression.
General Syntax
Example
Uses ternary condition and modulo operator inside a generator expression to compute alternating summation.
Definition
Conditional blocks execute specific branches of code based on boolean evaluation of expressions.
Purpose
Controls program execution paths based on runtime conditions and user input.
General Syntax
Example
Evaluates base condition `num <= 1` and uses a for-loop with if-condition to test divisibility.
Definition
Functions are reusable blocks of code defined using the `def` keyword that accept parameters and return values with `return`.
Purpose
Promotes modular code, reusability, and clean code separation.
General Syntax
Example
Defines parameterized function `is_even` returning a boolean based on remainder of division by 2.
Definition
Strings in Python are immutable sequences of Unicode characters with rich built-in manipulation methods like count(), replace(), find(), split(), join().
Purpose
Used for text processing, pattern replacement, and frequency analysis.
General Syntax
Example
Demonstrates counting character frequency, global character replacement, and single-occurrence removal.
Definition
The string `.find(sub, start)` or manual iteration with slicing `s[i:i+len(sub)]` finds all indices where a substring occurs.
Purpose
Used in text search engines, parsers, and string matching algorithms.
General Syntax
Example
Iteratively scans the main string with `.find()`, collecting all starting positions into a list or returning -1.
Definition
Dictionaries store unordered key-value pairs (`{key: value}`). Keys must be immutable and unique.
Purpose
Ideal for maintaining count distributions, lookup tables, and frequency histograms.
General Syntax
Example
Iterates over characters in a sentence, filters letters with `isalpha()`, and accumulates counts using `dict.get()`.
Definition
Tuples are immutable ordered collections defined with parentheses `(val1, val2)`. Supports indexing, slicing `[start:stop:step]`, and concatenation `+`.
Purpose
Used to store fixed record data, return multiple values from functions, and ensure data integrity.
General Syntax
Example
Demonstrates splitting a tuple into two halves using slice notation, tuple comprehension for even values, concatenation, and min/max.
Definition
Python handles files using the `open(filename, mode)` function and context managers (`with open(...) as f:`).
Purpose
Used for reading persistent datasets, writing logs, and filtering line-based data.
General Syntax
Example
Opens source and destination files safely using context manager and copies odd-numbered lines using `enumerate(..., start=1)`.
Definition
Exception handling catches runtime errors gracefully using `try`, `except`, `else`, and `finally` blocks.
Purpose
Prevents abrupt program crashes and provides meaningful error messages.
General Syntax
Example
Catches `ZeroDivisionError` when divisor is 0 and executes the `finally` cleanup block unconditionally.
Definition
Custom exceptions are created by subclassing Python's built-in `Exception` class and raised using the `raise` keyword.
Purpose
Allows developers to define domain-specific error types and enforce custom business validations.
General Syntax
Example
Defines custom `DuplicateNumberError` and raises it when a number is encountered more than once.
Definition
NumPy (Numerical Python) provides multidimensional array objects (`ndarray`), linear algebra routines, and fast vectorized operations.
Purpose
Essential for scientific computing, matrix mathematics, and data processing.
General Syntax
Example
Creates a matrix filled with 1s, reshapes 1D array of 6 elements into a 2x3 matrix, and calculates vector dot product.
Definition
Matplotlib is Python's standard plotting library. `matplotlib.pyplot` provides functions to create line plots, scatter plots, and customize axes.
Purpose
Used for visual data analysis, business metric presentation, and scientific charts.
General Syntax
Example
Plots monthly profits over 12 months with explicit X-axis ('Month Number') and Y-axis ('Total profit') labels.
Definition
NumPy generates continuous mathematical domains (`np.linspace`) and functions (`np.sin`, `np.cos`, `np.exp`), and Matplotlib renders multiple subplots.
Purpose
Used to visualize calculus, trigonometrics, polynomial modeling, and exponential growth.
General Syntax
Example
Generates 4 distinct subplots for Sine, Cosine, Polynomial ($x^3 - 4x$), and Exponential ($e^x$) curves using NumPy vectorization.