L
LLLOS.ai
Learn
L

Chapter 2 — Introduction To Python

Class 11 · Informatics Practices

Overview

Chapter 2 — Introduction To Python Master Diagram

This chapter introduces Python as a high-level, interpreted, general-purpose programming language used for problem solving and application development. It explains why Python is important—simple, readable syntax; extensive standard libraries; quick development cycle; and strong demand in academics and industry. Key themes include Python’s basic syntax and execution model, data types and data structures, control flow (decision making and loops), functions and modular programming, input/output, and simple debugging. By the end of the chapter, students will understand how to write, run and test basic Python programs, use common built-in types and operators, apply control structures to solve problems, create and call functions, and follow good coding practices.

Learning Objectives

  • Define Python and list its key features, versions and common application areas
  • Explain the difference between an interpreter and a compiler and describe Python's execution model
  • Identify Python tokens (keywords, identifiers, literals, operators, delimiters) and naming conventions
  • Apply variables, constants and type conversion/casting to perform and evaluate expressions
  • Use input(), print() and formatted output to read from and display data in Python programs
  • Explain and use operators (arithmetic, relational, logical, assignment, membership and identity) in expressions
  • Construct decision-making statements (if, if-else, elif) and predict program flow for given conditions
  • Implement looping constructs (for, while) including break and continue to solve repetitive tasks

Topics in this chapter

24 topics · tap a topic title to jump straight to it.

💻1

Overview of Python

💻 COMPUTER SCIENCE / IT

Overview of Python

Key Point: Arithmetic: a + b, a - b, a * b, a / b (float division), a // b (integer division), a % b (remainder), a ** b (power)

What is Python? Python is a high-level, interpreted, general-purpose programming language designed for readability and rapid development. Created by Guido van Rossum and first released in 1991, Python supports multiple programming paradigms (procedural, object-oriented, and functional) and emphasizes clear, readable code using indentation for block structure.

Key characteristics — Python is:

  • Interpreted: Code runs via an interpreter (no separate compilation step needed).
  • Dynamically typed: Variable types are determined at runtime.
  • Garbage-collected: Automatic memory management for unused objects.
  • High-level: Provides built-in data types and abstractions (strings, lists, dictionaries, etc.).
  • Batteries-included: Large standard library and many third-party packages for web development, data science, automation, and more.

Where Python is used (real-life domains): web applications (Django, Flask), data analysis and machine learning (Pandas, NumPy, scikit-learn), automation and scripting, DevOps tools, scientific computing, GUI apps, IoT (Raspberry Pi), education, and more.

Basic building blocks — Python programs are made of:

  • Variables and basic data types: int, float, str, bool
  • Compound data structures: list, tuple, set, dict
  • Control flow: if, for, while
  • Functions: reusable blocks defined with def (or lambda for small anonymous functions)
  • Modules and packages: code organization and reuse across files
  • Exception handling: try/except for runtime errors
  • File I/O: reading/writing text and binary files

Simple example (structure and syntax):

def greet(name):
    if name:
        return 'Hello, ' + name
    else:
        return 'Hello, World'

print(greet('Anita'))  # Hello, Anita

Advantages in learning and industry: Python's simple syntax makes it ideal for beginners. Its extensive ecosystem and community support make it a first-choice language for prototyping, automation, and data work. Python 3 is the recommended version for modern code.

Execution modes: interactive mode (REPL) for quick experiments and script mode (run .py files) for full programs. Use virtual environments to manage project-specific packages.

Best practices (short): write readable code with meaningful names, follow indentation rules, prefer list/dict comprehensions for concise operations, handle exceptions where appropriate, and keep functions small and single-purpose.

📌 Examples
  • Automating repetitive tasks: renaming many files in a folder with a script using the os module.
  • Data analysis: loading a CSV with pandas and computing averages and plots for a school project.
  • Web application: building a simple student portal backend using Flask or Django.
  • Web scraping: collecting data from web pages with requests and BeautifulSoup.
  • IoT projects: controlling LEDs or sensors on a Raspberry Pi using Python libraries.
  • Simple utilities: a calculator, expense tracker, or text-based quiz game implemented in Python.
🧮 Formulas
  1. \[Arithmetic: a + b\]
    \[a - b\]
    \[a * b\]
    \[a / b (float division)\]
    \[a // b (integer division)\]
    \[a % b (remainder)\]
    \[a ** b (power)\]
  2. \[Assignment and update: x = 5\]
    \[x += 2 # x becomes 7\]
  3. \[Comparison/logical: x == y\]
    \[x != y\]
    \[x < y\]
    \[x > y\]
    \[a and b\]
    \[a or b\]
    \[not a\]
  4. \[String operations: s + t (concatenation)\]
    \[s * 3 (repeat)\]
    \[s[index]\]
    \[s[start:end:step] (slicing)\]
  5. \[List slicing and indexing: L[i]\]
    \[L[start:stop]\]
    \[L[start:stop:step]\]
  6. \[List comprehension: [expr for item in iterable if condition] # concise list creation\]
💻2

Installing Python and IDEs

💻 COMPUTER SCIENCE / IT

Installing Python and IDEs

Key Point: python --version # check interpreter version

What and Why

Python is a high-level, interpreted programming language used for scripting, web development, data analysis, automation and education. To write and run Python programs you need the Python interpreter installed and an editor or Integrated Development Environment (IDE) to write, run and debug code.

Choose Python Version

Use Python 3 (current stable release). Python 2 is obsolete. Always choose a stable 3.x release compatible with libraries you need.

Installation — Quick Steps by OS

  1. Windows
    1. Go to https://www.python.org/downloads/ and download the Windows installer for Python 3.x.
    2. Run the installer. Important: check "Add Python to PATH" before clicking "Install Now".
    3. After install, verify in Command Prompt:
      python --version
      pip --version
  2. macOS
    1. Install using the official installer from python.org or use Homebrew:
      /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
      brew install python
    2. Verify:
      python3 --version
      pip3 --version
  3. Linux (Ubuntu/Debian)
    1. Use package manager:
      sudo apt update
      sudo apt install python3 python3-pip
    2. Verify:
      python3 --version
      pip3 --version

Virtual Environments (recommended)

Use venv to create isolated environments so project packages don't clash:

python3 -m venv env        # create environment
# Activate on macOS/Linux:
source env/bin/activate
# Activate on Windows (PowerShell):
env\Scripts\Activate.ps1
# Install packages inside env:
pip install requests

IDEs and Editors — Options & When to Use

  • IDLE — comes with Python, simple for beginners.
  • Thonny — beginner-friendly, shows how code executes step-by-step.
  • VS Code — lightweight editor with Python extension: good for all levels, supports debugging, virtual envs, Jupyter.
  • PyCharm (Community) — full-featured IDE for larger projects with code inspection and project management.
  • Jupyter Notebook / Lab — interactive notebooks, ideal for data analysis, visualization and teaching.
  • Spyder — scientific IDE (similar to MATLAB) used for data science.

Configuring an IDE

  1. Install the IDE (download or via package manager).
  2. In the IDE settings, select the Python interpreter (system python or virtual environment python executable).
  3. Install necessary extensions/plugins (e.g., Python extension in VS Code).
  4. Configure linter and formatter (optional) like flake8 or black.

First Program & Testing

Create a file hello.py with:

print("Hello, world!")

Run from terminal:

python hello.py   # or python3 hello.py

Troubleshooting Tips

  • If "python" command not found, confirm PATH or use full path or "python3".
  • Use pip list or pip3 list to check installed packages:
    pip list
  • If multiple Python versions exist, specify the correct interpreter in IDE settings.

Security & Best Practices

  • Keep Python and packages updated:
    pip install --upgrade pip
    pip install --upgrade 
  • Use virtual environments for each project.
  • Install packages from trusted sources (PyPI) and review dependencies.

Summary

Installing Python is straightforward: download or use a package manager, verify installation, create virtual environments, choose an IDE suitable for your needs, configure the interpreter, and run a test program. For classroom learning, Thonny or VS Code are often the best starting points.

📌 Examples
  • Hello World (hello.py): print("Hello, world!") # Run with: python hello.py
  • Create and use virtual environment (macOS/Linux): python3 -m venv env source env/bin/activate pip install requests
  • Install a package globally with pip: python -m pip install requests # Verify: pip show requests
  • Using VS Code: install VS Code → install Python extension → open folder → select interpreter (Command Palette: Python: Select Interpreter) → Run and Debug.
  • Jupyter example: install and start pip install notebook jupyter notebook # Create a notebook cell: import math math.sqrt(16)
🧮 Formulas
  1. \[python --version # check interpreter version\]
  2. \[python3 -m venv env # create virtual environment\]
  3. \[source env/bin/activate # activate on macOS/Linux\]
  4. \[env\Scripts\activate # activate on Windows (cmd)\]
  5. \[python -m pip install <package-name> # install package\]
  6. \[#! /usr/bin/env python3 (shebang for executable scripts on Unix)\]
💻3

Python Interpreter and Execution Model

💻 COMPUTER SCIENCE / IT

Python Interpreter and Execution Model

Key Point: Execution pipeline: source code -> tokens -> AST -> bytecode -> Python Virtual Machine (PVM) execution

Overview
Python is an interpreted, high-level, dynamically typed language. The Python interpreter reads your source code, translates it into an intermediate form, and executes it. The common reference implementation is CPython, which compiles Python source to bytecode and executes that bytecode on a Python Virtual Machine (PVM).

Interpreter vs Compiler (brief)

  • Compiler: translates source code fully into machine code before execution (example: C).
  • Interpreter: translates and executes code in smaller steps at runtime (example: Python). CPython uses a hybrid approach: it first compiles source to bytecode, then interprets bytecode.

Execution pipeline (step-by-step)

  • Source code: the .py file you write.
  • Lexical analysis / Tokenization: source is broken into tokens (keywords, identifiers, literals, operators).
  • Parsing: tokens are converted to an Abstract Syntax Tree (AST) that represents the program structure.
  • Bytecode compilation: AST is compiled into bytecode (a lower-level, platform-independent instruction set).
  • Python Virtual Machine (PVM): the PVM executes bytecode using an interpreter loop (fetch-decode-execute) and manages runtime structures like stack frames and namespaces.

Runtime concepts

  • Stack frames: each function call creates a frame containing local variables, instruction pointer, and evaluation stack.
  • Namespaces: collections that map names to objects. Typical namespaces are local, enclosing, global, and built-in (LEGB rule for name resolution).
  • Dynamic typing: variables are names bound to objects; types belong to objects and can change at runtime.
  • Memory management: objects are allocated on the heap; CPython uses reference counting plus a cyclic garbage collector to reclaim unreachable cycles.
  • Errors: syntax errors are caught at parsing/compilation time; exceptions (runtime errors) occur during execution.

Interactive mode vs Script mode

  • Interactive (REPL): enter statements/expression and get immediate results; good for experimentation and learning.
  • Script mode: run .py files using the interpreter (python file.py) for programs and automation.

Practical notes
Because Python compiles to bytecode, you may see .pyc files in __pycache__ created by CPython to speed up subsequent imports. Alternative interpreters (PyPy, Jython, IronPython) provide different execution strategies (e.g., JIT compilation) but keep the same high-level semantics.

Small example of the pipeline (visualized)

source:   x = 10
parser:   AST nodes for assignment and literal
compile:  bytecode (LOAD_CONST 10; STORE_NAME 'x')
PVM:      execute bytecode, allocate object 10, bind name 'x' to it

📌 Examples
  • Interactive REPL: >>> x = 5; >>> x = x + 2; >>> print(x) # outputs 7 — demonstrates dynamic typing and immediate execution
  • Script mode: file example.py containing: # example.py name = 'Asha' print('Hello', name) Run: python example.py # interpreter compiles to bytecode then executes the program
  • Scope (LEGB) example: def outer(): x = 'enclosing' def inner(): x = 'local' print(x) # prints 'local' (Local -> Enclosing -> Global -> Built-in) inner()
🧮 Formulas
  1. \[Execution pipeline: source code -> tokens -> AST -> bytecode -> Python Virtual Machine (PVM) execution\]
  2. \[LEGB rule for name lookup: Local -> Enclosing -> Global -> Built-in\]
  3. \[Memory model: objects on Heap\]
    \[references via names\]
    \[CPython uses Reference Count + Cycle GC\]
  4. \[Interpreter loop concept: fetch (bytecode) -> decode -> execute -> repeat\]
💻4

Comments and Indentation

💻 COMPUTER SCIENCE / IT

Comments and Indentation

Key Point: Comment syntax: single-line -> # comment_text

What are Comments?
Comments are non-executable text in a program used to explain code, leave notes for programmers, or document behaviour. Python ignores comments while running the program.

Types of comments in Python

  • Single-line comment: starts with #. Everything after # on the same line is a comment. Example: # This is a comment
  • Inline comment: placed after a statement on the same line: x = 5 # set x to 5
  • Multiline documentation strings (docstrings): triple quotes """...""" or '''...''' immediately after a module, function or class header. They are string literals used for documentation and are accessible at runtime via __doc__. (Technically they are strings, not comments.)

Best practices for comments

  • Keep comments short, meaningful and up to date.
  • Use comments to explain why something is done, not what simple statements do.
  • Use docstrings for public functions/classes/modules to document purpose, parameters and return values.

What is Indentation?
In Python indentation (leading spaces or tabs) defines blocks of code (the body of functions, loops, if-else, classes). Python uses indentation instead of braces ({ }) used in many other languages.

Key indentation rules

  • After a statement that ends with a colon (for, if, while, def, class, try, with, etc.), the following indented lines form the block associated with that statement.
  • All statements in the same block must have the same indentation level.
  • Mixing tabs and spaces in indentation can cause IndentationError or inconsistent behavior — PEP 8 recommends using 4 spaces per indent level.

Example: correct vs incorrect indentation

# Correct indentation
if x > 0:
    print('Positive')
    x -= 1
else:
    print('Non-positive')

# Incorrect indentation (will raise IndentationError or give unexpected block)
if x > 0:
print('Positive')  # Not indented

Docstrings example

def add(a, b):
    """Return the sum of a and b.

    Parameters:
      a (int): first number
      b (int): second number
    Returns:
      int: a + b
    """
    return a + b

Why good indentation and comments matter

  • Indentation makes logical structure visible, improving readability and preventing logic errors.
  • Good comments and docstrings make code maintainable and easier for others (or yourself later) to understand.

Quick tips

  • Use an editor that shows invisible characters and converts tabs to spaces.
  • Follow PEP 8: 4 spaces per indentation level, and short, clear docstrings.
  • Comment intent, not obvious operations; keep comments synchronized with code changes.
📌 Examples
  • # Single-line comment x = 10 # x stores the number of items
  • '''Module docstring example: This module contains utility functions for math operations. ''' def multiply(a, b): """Return product of a and b.""" return a * b
  • if score >= 90: grade = 'A' elif score >= 75: grade = 'B' else: grade = 'C' # All assignments inside the same block are indented equally
  • # Incorrect indentation example (raises IndentationError): for i in range(3): print(i) # must be indented under the for loop
🧮 Formulas
  1. \[Comment syntax: single-line -> # comment_text\]
  2. \[Docstring syntax: module/function/class -> """Documentation text"""\]
  3. \[Block rule: header_statement: \n<indent>block_statement_1\n<indent>block_statement_2 -> all lines in a block must have the same indentation\]
  4. \[PEP 8 recommendation: indentation = 4 spaces per level\]
  5. \[Error condition: mixing_tabs_and_spaces -> IndentationError or inconsistent behavior\]
💻5

Keywords and Identifiers

💻 COMPUTER SCIENCE / IT

Keywords and Identifiers

Key Point: Identifier regular expression: ^[A-Za-z_][A-Za-z0-9_]*$

Keywords are reserved words in Python that have a predefined meaning to the interpreter and cannot be used as names (identifiers) for variables, functions, classes, or other user-defined items. Examples include: if, else, for, while, def, class, import, return, True, False, None, etc. The full list of keywords can be obtained in Python using import keyword; keyword.kwlist.

Identifiers are names given by the programmer to entities like variables, functions, classes, modules, and objects. Identifiers must follow certain rules so the interpreter can correctly recognize them:

  • Must start with a letter (A–Z or a–z) or an underscore (_).
  • Can contain letters, digits (0–9) and underscores only: no spaces or other special characters.
  • Are case-sensitive: age and Age are different identifiers.
  • Cannot be a Python keyword or a built-in constant like True, False, None (they are reserved).
  • There is no practical length limit, but keep names readable.

Formal pattern (regular expression) for a valid identifier: ^[A-Za-z_][A-Za-z0-9_]*$

Naming conventions (best practices) (not enforced by the interpreter but recommended):

  • snake_case for variable and function names (e.g., student_name).
  • PascalCase / CapWords for class names (e.g., StudentRecord).
  • Use UPPERCASE for constants (e.g., MAX_SPEED = 100).
  • Single leading underscore (_name) indicates internal use; double leading underscores (__name) trigger name mangling in classes.

Why this matters: Using meaningful, valid identifiers makes code readable and avoids syntax errors. Attempting to use a keyword as an identifier or starting an identifier with a digit will raise a syntax error.

Quick examples (code):

# Valid identifiers
student_name = "Asha"
_age = 17
score1 = 95

# Invalid identifiers (cause errors)
# 1name = 10      # starts with digit -> SyntaxError
# total marks = 100  # space in name -> invalid
# for = 5         # 'for' is a keyword -> SyntaxError

Special identifiers: Names surrounded by double underscores (e.g., __init__, __name__) have special meaning in Python (magic methods or module attributes) but are not keywords; avoid redefining them unless you know what you are doing.

📌 Examples
  • Valid identifiers: student_name, _temp, totalMarks2025, calculate_area, MAX_SPEED
  • Invalid identifiers: 2ndPlace (starts with digit), user-name (hyphen not allowed), my var (space not allowed), class (keyword)
  • Real-life mapping: student_name -> stores a student's name; roll_no -> stores student's roll number; is_passed -> boolean True/False indicating pass status
  • Conventions: Use student_address (snake_case) for variables, StudentRecord (PascalCase) for class names, PI = 3.14 for constants
  • Special/intent identifiers: _internal_cache (indicates internal use), __init__ (class constructor method name, special/magic)
🧮 Formulas
  1. \[Identifier regular expression: ^[A-Za-z_][A-Za-z0-9_]*$\]
  2. \[Get keywords in Python: import keyword\]
    \[keyword.kwlist # returns list of reserved words\]
  3. \[Count keywords: len(keyword.kwlist) # returns number of keywords in that Python version\]
  4. \[Naming patterns (style guidelines\]
    \[not language formulas): snake_case for variables/functions\]
    \[PascalCase for classes\]
    \[UPPERCASE for constants\]
💻6

Variables and Assignment

💻 COMPUTER SCIENCE / IT

Variables and Assignment

Key Point: variable = expression # general assignment

What is a variable?
A variable is a name (label) that refers to a value stored in the computer's memory. In Python, variables are created when you assign a value to a name. Variables make programs readable and allow data to be reused and changed.

Assignment operator
The single equals sign = is the assignment operator. The right-hand side (an expression) is evaluated first, and the result is bound to the name on the left-hand side.

Basic rules for naming variables

  • Use letters, digits and underscores only: age_11, studentName.
  • Must not start with a digit: _score or score1 are valid, 1score is not.
  • Cannot use Python keywords (like for, if, class).
  • Prefer meaningful names and use snake_case for readability: total_marks, average_score.

Dynamic typing
Python is dynamically typed: a variable can be bound to values of different types during program execution. Example: x = 5 then x = 'five' is allowed.

Common assignment forms

  • Simple: x = expression
  • Multiple assignment (unpacking): a, b = 10, 20
  • Chain assignment: x = y = 0 (both refer to the same value)
  • Augmented assignment: count += 1 (short for count = count + 1)
  • Swap using tuple unpacking: a, b = b, a

Mutability vs immutability (brief)
Immutable types (int, float, str, tuple) cannot be changed in place; assignment creates a new object and binds the name to it. Mutable types (list, dict, set) can be changed in place; two variable names can reference the same mutable object (aliasing).

Memory analogy
Think of a variable as a labeled box. Assignment places a value inside the box or points the label to an object. Reassigning changes which object the label points to.

Best practices

  • Use clear, descriptive names and follow naming conventions.
  • Initialize variables before use.
  • Be careful with mutable objects—copy if you need independent copies.
  • Use augmented assignment for concise updates and potentially better performance.

Small code examples (illustrative)

age = 15                     # store an integer
name = 'Asha'                 # store a string
balance = float(input())      # convert input and assign
x, y = 5, 10                  # multiple assignment
x, y = y, x                   # swap values
scores = [10, 20]             # mutable object (list)
scores2 = scores              # aliasing: both names refer to same list
scores.append(30)             # modifies the list seen by both names
count = 0
count += 1                    # augmented assignment

This covers the core ideas of variables and assignment in Python for Class 11 Informatics Practices.

📌 Examples
  • Store student data: student_name = 'Rahul'; age = 16; total_marks = 482
  • Bank balance update: balance = 1500.0; deposit = 500.0; balance += deposit # balance becomes 2000.0
  • Swap two numbers without temp: a, b = 3, 7; a, b = b, a # now a=7, b=3
  • Multiple initialization: x = y = z = 0 # all three variables set to 0
  • Input and conversion: mark = int(input('Enter marks: ')) # assigns integer value from user input
  • Aliasing example: list1 = [1,2]; list2 = list1; list2.append(3) # list1 becomes [1,2,3] too
🧮 Formulas
  1. \[variable = expression # general assignment\]
  2. \[a\]
    \[b = value1\]
    \[value2 # unpacking / multiple assignment\]
  3. \[x = y = value # chain assignment\]
  4. \[x += n # augmented assignment equivalent to x = x + n\]
  5. \[a\]
    \[b = b\]
    \[a # swap values using tuple unpacking\]
  6. \[x = int(input()) # convert input string to integer and assign\]
📊7

Data Types and Literals

💻 COMPUTER SCIENCE / IT

Data Types and Literals

Key Point: int(x) => converts x to integer when possible (truncates toward 0 for floats)

What are Data Types?
A data type specifies the kind of values that can be stored and the operations that can be performed on them. Python is dynamically typed (you don’t declare types explicitly) and strongly typed (operations check types).

Common built-in data types in Python:

  • Numeric
    • int — integers, e.g., 42, -7
    • float — floating-point numbers (decimals), e.g., 3.14, -0.5
    • complex — complex numbers with real and imaginary parts, e.g., 2+3j
  • Boolean — True or False (capitalized)
  • String — sequence of characters enclosed in single, double or triple quotes, e.g., 'hello', "world", '''multi-line'''
  • NoneType — None (represents absence of value)

Literals
Literals are fixed values written directly in code. Examples: 100, 3.5, 'CBSE', True, None.

Numeric literal forms

  • Decimal: 255
  • Binary: 0b1010 (prefix 0b)
  • Octal: 0o377 (prefix 0o)
  • Hexadecimal: 0xFF (prefix 0x)
  • Underscores allowed for readability: 1_000_000
  • Imaginary: 3j or 2+3j

String literals

  • Single or double quotes: 'a' or "a"
  • Triple quotes for multi-line strings: '''multi\nline'''
  • Raw strings to ignore escape sequences: r"C:\\new_folder"

Boolean and None literals

  • True and False (note the capitalization)
  • None represents no value

Type checking and conversion

  • type(x) returns the type of x
  • isinstance(x, T) checks whether x is of type T
  • Explicit conversion (casting): int(), float(), str(), complex()
  • Implicit (coercion) example: int + float -> float

Important properties

  • Immutability: numbers and strings are immutable (operations create new objects)
  • Booleans are a subtype of integers: True == 1, False == 0

Small code examples

age = 16                # int literal
price = 199.99           # float literal
name = 'Asha'            # string literal
flag = True              # boolean literal
z = 3 + 4j               # complex literal

print(type(age))         # >> <class 'int'>
print(int(3.9))          # >> 3  (casting truncates toward 0)
print(1 + 2.0)           # >> 3.0  (int + float -> float)

Rules & tips

  • String concatenation: 'Hello' + ' ' + 'World' -> 'Hello World'
  • String repetition: 'ha' * 3 -> 'hahaha'
  • Division behaviors: / gives float, // gives integer floor division, % gives remainder
  • Use underscores in long numeric literals for readability: 3_500_000

Where used in real life? Data types allow programs to model real-world data correctly — e.g., ages as integers, prices as floats, product codes as strings, feature flags as booleans, sensor data as floats or lists of floats.

📌 Examples
  • age = 17 # int literal; use for whole-number quantities like years
  • price = 249.50 # float literal; use for money amounts (consider decimal for exact currency work)
  • is_student = True # boolean literal; use for yes/no conditions
  • hex_color = 0xff00ff # hexadecimal literal; common in web colors
  • path = r"C:\users\data" # raw string literal to avoid escaping backslashes
  • complex_num = 2 + 3j # complex literal; used in some engineering calculations
🧮 Formulas
  1. \[int(x) => converts x to integer when possible (truncates toward 0 for floats)\]
  2. \[float(x) => converts x to floating-point representation\]
  3. \[str(x) => converts x to string representation\]
  4. \[complex(a\]
    \[b) or a + bj => constructs a complex number with real a and imaginary b\]
  5. \[division algorithm: dividend = divisor * quotient + remainder (0 <= remainder < |divisor|)\]
  6. \[type coercion rule (common): int + float => float\]
💻8

Input and Output

💻 COMPUTER SCIENCE / IT

Input and Output

Key Point: Sum of two numbers: sum = a + b

Overview: In Python, input and output (I/O) means getting data from the user (input) and showing results on the screen or writing them out (output). The two most common functions are input() for reading from the keyboard and print() for writing to the console.

input(): input(prompt) displays an optional prompt and returns the user-entered data as a string. Because it always returns a string, you must convert it to numeric types when needed using int(), float(), etc. Example: age = int(input('Enter age: ')). Handle incorrect input using try/except to avoid ValueError.

print(): print(value1, value2, ..., sep=' ', end='\n', file=sys.stdout, flush=False) prints one or more values separated by sep and terminated by end. Common parameters:
- sep: string inserted between values (default a single space),
- end: string appended after the last value (default newline).
For formatted output use f-strings (Python 3.6+): print(f"Name: {name}, Score: {score:.2f}") or format() / % formatting.

Reading multiple values: Use split() to divide an input string and map() to convert types, e.g. a, b = map(int, input().split()) reads two integers from one line. For lists: nums = list(map(float, input().split())).

Common pitfalls: forgetting to convert types (so arithmetic on strings concatenates instead of adds), not trimming whitespace, and not handling exceptions. For numeric precision, control display with format specifiers like {value:.2f} to show two decimal places.

Good practice: Validate inputs, give clear prompts, convert types explicitly, and format outputs for readability (labels, fixed decimal places, alignment when printing tables).

📌 Examples
  • 1) Greeting (string input): name = input('Enter your name: ') print('Hello,', name) Output if input 'Asha': Hello, Asha
  • 2) Sum of two numbers (numeric conversion): a = int(input('Enter a: ')) b = int(input('Enter b: ')) print('Sum =', a + b) If inputs 4 and 5 -> Sum = 9
  • 3) Read multiple values in one line and average: marks = list(map(float, input('Enter marks separated by space: ').split())) avg = sum(marks) / len(marks) print(f'Average = {avg:.2f}') Input: 78 85 90 -> Average = 84.33
  • 4) Area of a circle (using float input and math): import math r = float(input('Radius: ')) area = math.pi * r * r print(f'Area = {area:.3f}') Input: 2 -> Area = 12.566
  • 5) Formatted table output (aligned columns): students = [('Asha', 85), ('Ravi', 92)] print('Name Marks') for name, marks in students: print(f'{name:<8} {marks:>3}') Output: Name Marks Asha 85 Ravi 92
🧮 Formulas
  1. \[Sum of two numbers: sum = a + b\]
  2. \[Average of n numbers: average = (x1 + x2 + ... + xn) / n\]
  3. \[Area of a circle: area = π * r * r (use math.pi in Python)\]
  4. \[Type conversion examples: int('123')\]
    \[float('3.14')\]
    \[str(100)\]
  5. \[print formatting: print(f"Value = {value:.2f}") -> shows value with 2 decimal places\]
  6. \[Reading multiple inputs: a\]
    \[b = map(int\]
    \[input().split())\]
💻9

Operators and Expressions

💻 COMPUTER SCIENCE / IT

Operators and Expressions

Key Point: Addition/Subtraction: result = a + b or result = a - b

What are operators and expressions?

An operator is a symbol that performs an operation on one or more operands (values or variables). An expression is a combination of operands and operators that Python evaluates to produce a value.

Types of operators in Python (with purpose)

  • Arithmetic: +, -, *, /, // (floor division), % (modulo), ** (exponentiation) — for numeric calculations.
  • Assignment: = and augmented assignments like +=, -=, *= — to store values in variables.
  • Relational (comparison): ==, !=, >, <, >=, <= — compare values and return True/False.
  • Logical: and, or, not — combine boolean conditions.
  • Bitwise: &, |, ^, ~, <<, >> — operate at binary bit level (useful for low-level tasks and flags).
  • Membership: in, not in — test membership in sequences (strings, lists, tuples, sets, dict keys).
  • Identity: is, is not — test if two references point to the same object.

Expressions and evaluation

  • Simple expression: a + b * c. Python evaluates based on operator precedence (multiplication before addition) and associativity (left-to-right for most binary operators).
  • Parentheses () override precedence: (a + b) * c.
  • Type conversion: when operands have different numeric types, Python performs implicit conversion (e.g., int to float). You can also use explicit conversion functions like int(), float(), str().
  • Short-circuit evaluation: in logical expressions, Python stops evaluating as soon as the result is determined (e.g., False and expr2 never evaluates expr2).

Important: Operator precedence (high to low) — common subset

1.  ( )        parentheses
2.  **         exponentiation (right-associative)
3.  +x, -x, ~x unary plus, minus, bitwise NOT
4.  *, /, //, %
5.  +, -      addition, subtraction
6.  <<, >>    bit shifts
7.  &, ^, |   bitwise AND, XOR, OR
8.  ==, !=, >, <, >=, <=    comparisons
9.  not      logical NOT
10. and      logical AND
11. or       logical OR
12. if-else (ternary)
13. =, +=, -=, ...  assignment

Best practices

  • Use parentheses to make expressions readable and avoid ambiguity.
  • Prefer augmented assignment for clarity and performance when updating variables (x += 1).
  • Be careful with floating point division vs integer division (use // when integer result is required).
  • Use descriptive variable names so expressions read like meaningful statements.

Small code examples (conceptual)

# arithmetic
bill = price * quantity
total = bill + bill * tax_rate

# comparison and logical
eligible = (age >= 18) and (has_id == True)

# membership
if name in students:  # True if name appears in list
    print("Present")

# augmented assignment
x = 5
x *= 3  # x becomes 15

# bitwise for permissions (example)
READ = 0b100
WRITE = 0b010
EXECUTE = 0b001
perm = READ | WRITE  # combine permissions

Summary: Operators let you perform computations and tests; expressions combine operators and operands to produce values. Understanding precedence, associativity, and type behavior is essential to write correct Python programs.

📌 Examples
  • Shopping bill: subtotal = sum(item_prices); tax = subtotal * tax_rate; total = subtotal + tax. Use parentheses if discounts apply: total = (subtotal - discount) + tax.
  • Temperature conversion: celsius = (fahrenheit - 32) * 5 / 9 — demonstrates arithmetic operators and order of operations.
  • Eligibility check: can_vote = (age >= 18) and (citizen == True) — uses relational and logical operators.
  • Login condition: if username in users and password == stored_password: login_success = True — membership + comparison + logical.
  • File permission flags (bitwise): set write permission: perm |= WRITE; check: if perm & WRITE: has_write = True.
  • Swap two variables without temporary using tuple unpacking: a, b = b, a — uses comma operator to form tuple and assignment.
🧮 Formulas
  1. \[Addition/Subtraction: result = a + b or result = a - b\]
  2. \[Multiplication/Division: result = a * b or result = a / b (float division)\]
  3. \[Floor division and modulo: q = a // b (quotient floor)\]
    \[r = a % b (remainder)\]
    \[relation: a = b * q + r\]
  4. \[Exponentiation: power = a ** b (a raised to b)\]
  5. \[Augmented assignment: x op= y is equivalent to x = x op y (e.g.\]
    \[x += 3 means x = x + 3)\]
  6. \[Comparison yields boolean: expression like (a < b) returns True or False\]
💻10

Control Flow — Conditional Statements

💻 COMPUTER SCIENCE / IT

Control Flow — Conditional Statements

Key Point: if syntax: if condition: statements

What is control flow? Control flow determines the order in which individual statements, instructions or function calls are executed or evaluated in a program. Conditional statements let a program make decisions and execute different code paths depending on whether a condition is true or false.

Why use conditional statements? To respond to different inputs and situations, implement branching logic (choose one of several actions), validate data, and control program behavior based on computed conditions.

Types of conditional statements in Python

  • if: execute a block when a condition is true.
  • if-else: choose between two blocks (true vs false).
  • if-elif-else: select among multiple exclusive alternatives.
  • Nested if: place an if (or if-else) inside another to test sub-conditions.

Basic syntax and examples

if condition:
    # statements when condition is True
elif another_condition:
    # statements when another_condition is True
else:
    # statements when all above conditions are False

Simple Python examples

# if example
age = 17
if age >= 18:
    print('You can vote.')

# if-else example
marks = 45
if marks >= 50:
    print('Pass')
else:
    print('Fail')

# if-elif-else example (grading)
score = 78
if score >= 90:
    grade = 'A'
elif score >= 75:
    grade = 'B'
elif score >= 60:
    grade = 'C'
else:
    grade = 'D'
print('Grade =', grade)

# ternary (conditional) expression
result = 'Even' if n % 2 == 0 else 'Odd'

Boolean expressions and truthiness

  • Conditions are expressions that evaluate to True or False.
  • Comparisons: ==, !=, <, <=, >, >=.
  • Logical operators: and, or, not.
  • In Python many values have truthiness: 0, 0.0, '', None and empty containers are False; most other values are True.

Short-circuit evaluation: in expressions with and/or, evaluation stops as soon as the outcome is determined (so later parts may not be evaluated).

Common pitfalls and best practices

  • Indentation is mandatory; use consistent indentation (4 spaces recommended).
  • Avoid deep nesting; prefer early returns or logical combinations.
  • Use elif for multiple mutually exclusive choices rather than many nested if-else.
  • Use meaningful boolean variable names to improve readability.

Flow of a conditional (summary)

Evaluate condition → if True execute block A → else (or elif) execute alternative block(s). Each condition is checked in order for if-elif-else chains.

📌 Examples
  • Traffic light: if light == 'green' then go; elif light == 'yellow' then slow down; else stop.
  • Age-based access: if age >= 18 then allow voting, else deny.
  • Grading system: if marks >= 90 then grade A; elif marks >= 75 then grade B; else lower grades.
  • Bank ATM withdrawal: if balance >= amount then approve and deduct; else show insufficient funds.
  • Thermostat control: if temp < set_point then switch_heater_on; elif temp > set_point then switch_cooler_on; else do_nothing.
🧮 Formulas
  1. \[if syntax: if condition: statements\]
  2. \[if-else syntax: if condition: statements_true else: statements_false\]
  3. \[if-elif-else syntax: if cond1: ... elif cond2: ... else: ...\]
  4. \[Ternary (conditional) expression: value_if_true if condition else value_if_false\]
  5. \[Comparison operators: ==, !=, <, <=, >, >=\]
  6. \[Logical operators and truth tables: A and B: True only if A is True and B is True A or B: True if A is True or B is True (or both) not A: True if A is False (Short truth table) A | B | A and B | A or B T | T | T | T T | F | F | T F | T | F | T F | F | F | F\]
💻11

Control Flow — Loops

💻 COMPUTER SCIENCE / IT

Control Flow — Loops

Key Point: range(start, stop, step) generates roughly ceil((stop - start) / step) iterations (when step > 0).

Loops are control-flow structures that repeat a block of code while a condition holds or for each item in a sequence. They help avoid code repetition, process collections, and implement iterative algorithms. Python provides two main loop constructs: while and for.

1. while loop
The while loop repeatedly executes a block as long as a Boolean condition is True. Typical pattern:

while condition:
    statements
    (update to move toward terminating condition)

Care must be taken to update variables used in the condition, otherwise an infinite loop will occur.

2. for loop
Python's for loop iterates over items of any iterable (lists, tuples, strings, range, etc.). Typical pattern:

for item in iterable:
    statements

Commonly used with range(start, stop, step) to generate sequences of integers.

3. Loop control statements
- break: exit the current loop immediately.
- continue: skip the rest of the loop body and start next iteration.
- pass: no-operation placeholder (useful where syntax requires a statement).
- else with loops: an optional else block runs if the loop completes normally (i.e., not terminated by break).

4. Nested loops
Loops may be placed inside other loops. The total number of iterations is typically the product of the iteration counts of each nested level (useful but can increase time complexity).

5. Practical tips
- Use enumerate() when you need both index and item in a for loop.
- Prefer for when iterating known collections/ranges; use while for condition-driven repetition.
- Avoid modifying the iterable you're iterating over (e.g., removing items from a list while using for on it); iterate over a copy instead.

6. Example snippets

# while: sum numbers until user enters 0
n = int(input())
s = 0
while n != 0:
    s += n
    n = int(input())
print(s)

# for with range: print first 5 squares
for i in range(1, 6):
    print(i*i)

# break and else
for x in [2, 3, 5, 7]:
    if x % 2 == 0:
        print('Found even')
        break
else:
    print('No break, all odd primes here (except 2)')

7. Complexity
Loops often determine time complexity. A single loop over n items is O(n). Nested loops that each run n times are O(n^2). Keep this in mind for performance-sensitive code.

📌 Examples
  • Calculate factorial of n using a for loop: n = 5 fact = 1 for i in range(1, n+1): fact *= i print(fact) # output 120
  • Sum of list of marks using a while loop: marks = [72, 85, 90, 68] i = 0 s = 0 while i < len(marks): s += marks[i] i += 1 print('Total:', s)
  • Print multiplication table (nested loops): for i in range(1, 6): for j in range(1, 11): print(f"{i}x{j}={i*j}") print()
  • Menu-driven program (use while True and break): while True: choice = input('A-add, Q-quit: ') if choice.upper() == 'Q': break elif choice.upper() == 'A': print('Add selected') else: print('Invalid')
🧮 Formulas
  1. \[range(start\]
    \[stop\]
    \[step) generates roughly ceil((stop - start) / step) iterations (when step > 0).\]
  2. \[Number of iterations in a simple for-loop over n items = n.\]
  3. \[Nested loops: if outer loop runs n times and inner loop runs m times per outer iteration\]
    \[total iterations = n * m.\]
  4. \[Sum computed by a loop accumulating an arithmetic sequence: sum = n * (first + last) / 2.\]
  5. \[Factorial definition (computed by a loop): n! = 1 * 2 * ... * n.\]
💻12

Functions — Definition and Usage

📐 MATHEMATICAL FORMULA / THEOREM

Functions — Definition and Usage

Key Point: Function definition template: def function_name(param1, param2=default, *args, **kwargs):

What is a function? A function is a named, reusable block of code that performs a specific task. In Python a function helps you break a program into smaller, manageable pieces, improves readability and enables reuse.

Basic syntax:

def function_name(parameter1, parameter2, ...):
    """Optional docstring describing the function"""
    statements
    return value  # optional

Key concepts:

  • Definition vs Call: You define a function with def and you call it by writing its name with arguments.
  • Parameters and arguments: Parameters are names in the definition; arguments are actual values passed when calling.
  • Return value: A function can return a value using return. If omitted, it returns None.
  • Parameter types: positional, keyword, default, arbitrary positional (*args), arbitrary keyword (**kwargs).
  • Lambda (anonymous) functions: Short single-expression functions: lambda x: x * 2.
  • Scope: Variables declared inside a function are local; variables outside are global. Use global or nonlocal only when needed.
  • Docstrings and annotations: Add documentation and optional type hints for clarity.

Why use functions? Modularity, reusability, easier testing and debugging, clearer structure and separation of concerns. Functions let you implement algorithms once and call them wherever needed.

Example flow:

# Define
def average(marks):
    return sum(marks) / len(marks)

# Use (call)
avg = average([75, 82, 90])
print(avg)

Best practices:

  • Give meaningful function names (verb or verb phrase).
  • Keep functions short and focused on one task.
  • Write docstrings that explain inputs, outputs and side effects.
  • Prefer returning values instead of modifying global state.
📌 Examples
  • 1) Simple function with parameters and return: def add(a, b): return a + b print(add(5, 3)) # Output: 8
  • 2) Temperature converter (real-life example): def celsius_to_fahrenheit(c): return (c * 9/5) + 32 print(celsius_to_fahrenheit(25)) # Output: 77.0
  • 3) Function with default and keyword arguments: def greet(name, msg='Hello'): return f"{msg}, {name}!" print(greet('Anita')) print(greet('Anita', msg='Good morning'))
  • 4) Variable-length arguments (*args, **kwargs): def stats(*numbers, round_to=2): mean = sum(numbers)/len(numbers) return round(mean, round_to) print(stats(10, 20, 30)) # Output: 20.0
  • 5) Lambda (anonymous) function: square = lambda x: x * x print(square(6)) # Output: 36
  • 6) Recursion (factorial) — shows call stack and base case: def factorial(n): if n == 0 or n == 1: return 1 return n * factorial(n - 1) print(factorial(5)) # Output: 120
🧮 Formulas
  1. \[Function definition template: def function_name(param1\]
    \[param2=default, *args, **kwargs):\]
  2. \[Return statement: return expression (if absent\]
    \[returns None)\]
  3. \[Lambda template: lambda arguments: expression\]
  4. \[Mathematical mapping notation: f: X -> Y (each input x in X maps to an output f(x) in Y)\]
  5. \[Typical usage pattern: result = function_name(arguments) (call and store return value)\]
  6. \[Recursion pattern: f(n) = base_value if base case\]
    \[else combine(n\]
    \[f(n-1))\]
💻13

Function Parameters and Types

📐 MATHEMATICAL FORMULA / THEOREM

Function Parameters and Types

Key Point: Function signature template: def func(positional, default=value, *args, **kwargs):

What is a parameter? A parameter is a name listed in a function definition. An argument is the actual value passed to the function when it is called. Functions can accept different kinds of parameters to make them flexible and reusable.

Common parameter types in Python:

  • Positional (required) parameters: Values must be supplied in the correct order when calling the function.
    Example signature: def add(a, b):
  • Default parameters: Have a default value used when the caller omits that argument.
    Example signature: def greet(name, msg='Hello'):
  • Keyword arguments: Caller names the parameter when passing a value; order can change.
    Call example: greet(msg='Hi', name='Riya')
  • Variable-length positional arguments (*args): Collect extra positional arguments into a tuple.
    Example signature: def total(*numbers):
  • Variable-length keyword arguments (**kwargs): Collect extra keyword arguments into a dictionary.
    Example signature: def info(**details):

Parameter order rules (practical guidance): required (positional) parameters first, then default parameters, then *args, then keyword-only parameters (if used), and finally **kwargs. Also, you cannot place a non-default parameter after a default parameter.

Passing behaviour (mutability): Python uses a model often described as "pass-by-object-reference". Mutable objects (like lists, dictionaries) can be changed inside a function and those changes are visible to the caller. Immutable objects (like integers, strings, tuples) cannot be altered in place — reassigning a parameter name inside the function does not change the caller's variable.

Important caveat about default parameters: Default parameter values are evaluated once at function definition time. Using a mutable object (like a list) as a default can lead to unexpected shared state between calls. Use None and create a new object inside the function if needed.

Small code examples:

# positional and default
def power(base, exponent=2):
    return base ** exponent

# variable-length
def summarize(*values):
    return sum(values)

# keyword arguments
def student(name, **marks):
    return name, marks

# mutable default pitfall (avoid this)
def append_bad(item, lst=[]):
    lst.append(item)
    return lst

# safe version
def append_safe(item, lst=None):
    if lst is None:
        lst = []
    lst.append(item)
    return lst

Why this matters in real life: Function parameter types let you design flexible APIs: optional settings with defaults, accept any number of data inputs, or capture named configuration options. Understanding mutability prevents bugs when collecting results across multiple calls.

📌 Examples
  • 1) Positional & default: def bill(amount, tax_rate=0.05): return amount + amount*tax_rate. Call: bill(100) -> 105
  • 2) Keyword args: def send_email(to, subject, cc=None): ... Call: send_email(subject='Exam', to='student@example.com')
  • 3) *args for variable items: def total_marks(*marks): return sum(marks). Call: total_marks(80, 75, 90) -> 245
  • 4) **kwargs for flexible student record: def add_student(name, **details): print(name, details). Call: add_student('Asha', age=16, grade='XI')
  • 5) Mutable default pitfall: append_bad(1) -> [1]; append_bad(2) -> [1,2] (unexpected). Use append_safe instead to avoid shared list.
🧮 Formulas
  1. \[Function signature template: def func(positional\]
    \[default=value, *args, **kwargs):\]
  2. \[Rule: non-default parameters cannot follow default parameters (def f(a\]
    \[b=2\]
    \[c) is invalid).\]
  3. \[Default evaluation: default_value is evaluated once at definition time\]
    \[not at each call.\]
  4. \[Mutability rule: If parameter object is mutable\]
    \[in-place modifications inside function affect caller's object\]
    \[reassigning names does not.\]
💻14

Anonymous Functions and Recursion

📐 MATHEMATICAL FORMULA / THEOREM

Anonymous Functions and Recursion

Key Point: Factorial: n! = n × (n-1)! with base 0! = 1

Anonymous Functions (lambda)

Anonymous functions are small one-line functions defined without a name using the lambda keyword. They are used for short operations where writing a full def function is unnecessary.

Syntax: lambda arguments: expression

Characteristics:

  • Single expression only (the expression's value is returned).
  • Often used with functions like map(), filter(), sorted(), and reduce().
  • Useful for short throwaway functions, key functions in sorting, or functional-style programming.

Example usage (HTML code block):

# square using lambda
square = lambda x: x * x
print(square(5))  # Output: 25

# using with map to square a list
nums = [1, 2, 3, 4]
squares = list(map(lambda x: x*x, nums))  # [1, 4, 9, 16]

Common higher-order uses

  • map(function, iterable) — apply function to each item.
  • filter(function, iterable) — keep items where function(item) is True.
  • sorted(iterable, key=function) — sort using function(item) as key.
  • functools.reduce(function, iterable) — accumulate values using function.

Recursion

Recursion is a technique where a function calls itself to solve smaller instances of the same problem. Each recursive function must have:

  • Base case: a condition that stops further recursion.
  • Recursive case: the part where the function calls itself with a smaller/simpler input.

Recursion uses the call stack: each call is pushed onto the stack until the base case is reached, then calls return in reverse order.

Example: factorial n! (= 1×2×...×n)

def factorial(n):
    if n == 0 or n == 1:   # base case
        return 1
    else:
        return n * factorial(n-1)  # recursive call

print(factorial(5))  # Output: 120

Example: Fibonacci sequence (simple recursive form)

def fib(n):
    if n == 0:
        return 0
    if n == 1:
        return 1
    return fib(n-1) + fib(n-2)

print(fib(6))  # Output: 8

Important points

  • Always ensure a correct base case to avoid infinite recursion (which leads to RecursionError in Python).
  • Python has a recursion depth limit (default ~1000). It can be changed with sys.setrecursionlimit() but raising it carelessly can cause stack overflow.
  • Recursive solutions can be elegant and easy to reason about for divide-and-conquer problems (e.g., tree traversal, quicksort), but sometimes iterative solutions are more efficient.
  • Memoization (caching results) can turn exponential recursive algorithms (like naive Fibonacci) into linear-time algorithms.
  • Python does not optimize tail recursion, so tail-recursive styles do not get automatic stack savings.

Comparison & complexity (intuition)

  • Linear recursion (one recursive call per call), e.g., factorial or summing a list: time O(n), space O(n) due to stack.
  • Binary recursion (two calls per call), e.g., naive Fibonacci: time O(2^n) (exponential), space O(n) (stack depth = n).

Real-life analogies

  • Recursive: Like nested dolls — to open the biggest doll you open the next smaller one and repeat until the smallest; then you close them in reverse order. Each doll corresponds to a call on the stack.
  • Anonymous function: A sticky note with a short instruction used once and thrown away — quick and temporary.

Practical tips for students

  • Use lambda for short, simple functions (single expression) — not for complex logic.
  • When recursion is natural (trees, divide-and-conquer), write clear base cases and test small inputs first.
  • If recursion is too slow (like Fibonacci), consider memoization or iterative solutions.

📌 Examples
  • Lambda to double numbers: nums = [1,2,3]; doubled = list(map(lambda x: x*2, nums)) # [2,4,6]
  • Filter odd numbers: odds = list(filter(lambda x: x%2==1, [1,2,3,4,5])) # [1,3,5]
  • Sort by length: words = ['apple','pie','banana']; words_sorted = sorted(words, key=lambda w: len(w)) # ['pie','apple','banana']
  • Reduce to product (requires functools.reduce): from functools import reduce; product = reduce(lambda a,b: a*b, [2,3,4]) # 24
  • Recursive factorial: def factorial(n): return 1 if n<=1 else n*factorial(n-1); factorial(5) # 120
  • Recursive Fibonacci (naive): def fib(n): return n if n<2 else fib(n-1)+fib(n-2); fib(6) # 8
🧮 Formulas
  1. \[Factorial: n! = n × (n-1)! with base 0! = 1\]
  2. \[Fibonacci recurrence: F(n) = F(n-1) + F(n-2)\]
    \[with F(0)=0\]
    \[F(1)=1\]
  3. \[Time complexity examples: linear recursion T(n)=T(n-1)+O(1) ⇒ O(n)\]
    \[binary recursion T(n)=T(n-1)+T(n-2)+O(1) ⇒ O(φ^n) ~ O(2^n) (exponential).\]
  4. \[Map/Filter complexity: O(n) where n is number of elements processed\]
⚖️15

Strings — Basics and Operations

💻 COMPUTER SCIENCE / IT

Strings — Basics and Operations

Key Point: Indexing: s[i] (0-based). Negative: s[-1] is last character.

What is a string? A string is an ordered sequence of characters enclosed in quotes, e.g. 'Hello', "Welcome". In Python a string is an immutable sequence type used to store text.

Creation: Use single ('...'), double ("..."), or triple quotes ('''...''' or """...""") for multi-line text.

Key properties

  • Immutable: Once created, characters in a string cannot be changed. Operations that seem to modify a string actually create a new string.
  • Indexed & ordered: Characters have positions starting from 0. Negative indices count from the end: -1 is the last character.

Core operations

  • Indexing: s[i] returns the character at index i (0-based). Example: s[0] is the first char.
  • Slicing: s[start:stop:step] extracts a substring from index start to stop-1, stepping by step. Omitting start or stop uses defaults (start=0, stop=len(s)).
  • Concatenation: s1 + s2 joins two strings.
  • Repetition: s * n repeats s n times.
  • Membership: 'sub' in s returns True if substring 'sub' occurs in s.
  • Length: len(s) returns number of characters.

Common string methods (short list)

  • Case: s.lower(), s.upper(), s.capitalize(), s.title()
  • Whitespace: s.strip(), s.lstrip(), s.rstrip()
  • Search & replace: s.find('sub'), s.index('sub'), s.count('sub'), s.replace('old', 'new')
  • Split & join: s.split(sep) -> list of parts; sep.join(list) -> string
  • Checks: s.isalpha(), s.isdigit(), s.isalnum(), s.startswith(prefix), s.endswith(suffix)

Formatting: Build strings with placeholders: old style: 'Hello %s' % name; str.format(): 'Hi {0}'.format(name); f-strings (Python 3.6+): f'Hi {name}'.

Escapes & raw strings: Use backslash escapes for special chars: '\n' newline, '\t' tab, '\\' backslash. Prefix with r to make raw string (r'C:\path') so backslashes are literal.

Why immutability matters: Because strings are immutable, operations produce new objects. For many small concatenations use list-join pattern for efficiency: ''.join(parts).

Examples in one line: s = 'Hello'; s[1] -> 'e'; s[1:4] -> 'ell'; 'ab' * 3 -> 'ababab'; 'py' in 'python' -> True.

Common pitfalls: IndexError for out-of-range indexing, using replace without assigning result (s.replace(...) returns new string), confusing str.index (throws ValueError if not found) vs str.find (returns -1).

📌 Examples
  • Username extraction: full = 'john.doe@example.com'; username = full.split('@')[0] # 'john.doe'
  • Greeting template: name = 'Anita'; msg = f'Hello, {name}! Welcome.' # 'Hello, Anita! Welcome.'
  • Slicing for substring: s = 'CBSE_INFORMATICS'; sub = s[5:15] # extracts characters from index 5 to 14
  • Reverse a string: s[::-1] # returns the string reversed (slice with step -1)
  • Efficient joining: words = ['This','is','IP']; sentence = ' '.join(words) # 'This is IP'
🧮 Formulas
  1. \[Indexing: s[i] (0-based)\]
    \[Negative: s[-1] is last character.\]
  2. \[Slicing: s[start:stop:step] — substring from start to stop-1\]
    \[step is stride.\]
  3. \[Concatenation: s3 = s1 + s2\]
  4. \[Repetition: s_repeat = s * n\]
  5. \[Membership: 'sub' in s returns True/False\]
  6. \[Length: n = len(s)\]
💻16

Strings — Methods and Formatting

💻 COMPUTER SCIENCE / IT

Strings — Methods and Formatting

Key Point: Indexing: s[i] (i from 0 to len(s)-1); negative index s[-1] is last character

What is a string? A string is an ordered sequence of characters enclosed in quotes (single, double or triple) used to represent text. Example: 'Hello', "World".

Immutability: Strings are immutable — once created their contents cannot be changed. Operations that seem to modify a string actually create a new string.

Indexing and slicing: Characters in a string are accessed using indices. First character index = 0, last = -1. Slicing extracts substrings using the notation s[start:stop:step] (stop is exclusive).

s = 'python'
# indexing
s[0]        # 'p'
s[-1]       # 'n'
# slicing
s[1:4]      # 'yth'
s[::2]      # 'pto'

Basic operations: concatenation (+), repetition (*), membership (in), length (len(s)), iteration (for char in s).

Common string methods (categories):

  • Case conversion: lower(), upper(), title(), capitalize(), swapcase()
  • Trimming/padding: strip(), lstrip(), rstrip(), zfill(), rjust(), ljust(), center()
  • Search & replace: find(), index(), rfind(), count(), replace()
  • Split & join: split(), rsplit(), splitlines(), join()
  • Tests: isalpha(), isdigit(), isalnum(), isspace(), islower(), isupper()
  • Formatting helpers: format(), f-strings, old-style % operator

Formatting strings (why): Formatting is used to produce readable text, align columns, show numeric precision (currency, percentages), build templates and reports.

Three common formatting styles:

  1. Old-style: 'Name: %s Age: %d' % (name, age)
  2. str.format(): 'Name: {:10} Score: {:.2f}'.format(name, score)
  3. f-strings (recommended in Python 3.6+): f'Name: {name:10} Score: {score:.2f}'

Format mini-language (summary): an expression like {:[fill][align][width][,][.precision][type]} controls output. Examples:

  • {:10} — minimum width 10 (right by default)
  • {:<10}, {:^10}, {:>10} — left, center, right alignment
  • {:0>5} — pad with zeros to width 5
  • {:.2f} — floating point with 2 decimals
  • {:,} — include thousand separators (e.g., 1,000)
  • {:b}, {:x}, {:o} — binary, hex, octal formatting

Practical notes:

  • Use strip() to remove extra spaces from user input before validation.
  • Use split() and join() to parse or build CSV/text lines.
  • Use formatting to align reports or print tables in console applications.

Small example (receipt line):

item = 'Notebook'
price = 79.5
print(f'{item:20} {price:8.2f}')
# Notebook             79.50

These methods and formatting capabilities form the backbone of text processing in Python and are heavily used in data cleaning, reporting, user interfaces and file I/O.

📌 Examples
  • Normalize emails (lowercase, strip spaces): raw = ' Student@Example.COM\n'; clean = raw.strip().lower() # 'student@example.com'
  • Split and join to process CSV line: line = 'apple,banana,kiwi'; fruits = line.split(','); new_line = ';'.join(fruits) # 'apple;banana;kiwi'
  • Validate numeric input: s = '12345'; if s.isdigit(): n = int(s)
  • Search and replace in text: text.replace('colour', 'color') # useful for standardizing spellings
  • Format a scorecard row: name='Anita'; score=95.678; print(f'{name:10} | {score:6.2f}') # aligns name and shows score with 2 decimals
  • Create zero-padded identifiers: id = '23'; print(id.zfill(5)) # '00023' (useful for invoice or roll numbers)
🧮 Formulas
  1. \[Indexing: s[i] (i from 0 to len(s)-1)\]
    \[negative index s[-1] is last character\]
  2. \[Slicing: s[start:stop:step] — returns substring from start to stop-1 stepping by step (defaults: start=0\]
    \[stop=len(s)\]
    \[step=1)\]
  3. \[Length: n = len(s)\]
  4. \[Concatenation: s3 = s1 + s2\]
    \[Repetition: s2 = s1 * k\]
  5. \[Format placeholder pattern: {:[fill][align][width][,][.precision][type]} (examples: '{:>10}', '{:.2f}', '{:0>4d}', '{:,}')\]
  6. \[Old-style formatting: 'Hello %s\]
    \[score=%d' % (name\]
    \[score) — newer code prefers str.format() or f-strings\]
⚖️17

Lists — Sequences and Operations

💻 COMPUTER SCIENCE / IT

Lists — Sequences and Operations

Key Point: Creation: l = [a, b, c] or l = list(iterable)

What is a list? A list in Python is an ordered sequence of items (elements) enclosed in square brackets []. Lists can store items of different types (heterogeneous), are indexed (starting at 0), and are mutable (you can change their elements after creation). Lists can also be nested (a list can contain other lists).

Key characteristics:

  • Ordered: position of each element is fixed unless you change the list.
  • Indexed: elements accessed by integer indices (0, 1, 2, ...).
  • Mutable: individual elements can be modified, added, or removed.
  • Heterogeneous: elements may be of different data types (numbers, strings, objects).
  • Dynamic size: length grows or shrinks at runtime.

Creating lists: l = [1, 2, 3] or l = list(). You can create an empty list and then add items.

Indexing and negative indices: Access elements with l[0], l[1], etc. Negative indices count from the end: l[-1] is the last element, l[-2] the second last.

Slicing: Get a sub-list using l[start:stop] (start included, stop excluded). General form: l[start:stop:step]. Examples: l[1:4], l[:3], l[::2].

Common sequence operations (basic operators and built-in functions): + (concatenate two lists), * (repeat), in (membership test), len(l) (length), min(l), max(l) (for comparable items), and sorted(l) (returns a sorted copy).

Important list methods (mutating operations):

  • l.append(x) — add x at end.
  • l.extend(iterable) — append all elements from iterable.
  • l.insert(i, x) — insert x at index i.
  • l.remove(x) — remove first occurrence of x.
  • l.pop() or l.pop(i) — remove and return last or i-th element.
  • del l[i] — delete element at index i; del l[a:b] deletes a slice.
  • l.clear() — remove all elements.
  • l.index(x) — return index of first x (error if not found).
  • l.count(x) — number of occurrences of x.
  • l.sort() — sort list in place; sorted(l) returns a sorted copy.
  • l.reverse() — reverse elements in place.
  • l.copy() — shallow copy of the list.

Mutability and aliasing: Assigning b = a does not copy; both names refer to same list. Use b = a.copy() (shallow) or import copy; copy.deepcopy(a) for independent nested copies.

Nested lists: Represent matrices or tables. Example: m = [[1,2,3],[4,5,6]]. Access element row r, column c by m[r][c].

Iteration: Use for item in l: to traverse elements. List comprehensions provide concise creation: [x*x for x in range(5)].

Performance notes (important to remember): indexing is O(1). Appending is amortized O(1). Inserting or removing in middle, searching, or concatenating large lists are O(n) operations (n = list length). Slicing makes a new list (cost proportional to slice length).

CBSE tip: Understand examples by writing small programs that create, modify, and print lists — test append vs extend, and observe how negative indexing and slicing work.

📌 Examples
  • Shopping list: ['milk', 'bread', 'eggs'] — add with append('butter'), check membership with 'eggs' in shopping_list, remove with remove('bread').
  • Playlist: songs = ['Song A', 'Song B', 'Song C']; play a slice for first two songs with songs[:2]; repeat an intro jingle 3 times with intro = ['jingle']; intro * 3.
  • Class attendance register (nested list): attendance = [['Alice', 'P'], ['Bob', 'A'], ['Cathy', 'P']] — access Bob's status with attendance[1][1].
  • Matrix (2×3) used for seating plan: seats = [[1,2,3],[4,5,6]] — change seat 5 to 50 with seats[1][1] = 50.
  • Building a list with comprehension: squares = [x*x for x in range(1, 6)] results in [1, 4, 9, 16, 25].
🧮 Formulas
  1. \[Creation: l = [a\]
    \[b\]
    \[c] or l = list(iterable)\]
  2. \[Indexing: l[i] (0-based)\]
    \[negative: l[-1] == last element\]
  3. \[Slicing: l[start:stop:step] (start included\]
    \[stop excluded)\]
  4. \[Concatenation: l1 + l2\]
  5. \[Repetition: l * n\]
  6. \[Membership: x in l (returns True/False)\]
💻18

Tuples

💻 COMPUTER SCIENCE / IT

Tuples

Key Point: len(t) -> number of elements in tuple t

What is a tuple?
A tuple is an ordered, immutable collection of items in Python. Tuples store a fixed sequence of values which can be of different data types (int, float, string, another tuple, etc.). Because they are immutable, once created their elements cannot be changed, added or removed.

How to create tuples

# empty tuple
t0 = ()
# tuple with elements
t1 = (1, 2, 3)
# parentheses are optional in many contexts (comma defines tuple)
t2 = 4, 5, 6
# single-element tuple requires a trailing comma
t3 = (7,)
# nested tuple
t4 = (1, (2, 3), 'a')

Key properties

  • Ordered: elements have fixed positions (indexes start at 0).
  • Immutable: cannot change elements after creation (no append/pop/insert).
  • Heterogeneous: can contain mixed data types.
  • Hashable if all elements are hashable: can be used as dictionary keys or set elements.

Common operations

# indexing and negative indexing
a = (10, 20, 30)
print(a[0])    # 10
print(a[-1])   # 30

# slicing
print(a[0:2])  # (10, 20)

# concatenation and repetition
b = (40, 50)
print(a + b)   # (10, 20, 30, 40, 50)
print(a * 2)   # (10, 20, 30, 10, 20, 30)

# membership, length, methods
print(20 in a)        # True
print(len(a))         # 3
print(a.count(20))    # number of occurrences
print(a.index(30))    # index of first occurrence

# packing and unpacking
coord = (5, 6)
x, y = coord

Why use tuples (advantages)

  • Immutability makes data safer (no accidental changes).
  • Tuples can be used as keys in dictionaries when needed.
  • Often slightly faster and more memory-efficient than lists for fixed data.

Class 11 tips
Remember the single-element tuple syntax (x,) and that parentheses can be omitted in many contexts when commas separate values. Use tuples when you need an ordered collection that should not change (for example, coordinates, fixed records, constant configurations).

📌 Examples
  • Coordinates: location = (12.9716, 77.5946) # (latitude, longitude)
  • RGB color: color = (255, 128, 0) # (R, G, B) - fixed 3 values
  • Date as tuple: date = (2025, 12, 25) # (year, month, day) - immutable record
  • Dictionary key: mapping[(user_id, resource_id)] = 'access' # tuple used as key
  • Packing/unpacking: point = (3, 4); x, y = point # unpack into variables
🧮 Formulas
  1. \[len(t) -> number of elements in tuple t\]
  2. \[t[i] -> element at index i (0-based)\]
    \[t[-1] -> last element\]
  3. \[t[i:j] -> slice from index i to j-1 (returns a tuple)\]
  4. \[t1 + t2 -> concatenation of tuples\]
  5. \[t * n -> repetition (n times)\]
  6. \[x in t -> True if x is an element of t\]
💻19

Dictionaries

💻 COMPUTER SCIENCE / IT

Dictionaries

Key Point: len(d) — number of key-value pairs in dictionary d.

What is a dictionary? A dictionary in Python is an unordered (in older versions), mutable collection of key-value pairs. Each value is accessed using a unique key. Dictionaries are implemented as hash tables, providing very fast lookup, insertion and deletion on average.

Basic properties

  • Syntax: a dictionary literal uses curly braces: {key1: value1, key2: value2}.
  • Keys must be immutable and hashable (e.g., numbers, strings, tuples). Values can be any object (including lists or other dictionaries).
  • Mutable: you can add, update or remove items after creation.
  • From Python 3.7 onward, dictionaries preserve insertion order.

Creating dictionaries

# literal
d = {'apple': 3, 'banana': 5}

# from pairs using dict()
pairs = [('a', 1), ('b', 2)]
d2 = dict(pairs)

# fromkeys
keys = ['x','y','z']
d3 = dict.fromkeys(keys, 0)

# comprehension
squares = {n: n*n for n in range(1,6)}

Accessing and modifying

value = d['apple']         # access (KeyError if missing)
value = d.get('apple', 0)   # safe access with default

# add/update
d['orange'] = 7

# remove
d.pop('banana')             # remove by key
last = d.popitem()          # remove and return arbitrary pair (LIFO in 3.7+)

Common methods

  • keys(), values(), items() — iterate over keys, values, or key-value tuples.
  • update(other_dict) — merge another dict (overwrites duplicates).
  • clear() — remove all items; copy() — shallow copy.
  • setdefault(key, default) — return value if key exists, otherwise set it to default and return default.

Iteration patterns

for k in d:             # iterates keys
    print(k, d[k])

for k, v in d.items():   # iterates key-value pairs
    print(k, v)

Nested dictionaries are dictionaries that contain other dictionaries as values. Useful to represent structured data (e.g., student -> {name, age, marks}).

When to use a dictionary? Use dictionaries when you need fast lookup by a unique key (e.g., mapping IDs to records, frequency counts, configuration settings). For ordered indexed sequences use lists; for simple key-value pairs where keys are ordered and frequently sliced, consider pandas or OrderedDict (legacy).

Notes: because dictionaries are mutable, avoid using them as keys in other dicts or sets. Keys must be hashable. For copying nested structures, use copy.deepcopy to avoid shared references.

📌 Examples
  • Phone directory: map names to phone numbers. Example: {'Alice': '9876543210', 'Bob': '9123456780'}. Lookup is direct: phone = phonebook['Alice'] or phonebook.get('Eve','Not found').
  • Student records (nested dict): {101: {'name':'Priya', 'age':16, 'marks':{'Math':95, 'Eng':88}}, 102: {...}}. Access Priya's Math: students[101]['marks']['Math'].
  • Counting word frequency in a sentence: text = 'to be or not to be' freq = {} for w in text.split(): freq[w] = freq.get(w, 0) + 1 # freq -> {'to':2, 'be':2, 'or':1, 'not':1}
  • Inventory management: items mapped to quantities and prices. Example: inventory = {'pen': {'qty': 50, 'price': 5}, 'book': {'qty': 20, 'price': 60}}. Update qty: inventory['pen']['qty'] -= 5.
  • Merging dictionaries: d3 = {**d1, **d2} or d1.update(d2). If keys clash, later value overwrites earlier one.
🧮 Formulas
  1. \[len(d) — number of key-value pairs in dictionary d.\]
  2. \[Membership test: key in d returns True if key exists (checks keys only).\]
  3. \[Merging (creating new dict): merged = {**d1, **d2} (d2 values overwrite d1 for same keys).\]
  4. \[Average time complexities (hash table behavior): lookup O(1)\]
    \[insertion O(1)\]
    \[deletion O(1)\]
    \[Worst case can degrade to O(n) but is rare.\]
  5. \[dict.fromkeys(iterable\]
    \[value) creates a dictionary with given keys all set to value.\]
💻20

Type Conversions between Collections

💻 COMPUTER SCIENCE / IT

Type Conversions between Collections

Key Point: list(iterable) -> list (mutable sequence)

What it is
Type conversions between collections in Python means converting data from one collection type to another — for example, from a list to a set, tuple to list, or from a list of pairs to a dictionary. Conversions are done using constructors and helper methods so you can use the strengths of each collection type (mutability, uniqueness, ordering, mapping).

Why and when to convert

  • To remove duplicates: convert a list to a set.
  • To make sequence immutable: convert list to tuple.
  • To get index access: convert set to list or tuple.
  • To build key->value mappings: convert a list of (key, value) pairs to a dict.
  • To iterate keys/values: convert dict to list (of keys), list(dict.values()), or list(dict.items()).

Common conversion functions and rules

  • list(iterable) → creates a mutable sequence. Example: list('abc')['a','b','c'].
  • tuple(iterable) → creates an immutable sequence.
  • set(iterable) → creates an unordered collection of unique, hashable elements (duplicates removed).
  • dict(mapping_or_seq_of_pairs) → creates a mapping. Passing a sequence of (key, value) pairs builds a dict.
  • dict.keys(), dict.values(), dict.items() return view objects; wrap with list(...) or tuple(...) to convert to a sequence.

Important behavior and edge-cases

  • Converting a list to a set removes duplicates but does not preserve order. If you need to remove duplicates while preserving original order, use list(dict.fromkeys(my_list)) or an OrderedDict approach.
  • Sets and dict keys require hashable elements. You cannot create a set of lists (lists are unhashable), but you can create a set of tuples.
  • Converting a dict to a list directly (i.e. list(my_dict)) returns a list of keys.
  • Order: dict preserves insertion order (Python 3.7+), set is unordered; converting between them may change order.

Short code examples

# list -> set (remove duplicates)
my_list = [1, 2, 2, 3]
my_set = set(my_list)   # {1, 2, 3}

# set -> list (indexable)
ordered_list = list(my_set)  # order may vary

# list -> tuple (make immutable)
my_tuple = tuple(my_list)    # (1, 2, 2, 3)

# tuple -> list (modify elements)
new_list = list(my_tuple)

# list of pairs -> dict
pairs = [('roll1', 85), ('roll2', 90)]
marks = dict(pairs)   # {'roll1': 85, 'roll2': 90}

# dict -> list of keys / values / items
keys = list(marks)            # ['roll1', 'roll2']
values = list(marks.values()) # [85, 90]
items = list(marks.items())   # [('roll1', 85), ('roll2', 90)]

# remove duplicates while keeping order
uniq_ordered = list(dict.fromkeys([3,1,3,2]))  # [3, 1, 2]
📌 Examples
  • Remove duplicate student IDs: my_ids = ['S1','S2','S1'] -> unique_ids = set(my_ids) gives {'S1','S2'} (order not guaranteed).
  • Keep insertion order while removing duplicates: ids = ['S1','S2','S1'] -> unique_ordered = list(dict.fromkeys(ids)) -> ['S1','S2'].
  • CSV row to fields and then to tuple: row = 'Alice,20,Physics' -> fields = row.split(',') -> ['Alice','20','Physics'] -> record = tuple(fields).
  • Make scores immutable for safety: scores = [85,90,78] -> scores_fixed = tuple(scores).
  • Create map of roll->marks from list of pairs: pairs = [('r1',80),('r2',90)] -> marks = dict(pairs) -> marks['r1'] == 80.
  • Convert dict to list to sort by key: keys_sorted = sorted(list(marks)) or items_sorted = sorted(marks.items(), key=lambda x: x[0]).
🧮 Formulas
  1. \[list(iterable) -> list (mutable sequence)\]
  2. \[tuple(iterable) -> tuple (immutable sequence)\]
  3. \[set(iterable) -> set (unordered unique elements)\]
  4. \[dict(seq_of_pairs) -> dict (mapping from keys to values)\]
  5. \[list(dict_obj) -> list of keys\]
    \[list(dict_obj.values()) -> list of values\]
    \[list(dict_obj.items()) -> list of (key,value) pairs\]
  6. \[Remove duplicates (unordered): set(my_list)\]
    \[Preserve order while removing duplicates: list(dict.fromkeys(my_list))\]
💻21

Built-in Functions and Standard Library (Intro)

📐 MATHEMATICAL FORMULA / THEOREM

Built-in Functions and Standard Library (Intro)

Key Point: Factorial: n! = n × (n-1) × ... × 1 (use math.factorial(n))

Overview: In Python, built-in functions are ready-to-use functions provided by the language (no import required). The standard library is a collection of modules bundled with Python that provide additional functionality (math, random, datetime, os, json, statistics, etc.). Together they let you solve many common tasks quickly, reliably and with fewer lines of code.

Built-in functions (what and why):

  • Examples: print(), input(), len(), int(), float(), str(), type(), sum(), min(), max(), sorted(), abs(), round(), range(), pow(), divmod().
  • Called directly: len(my_list) or abs(-5). They live in the global/built-in namespace.
  • Use when you need common, well-tested operations (conversion, aggregation, introspection, I/O).

Standard library (modules):

  • Import syntax: import module, from module import name, import module as alias.
  • Common modules and purpose:
    • math — mathematical functions: sqrt, factorial, sin, cos, log
    • random — pseudo-random numbers: random(), randint(), choice(), shuffle()
    • datetime — dates and times
    • statistics — mean, median, mode, stdev
    • json, csv — data interchange
    • os, sys — operating system and interpreter interaction

How they differ:

  • Built-in functions are always available without import.
  • Standard-library functions live inside modules and require import.
  • Both are part of the Python ecosystem, tested and optimized—prefer them over writing low-level code.

Namespaces and calling: When you do import math, call math.sqrt(9). If you do from math import sqrt, call sqrt(9) directly. Use aliases for convenience: import numpy as np (third-party).

Benefits: Reliability, readability, less code, portability. Using library functions reduces bugs and improves performance.

Small code examples:

# built-in
nums = [2, 5, 1]
print(len(nums), sum(nums), max(nums))

# standard library
import math
print(math.sqrt(25), math.factorial(4))

import random
print(random.randint(1, 10))

from datetime import date
print(date.today())

Teaching tips: Show direct calls to built-ins, then show import and use of modules. Ask students to replace manual code (e.g., computing average via loop) with statistics.mean() to highlight advantages.

📌 Examples
  • 1) Using built-ins: ``nums = [3,7,2]; print('Length =', len(nums)); print('Sum =', sum(nums));`` — quick aggregation.
  • 2) Using math module: ``import math x = 16 print(math.sqrt(x)) # 4.0 print(math.factorial(5)) # 120`` — use tested math routines.
  • 3) Random sample for real-life: ``import random candidates = ['Asha','Bala','Chirag'] winner = random.choice(candidates) print(winner)`` — useful for fair selection/draws.
  • 4) Date/time for timestamp: ``from datetime import datetime now = datetime.now() print(now.strftime('%Y-%m-%d %H:%M:%S'))`` — logging events with timestamp.
  • 5) Simple data conversion: ``s = '123' i = int(s) print(i + 5) # use built-in conversion functions``
  • 6) Using statistics for class marks: ``import statistics marks = [45, 67, 78, 82] print(statistics.mean(marks), statistics.median(marks))``
🧮 Formulas
  1. \[Factorial: n! = n × (n-1) × ... × 1 (use math.factorial(n))\]
  2. \[Power: a^b = pow(a\]
    \[b) or a**b (built-in pow() or operator)\]
  3. \[Average (mean): mean = (x1 + x2 + ... + xn) / n (use statistics.mean(list))\]
  4. \[Median: middle value after sorting (use statistics.median(list))\]
  5. \[Combinations: nCr = n! / (r! (n-r)!) (compute with math.factorial or math.comb in Python 3.8+)\]
  6. \[Permutations: nPr = n! / (n-r)! (compute with math.factorial or math.perm in Python 3.8+)\]
⚖️22

File Handling — Basic Operations

💻 COMPUTER SCIENCE / IT

File Handling — Basic Operations

Key Point: open(filename, mode, encoding=None) # e.g., open('file.txt', 'r', encoding='utf-8')

What is File Handling?
File handling means creating, opening, reading, writing, updating and closing files from a program so that data can be stored permanently. In Python, file handling is done using the built-in open() function which returns a file object. Files may be text or binary.

Basic operations

  • Open: f = open(filename, mode, encoding=...). The mode decides whether you read, write or append. Common modes: 'r' (read), 'w' (write, truncates), 'a' (append), 'x' (create), 'b' (binary), '+' (update read/write).
  • Read: f.read() (all), f.readline() (one line), f.readlines() (list of lines). Use an integer argument to limit bytes/characters: f.read(10).
  • Write: f.write(string) writes a string to the file; f.writelines(list_of_strings) writes multiple lines (no automatic newlines).
  • Move file pointer: f.tell() gives current position; f.seek(offset, whence) moves pointer. whence can be 0 (start), 1 (current), 2 (end).
  • Close: f.close() frees resources. Prefer with open(...) as f: to auto-close even on errors.

Important behaviours

  • Opening in 'w' truncates (clears) existing file. Use 'a' to preserve content and add at the end.
  • Binary mode 'b' reads/writes bytes; text mode decodes/encodes using encoding (default UTF-8 in many cases).
  • Use exception handling (try/except) or a with block to handle errors such as FileNotFoundError or IOError.

Why it matters (real-life uses): saving student marks, logging application activities, reading configuration, processing CSV/JSON data, storing uploaded files, etc.

Short example (read and write)

# Write
with open('students.txt', 'w', encoding='utf-8') as f:
    f.write('Alice,85\nBob,78\n')

# Read
with open('students.txt', 'r', encoding='utf-8') as f:
    data = f.read()
    print(data)

Best practices

  • Use with to auto-close files.
  • Specify encoding when reading/writing text to avoid platform differences.
  • Use appropriate mode: 'r' for reading, 'a' for appending logs, 'b' when handling images or other binary files.
📌 Examples
  • 1) Read whole file: with open('notes.txt', 'r', encoding='utf-8') as f: text = f.read() 2) Read line-by-line (memory friendly): with open('large.txt', 'r', encoding='utf-8') as f: for line in f: process(line) 3) Append to a file (useful for logs): with open('app.log', 'a', encoding='utf-8') as log: log.write('2025-12-18: Started process\n') 4) Binary write (saving an image): with open('image.jpg', 'rb') as src: data = src.read() with open('copy.jpg', 'wb') as dst: dst.write(data) 5) Using seek and tell: with open('data.txt', 'r', encoding='utf-8') as f: print(f.tell()) # position 0 chunk = f.read(10) print(f.tell()) # position after reading 10 chars f.seek(0) # back to start
  • 6) Handle missing file with exception: try: with open('missing.txt', 'r') as f: print(f.read()) except FileNotFoundError: print('File not found.')
  • 7) Write multiple lines: lines = ['Name,Marks\n', 'Alice,90\n', 'Bob,82\n'] with open('marks.csv', 'w', encoding='utf-8') as f: f.writelines(lines)
🧮 Formulas
  1. \[open(filename\]
    \[mode\]
    \[encoding=None) # e.g.\]
    \[open('file.txt', 'r'\]
    \[encoding='utf-8')\]
  2. \[Modes: 'r' (read), 'w' (write\]
    \[truncate), 'a' (append), 'x' (create), 'b' (binary), 't' (text), '+' (read/write)\]
    \[Combine: 'rb', 'w+'\]
    \[etc.\]
  3. \[f.read(n) # read up to n characters/bytes\]
    \[f.read() reads all\]
  4. \[f.readline() # read next line\]
  5. \[f.readlines() # read all lines as a list\]
  6. \[f.write(string) # write string (must be bytes in binary mode)\]
💻23

Errors, Exceptions and Debugging

💻 COMPUTER SCIENCE / IT

Errors, Exceptions and Debugging

Key Point: try-except-else-finally pattern: try: ... except SomeException as e: ... else: ... finally: ...

Overview
In programming, an error is a problem in code that prevents correct execution. An exception is a runtime event indicating an error or unusual condition that can be caught and handled. Debugging is the process of finding and fixing errors or logical mistakes.

Types of Errors

  • Syntax Errors — mistakes in the program's grammar (e.g., missing colon, unmatched parenthesis). Caught before running the program.
  • Runtime Errors / Exceptions — occur during program execution (e.g., division by zero, file not found). These produce an exception and a stack trace.
  • Logical Errors — the program runs but gives incorrect results (e.g., wrong formula or wrong loop condition). Hardest to detect.

Exceptions in Python

Python has built-in exception types (ValueError, TypeError, IndexError, KeyError, ZeroDivisionError, FileNotFoundError, etc.). Exceptions form a hierarchy under BaseExceptionException. When an exception occurs, Python creates an exception object and prints a traceback showing the call stack.

Handling Exceptions

Use try / except to catch exceptions and handle them gracefully. Optionally use else to run code when no exception occurs and finally for cleanup that must run in all cases.

try:
    result = a / b
except ZeroDivisionError:
    print("Cannot divide by zero")
else:
    print("Result:", result)
finally:
    print("Cleanup code runs always")

Raising and Custom Exceptions

You can raise an exception intentionally using raise, and define custom exceptions by subclassing Exception:

if age < 0:
    raise ValueError("Age cannot be negative")

class MyError(Exception):
    pass

Debugging Techniques

  • Use print/logging statements to inspect variable values and control flow.
  • Use an interactive debugger (IDE or pdb) to set breakpoints, step through code, and inspect the call stack.
  • Read tracebacks carefully — they give the file, line number, and exception message.
  • Write small test cases (unit tests) and validate expected outputs.
  • Use assertions (assert condition, "msg") to document and check assumptions during development.
  • Keep functions small and modular so bugs are easier to isolate.

Best Practices

  • Catch specific exceptions, not a bare except:, so you don't hide bugs.
  • Log exceptions with stack traces for later analysis (use the logging module).
  • Clean up resources (files, network connections) in finally or use context managers (with).
  • Validate input early to prevent exceptions (e.g., check for zero before dividing).

Example trace (short): Traceback (most recent call last): File "main.py", line 10, in <module> result = a/b ZeroDivisionError: division by zero — shows where the error occurred and its type.

📌 Examples
  • Division by zero: a = 10; b = 0; result = a / b -> ZeroDivisionError. Fix: check b != 0 or handle with try/except.
  • File not found: open('data.txt') when file missing -> FileNotFoundError. Fix: use try/except or check os.path.exists before opening.
  • Index error: lst = [1,2]; access lst[5] -> IndexError. Fix: validate index or iterate safely.
  • Value error from input: int('abc') -> ValueError. Fix: validate or handle conversion inside try/except.
  • Key error in dictionary: d = {'a':1}; d['b'] -> KeyError. Fix: use d.get('b') or handle exception.
  • Custom validation: raise ValueError('age must be positive') if input age &lt; 0 to stop invalid data early.
🧮 Formulas
  1. \[try-except-else-finally pattern: try: <code>...</code> except SomeException as e: <code>...</code> else: <code>...</code> finally: <code>...</code>\]
  2. \[Raise and custom: raise ExceptionType('message')\]
    \[class MyError(Exception): pass\]
  3. \[Assertion: assert condition, 'error message' (used for internal checks during development)\]
  4. \[Exception hierarchy snippet: BaseException -> Exception -> ArithmeticError -> ZeroDivisionError\]
  5. \[Resource handling pattern: with open('file') as f: <code>...</code> (automatically handles closing)\]
  6. \[Logging exception: import logging\]
    \[logging.exception('message') (records error + stack trace)\]
⌨️24

Program Design and Problem Solving

💻 COMPUTER SCIENCE / IT

Program Design and Problem Solving

Key Point: Average of N numbers: average = (sum of all numbers) / N

Overview: Program design and problem solving is a systematic process of converting a real-world problem into a working computer program. It emphasizes understanding the problem, devising an algorithm, representing it (pseudocode/flowchart), implementing in code (Python), and testing/debugging.

Key steps

  • Understand the problem — identify inputs, expected outputs, constraints, and edge cases.
  • Analyze — break the problem into smaller subproblems; decide data types and possible algorithms.
  • Design — create algorithm using stepwise refinement; write pseudocode and draw flowchart. Choose control structures (sequence, selection, iteration) and data structures (list, tuple, dictionary).
  • Implement — convert pseudocode into Python code, organize code into functions (modular design) for clarity and reuse.
  • Test and debug — use sample inputs (including edge cases), trace outputs, fix logic/syntax/runtime errors, use print/debugger and assertions.
  • Optimize and document — improve readability and efficiency, add comments and user instructions.

Design strategies & principles

  • Top-down design (decompose into modules) and bottom-up (build reusable components).
  • Stepwise refinement: iteratively refine a high-level step into detailed steps.
  • Use of functions to encapsulate tasks; single-responsibility principle for each function.
  • Handle errors and edge cases explicitly (input validation).

Pseudocode and flowcharts: Pseudocode uses plain-language structured steps (no syntax). Flowcharts use symbols (oval = start/end, parallelogram = input/output, rectangle = process, diamond = decision). Both help verify logic before coding.

Algorithm types & control structures: Sequential (straight steps), Selection (if/if-else/elif), Iteration (for, while). Common patterns: linear search, binary search (on sorted data), sorting (bubble, selection, insertion), accumulation (summing), and counting.

Correctness & complexity: Verify correctness by reasoning and testing. Consider time complexity (how running time grows with input size) and space complexity (extra memory used). Aim for clear, correct solutions first; then optimize if needed.

📌 Examples
  • Find average of N numbers: Input N and list of numbers → compute sum → average = sum / N → output average. (Use loop to accumulate and handle N=0 case.)
  • Largest of three numbers: Input a,b,c → use nested selection or pairwise comparison to determine max → output max. (Edge case: equal numbers.)
  • Grade calculator: Input marks for subjects and total → compute percentage = (total_obtained / total_max) * 100 → assign grade by range using if-elif-else.
  • Prime check for a number: Input n → if n<=1 not prime; else check divisibility from 2 to sqrt(n) → if any divisor found then composite else prime.
  • Fibonacci series up to N terms: Use iteration (or recursion) to generate sequence: start with 0,1 then next = prev1 + prev2; output list up to N.
  • Shopping bill with discounts: Read prices and quantities → compute subtotal by summing price*quantity → apply discount or tax → show final payable amount and itemized bill.
🧮 Formulas
  1. \[Average of N numbers: average = (sum of all numbers) / N\]
  2. \[Percentage: percentage = (obtained_marks / total_marks) * 100\]
  3. \[Sum of first n natural numbers: S = n(n + 1) / 2 (useful for reasoning about loops)\]
  4. \[Sum of AP (first n terms): S = n/2 * (2a + (n-1)d) (rarely used but helpful in complexity proofs)\]
  5. \[Common time complexities: O(1) (constant)\]
    \[O(log n) (logarithmic)\]
    \[O(n) (linear)\]
    \[O(n log n) (linearithmic)\]
    \[O(n^2) (quadratic)\]
  6. \[Loop iterations estimate: a loop from 1 to n generally implies O(n) time\]
    \[nested loops over n imply O(n^2).\]

Key Concepts

Python
A high-level, interpreted, general-purpose programming language known for readable syntax and rapid development.
Interpreter
A program that reads and executes Python code line by line without prior compilation to machine code.
Script
A file containing Python code (usually with .py extension) that can be executed by the interpreter.
Variable
A named location used to store data that can be changed during program execution.
Data type
Specifies the kind of value a variable can hold (e.g., int, float, str, bool).
Integer
A data type for whole numbers without a fractional part.
Float
A data type for numbers with a fractional (decimal) part.
String
A sequence of characters enclosed in quotes used to represent text.
Boolean
A data type with two possible values: True or False, used for logical operations.
Identifier
A name given to variables, functions, classes, etc.; must start with a letter or underscore and cannot be a keyword.
Keyword
Reserved words in Python that have special meaning and cannot be used as identifiers (e.g., if, for, def).
Comment
Non-executable text in code used to explain or annotate; starts with # for single-line comments.
input()
A built-in function that reads a line of text from the user and returns it as a string.
print()
A built-in function that displays values or text to the standard output (console).
Operator
Symbols that perform operations on values or variables (arithmetic, comparison, logical, assignment, etc.).
Expression
A combination of values, variables, and operators that produces a value when evaluated.
Statement
A complete instruction executed by the Python interpreter, such as assignments or function calls.
Indentation
Leading whitespace (spaces or tabs) used to define block structure in Python; incorrect indentation causes errors.
Function
A reusable block of code defined with def that can accept inputs (parameters) and may return a value.
List
An ordered, mutable collection of items, written with square brackets.

Practice Questions

  1. Define Python and list any three of its key features. / पायथन को परिभाषित कीजिए और इसकी कोई तीन प्रमुख विशेषताएँ लिखिए।
    Show answer

    Python is a high-level, interpreted, general-purpose programming language; three key features are that it is interpreted, dynamically typed, and high-level with a large standard library (batteries-included). / पायथन एक उच्च-स्तरीय, इंटरप्रेटेड, सामान्य-उद्देश्य प्रोग्रामिंग भाषा है; तीन प्रमुख विशेषताएँ हैं—यह इंटरप्रेटेड है, गतिशील रूप से टाइप्ड है, और बड़े मानक पुस्तकालय वाली उच्च-स्तरीय भाषा है।

  2. Differentiate between an interpreter and a compiler with reference to Python's execution model. / पायथन के निष्पादन मॉडल के संदर्भ में इंटरप्रेटर और कंपाइलर में अंतर बताइए।
    Show answer

    A compiler translates the whole source into machine code before running (e.g., C), while an interpreter translates and executes in steps at runtime; CPython uses a hybrid model that first compiles source to bytecode and then interprets it on the PVM. / कंपाइलर चलाने से पहले पूरे स्रोत को मशीन कोड में अनुवादित करता है (जैसे C), जबकि इंटरप्रेटर रनटाइम पर चरणों में अनुवाद और निष्पादन करता है; CPython एक हाइब्रिड मॉडल का उपयोग करता है जो पहले स्रोत को बाइटकोड में संकलित करता है और फिर PVM पर उसकी व्याख्या करता है।

  3. State the rules for naming a valid Python identifier and give one valid and one invalid example. / एक मान्य पायथन आइडेंटिफ़ायर के नामकरण के नियम बताइए और एक मान्य व एक अमान्य उदाहरण दीजिए।
    Show answer

    An identifier must start with a letter or underscore, contain only letters, digits and underscores, be case-sensitive, and not be a keyword; 'student_name' is valid while '1name' (starts with a digit) is invalid. / आइडेंटिफ़ायर अक्षर या अंडरस्कोर से शुरू होना चाहिए, केवल अक्षर, अंक और अंडरस्कोर रखे, केस-संवेदी हो, और कीवर्ड न हो; 'student_name' मान्य है जबकि '1name' (अंक से शुरू) अमान्य है।

  4. Predict the output and explain: x = 5; x = x + 2; print(x). / आउटपुट का अनुमान लगाइए और समझाइए: x = 5; x = x + 2; print(x).
    Show answer

    The output is 7 because x is first bound to 5, then the expression x + 2 evaluates to 7 and is reassigned to x, which print then displays. / आउटपुट 7 है क्योंकि x पहले 5 से बंधता है, फिर व्यंजक x + 2 का मान 7 निकलता है और पुनः x को सौंपा जाता है, जिसे print प्रदर्शित करता है।

  5. Why does input() require type conversion for arithmetic, and how is it done? / अंकगणित के लिए input() को टाइप रूपांतरण की आवश्यकता क्यों होती है, और यह कैसे किया जाता है?
    Show answer

    input() always returns a string, so arithmetic on it would concatenate instead of add; we convert it using int() or float(), e.g., age = int(input('Enter age: ')). / input() हमेशा एक स्ट्रिंग लौटाता है, इसलिए उस पर अंकगणित जोड़ने के बजाय जोड़कर लिखाई (कॉन्कैटेनेशन) करेगा; हम इसे int() या float() से रूपांतरित करते हैं, जैसे age = int(input('Enter age: '))।

  6. Write an if-elif-else program that prints the grade for a score (A for >=90, B for >=75, else C). / एक if-elif-else प्रोग्राम लिखिए जो किसी स्कोर के लिए ग्रेड छापे (>=90 पर A, >=75 पर B, अन्यथा C)।
    Show answer

    score = int(input()); if score >= 90: grade = 'A'; elif score >= 75: grade = 'B'; else: grade = 'C'; print('Grade =', grade) — conditions are checked in order until one is True. / score = int(input()); if score >= 90: grade = 'A'; elif score >= 75: grade = 'B'; else: grade = 'C'; print('Grade =', grade) — शर्तें क्रम में जाँची जाती हैं जब तक एक सत्य न हो।

  7. Explain the difference between break and continue in a loop with an example. / लूप में break और continue के बीच अंतर एक उदाहरण सहित समझाइए।
    Show answer

    break exits the loop immediately, while continue skips the rest of the current iteration and moves to the next; e.g., in 'for i in range(5): if i==3: break' the loop stops at 3, but with 'continue' it would only skip printing 3. / break लूप से तुरंत बाहर निकलता है, जबकि continue वर्तमान पुनरावृत्ति का शेष भाग छोड़कर अगली पर चला जाता है; जैसे 'for i in range(5): if i==3: break' में लूप 3 पर रुक जाता है, परंतु 'continue' से केवल 3 छपना छूटता है।

  8. Why is indentation significant in Python, and what error results from inconsistent indentation? / पायथन में इंडेंटेशन क्यों महत्वपूर्ण है, और असंगत इंडेंटेशन से कौन-सी त्रुटि होती है?
    Show answer

    Python uses indentation instead of braces to define code blocks, so all statements in a block must be equally indented; mixing tabs and spaces or wrong indentation raises an IndentationError. / पायथन कोड ब्लॉक परिभाषित करने के लिए ब्रेसेज़ के बजाय इंडेंटेशन का उपयोग करता है, इसलिए ब्लॉक के सभी कथन समान रूप से इंडेंट होने चाहिए; टैब और स्पेस मिलाने या गलत इंडेंटेशन से IndentationError उत्पन्न होती है।

Related Laws & Principles

Explore all

Foundational laws & principles connected to this chapter — tap to open in the Laws Explorer.

Loading related laws…
Sourced from 333 content files · LLOS Learn · browse all chapters