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

varName = value castVal = int(strVal)

Example

m = int(input('Enter m: ')) n = int(input('Enter n: ')) result = m ** n print(f'{m}^{n} = {result}')

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

power = base ** exp mod = val % 2 sum_val += (-1)**(i+1) * i

Example

# Alternating series: 1 - 2 + 3 - 4 + 5 - ... + n n = 10 total = sum(i if i % 2 != 0 else -i for i in range(1, n + 1)) print('Series Sum:', total)

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

if condition1: # code block elif condition2: # code block else: # default code

Example

def is_prime(num): if num <= 1: return False for i in range(2, int(num**0.5) + 1): if num % i == 0: return False return True print(is_prime(17)) # True

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

def function_name(param1, param2=default): # statements return result

Example

def is_even(num): '''Returns True if number is even, False if odd.''' return num % 2 == 0 print('Is 14 even?', is_even(14)) # True print('Is 19 even?', is_even(19)) # False

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

freq = s.count(ch) s_new = s.replace(old, new, max_count) idx = s.find(sub)

Example

text = 'banana' print('Count of a:', text.count('a')) # 3 print('Replace a with o:', text.replace('a', 'o')) # 'bonono' print('Remove 1st a:', text.replace('a', '', 1)) # 'bnana'

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

def find_all(main_str, sub_str): # search loop return indices_list

Example

def find_all_occurrences(main_s, sub_s): indices = [] start = 0 while True: idx = main_s.find(sub_s, start) if idx == -1: break indices.append(idx) start = idx + 1 return indices if indices else -1 print(find_all_occurrences('abracadabra', 'abra')) # [0, 7]

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

d = {} d[key] = d.get(key, 0) + 1

Example

def letter_frequency(sentence): freq = {} for char in sentence.lower(): if char.isalpha(): freq[char] = freq.get(char, 0) + 1 return freq print(letter_frequency('Hello World'))

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

half1 = t[:len(t)//2] half2 = t[len(t)//2:] t_evens = tuple(x for x in t if x % 2 == 0) t_new = t1 + t2

Example

t1 = (1, 2, 5, 7, 9, 2, 4, 6, 8, 10) mid = len(t1) // 2 print('Half 1:', t1[:mid]) print('Half 2:', t1[mid:]) print('Even tuple:', tuple(x for x in t1 if x % 2 == 0)) print('Concatenated:', t1 + (11, 13, 15)) print('Min/Max:', min(t1), max(t1))

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

with open(src, 'r') as fin, open(dest, 'w') as fout: for idx, line in enumerate(fin, start=1): if idx % 2 != 0: # Odd line fout.write(line)

Example

def copy_odd_lines(file1, file2): with open(file1, 'r') as f1, open(file2, 'w') as f2: for line_no, line in enumerate(f1, start=1): if line_no % 2 != 0: f2.write(line) print('Odd numbered lines copied successfully.')

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

try: # risky code except ExceptionType as err: # handle error finally: # cleanup code

Example

def safe_divide(a, b): try: res = a / b except ZeroDivisionError: return 'Error: Division by zero is undefined!' except TypeError: return 'Error: Invalid operand types!' else: return f'Result = {res}' finally: print('Division operation finished.') print(safe_divide(10, 0))

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

class CustomError(Exception): pass raise CustomError('Custom error message')

Example

class DuplicateNumberError(Exception): '''Raised when a duplicate number is detected.''' pass def check_duplicates(numbers): seen = set() for num in numbers: if num in seen: raise DuplicateNumberError(f'Duplicate number found: {num}') seen.add(num) return 'All numbers are unique!'

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

import numpy as np arr_ones = np.ones(shape) dot_prod = np.dot(arr1, arr2) reshaped = arr.reshape(rows, cols)

Example

import numpy as np # 1s array a = np.ones((2, 3)) print('Ones:\n', a) # 1D to 2D Reshape arr1d = np.array([1, 2, 3, 4, 5, 6]) arr2d = arr1d.reshape(2, 3) print('Reshaped (2x3):\n', arr2d) # Dot Product v1 = np.array([1, 2, 3]) v2 = np.array([4, 5, 6]) print('Dot Product:', np.dot(v1, v2)) # 32

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

import matplotlib.pyplot as plt plt.plot(x, y, marker='o') plt.xlabel('X Axis Label') plt.ylabel('Y Axis Label') plt.title('Title') plt.show()

Example

import matplotlib.pyplot as plt months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'] profits = [12000, 15000, 18000, 14000, 22000, 25000, 21000, 28000, 30000, 32000, 35000, 40000] plt.figure(figsize=(10, 5)) plt.plot(months, profits, marker='o', color='teal', linewidth=2, label='ABC Corp') plt.xlabel('Month Number') plt.ylabel('Total profit') plt.title('Company ABC Annual Profit Report') plt.grid(True) plt.legend() plt.show()

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

x = np.linspace(start, stop, num_points) y = np.sin(x) plt.subplot(rows, cols, index)

Example

import numpy as np import matplotlib.pyplot as plt x = np.linspace(-2 * np.pi, 2 * np.pi, 300) plt.figure(figsize=(12, 8)) # Sine plt.subplot(2, 2, 1) plt.plot(x, np.sin(x), 'b-'); plt.title('Sine Curve'); plt.grid(True) # Cosine plt.subplot(2, 2, 2) plt.plot(x, np.cos(x), 'g-'); plt.title('Cosine Curve'); plt.grid(True) # Polynomial y = x^3 - 4x plt.subplot(2, 2, 3) plt.plot(x, x**3 - 4*x, 'r-'); plt.title('Polynomial Curve (x^3 - 4x)'); plt.grid(True) # Exponential y = e^x (bounded x) x_exp = np.linspace(-2, 2, 200) plt.subplot(2, 2, 4) plt.plot(x_exp, np.exp(x_exp), 'm-'); plt.title('Exponential Curve (e^x)'); plt.grid(True) plt.tight_layout() plt.show()

Generates 4 distinct subplots for Sine, Cosine, Polynomial ($x^3 - 4x$), and Exponential ($e^x$) curves using NumPy vectorization.

← Back to Python