L
LLLOS.ai
Learn
L

Chapter 4 — Getting Started With Python

Class 11 · Computer Science

Overview

Chapter 4 — Getting Started With Python Master Diagram

Introduction: "Getting Started with Python" introduces students to Python as a high-level, interpreted programming language. The chapter explains how Python fits into the world of programming languages, differences between interpreters and compilers, and how to set up and use the Python environment (IDLE and script mode). Importance: This chapter builds the foundation for all programming topics that follow. It teaches how to write, save, run and debug simple Python programs, and establishes good habits (indentation, comments, readable identifiers) that are essential for correct and maintainable code. Key themes: basic Python syntax and semantics; interactive vs script mode; using IDLE; writing the first Python programs (print, input); identifiers, keywords, variables and assignment; primitive data types (numbers, strings, booleans) and type conversion; operators, expressions and precedence; comments, indentation and simple error types. What the student will learn: By the end of the chapter the student will be able to install/open Python IDLE, create and run Python programs, use print() and input() for I/O, declare and use variables, identify Python keywords and valid identifiers,…

Learning Objectives

  • Define Python and list its key features and advantages for programming
  • Explain the purpose of IDLE and describe different ways to run a Python program
  • Identify Python keywords and valid identifiers and apply naming rules correctly
  • Differentiate between literals, variables, and constants in Python
  • Classify basic Python data types (int, float, bool, str, None) and describe their common uses
  • Demonstrate input and output operations using print() and input(), including formatted output
  • Write and evaluate Python expressions using arithmetic, relational, logical, and assignment operators
  • Apply operator precedence and associativity to predict and trace expression evaluation

Topics in this chapter

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

💻1

Introduction to Python

💻 COMPUTER SCIENCE / IT

Introduction to Python

Key Point: Variable assignment: variable_name = expression (e.g., total = price * quantity)

What is Python?

Python is a high-level, interpreted, general-purpose programming language created by Guido van Rossum and first released in 1991. It is designed to be easy to read and write, with a clear and compact syntax. Python supports multiple programming paradigms including procedural, object-oriented and functional programming.

Key Characteristics

  • Interpreted: Code is executed line by line by the Python interpreter (no explicit compile step required).
  • High-level: Abstracts away many low-level details (memory management, pointers).
  • Dynamically typed: Variable types are determined at runtime (no need to declare types).
  • Readable syntax: Uses indentation to define blocks, improving readability.
  • Extensive standard library: Batteries-included modules for many tasks (file I/O, networking, data processing).
  • Cross-platform: Runs on Windows, macOS, Linux and many other systems.

Common Uses (Real-world)

  • Web development (Django, Flask)
  • Data science and machine learning (Pandas, NumPy, scikit-learn)
  • Scripting and automation (automating repetitive tasks, system scripts)
  • Game development (libraries like Pygame)
  • Education (beginner-friendly language used to teach programming)
  • Internet of Things and embedded systems (MicroPython)

Basic Concepts & Execution Model

Typical steps to run a simple Python program:

  1. Write code in a file with extension .py or in an interactive environment (IDLE, Jupyter notebook).
  2. Run the interpreter which reads the code and executes statements sequentially.
  3. Interpreter evaluates expressions, executes statements, and prints output.

Simple Example

print('Hello, Python!')

This prints a greeting to the screen. Indentation and correct spelling of keywords matter.

Important Language Rules

  • Indentation: Indentation (spaces or tabs) define blocks. Consistent use is required.
  • Comments: Use # for single-line comments. Triple quotes ('''...''') are used for multi-line strings/docstrings.
  • Keywords: Reserved words (like if, else, for, while, def, class, import) cannot be used as identifiers.
  • Identifiers: Names for variables and functions must start with a letter or underscore and can contain letters, digits and underscores.

Basic Data Types

  • Numeric types: int, float, complex
  • Boolean: bool (True or False)
  • Text: str
  • Collections (introduced later): list, tuple, set, dict

Input and Output

To print output: print(). To read input from user: input() (returns a string). Use type conversion functions like int() and float() to convert inputs to numeric types.

Advantages & Classroom Relevance

  • Easy to learn syntax suitable for beginners.
  • Widely used in industry and research — skills transfer to real applications.
  • Large community and many learning resources.

Summary

Python is a beginner-friendly, powerful language ideal for learning programming concepts. For Class 11, focus on writing small programs, understanding variables, basic data types, operators, control flow (if, loops introduced later), input/output, and following Python's indentation and naming rules.

📌 Examples
  • Hello world: print('Hello, Python!') — prints a greeting to the screen.
  • Sum of two numbers: num1 = int(input('Enter first number: ')) num2 = int(input('Enter second number: ')) print('Sum =', num1 + num2)
  • Average of three marks: m1 = float(input()) m2 = float(input()) m3 = float(input()) avg = (m1 + m2 + m3) / 3 print('Average =', avg)
  • Using a conditional (basic idea): age = int(input('Age: ')) if age >= 18: print('Eligible') else: print('Not eligible')
  • String concatenation: name = input('Name: ') print('Hello, ' + name)
  • Using a loop (conceptual example to be covered later): for i in range(5): print(i)
🧮 Formulas
  1. \[Variable assignment: variable_name = expression (e.g.\]
    \[total = price * quantity)\]
  2. \[Input and conversion: value = int(input()) or x = float(input())\]
  3. \[Print with separators and end: print(a\]
    \[b\]
    \[sep=' '\]
    \[end='\n')\]
  4. \[Arithmetic operators: + - * / // % ** (addition\]
    \[subtraction\]
    \[multiplication\]
    \[division\]
    \[integer division\]
    \[modulus\]
    \[exponent)\]
  5. \[Comparison operators: == != > < >= <= (equal\]
    \[not equal\]
    \[greater\]
    \[less\]
    \[etc.)\]
  6. \[Logical operators: and or not\]
💻2

Features of Python

💻 COMPUTER SCIENCE / IT

Features of Python

Key Point: Variable assignment: x = 10 # no type declaration

Overview: Python is a high-level, general-purpose programming language designed to be easy to read and write. It supports multiple programming paradigms (procedural, object-oriented, functional) and is widely used in areas such as web development, data analysis, automation, machine learning and scripting.

  • High-level language: Python abstracts away low-level details (memory management, pointers) so you can focus on solving problems rather than handling hardware specifics.
  • Interpreted: Python code is executed by an interpreter line-by-line (no separate compile step required). This makes testing and debugging faster and enables interactive use.
  • Readable and simple syntax: Python uses indentation to define blocks, not braces; its syntax is concise and close to readable English, which lowers the learning curve.
  • Dynamically typed: Variables do not require explicit type declarations; types are determined at runtime. This increases flexibility but requires careful runtime checks.
  • Object-oriented: Python supports classes, objects, inheritance and encapsulation, allowing modular and reusable code design.
  • Large standard library and ecosystem: Built-in modules (e.g., math, datetime, os) plus a vast third-party package repository (PyPI) let you do more with less code.
  • Cross-platform / portable: Python runs on Windows, macOS, Linux and many other platforms with little or no change to code.
  • Interactive mode and scripting: You can run Python interactively (REPL) for experiments, or run scripts for automation and batch tasks.
  • Garbage collection: Automatic memory management reclaims unused objects, reducing memory-leak issues for most uses.
  • Extensible and embeddable: Python can call C/C++ libraries for performance-critical modules and can be embedded into other applications.
  • Open source and large community: Python is free to use and has extensive documentation, tutorials and community support.
  • Case-sensitive and indentation-significant: Variable and function names are case-sensitive; proper indentation is mandatory, which enforces readable structure.

Why these features matter for Class 11 students: The simplicity, immediate feedback (interactive mode), and powerful libraries make Python ideal for beginners to learn core programming concepts (variables, control flow, functions, data structures) and to prototype real-life applications quickly.

📌 Examples
  • Automation: A short Python script using the os and shutil modules can batch-rename files or back up folders automatically (practical for organizing photos or school projects).
  • Data analysis: Using pandas, students can load a CSV of class marks and compute averages, medians and plot performance—helpful for quick statistical summaries.
  • Web development: A simple web app using Flask can host a student project (e.g., a book catalog) accessible from any browser.
  • Machine learning: With libraries like scikit-learn or TensorFlow, Python lets students experiment with basic classification or regression models on small datasets.
  • Microcontroller / IoT: MicroPython or CircuitPython lets Python control sensors and LEDs on Raspberry Pi Pico or Adafruit boards for hands-on electronics projects.
  • GUI apps: Tkinter enables building simple desktop applications (like a calculator) to understand event-driven programming.
🧮 Formulas
  1. \[Variable assignment: x = 10 # no type declaration\]
  2. \[Input / Output: name = input('Enter name: ')\]
    \[print('Hello'\]
    \[name)\]
  3. \[If statement: if condition:\n # indented block\nelse:\n # else block\]
  4. \[For loop: for i in range(start\]
    \[stop\]
    \[step):\n # loop body\]
  5. \[Function definition: def func(arg1\]
    \[arg2=default):\n return value\]
  6. \[Class skeleton: class MyClass:\n def __init__(self\]
    \[x):\n self.x = x\]
💻3

Installing Python and IDE (IDLE)

💻 COMPUTER SCIENCE / IT

Installing Python and IDE (IDLE)

Key Point: Check Python version: python --version or python3 --version

This topic explains how to install Python and use the bundled IDE, IDLE. It covers downloading Python, configuring the PATH, verifying the installation, opening IDLE, writing and running a simple program, and troubleshooting tips.

1. What you need

  • Internet access to download the installer (or package manager access on Linux/macOS).
  • Administrator or sudo rights on the machine to install system-wide, or use a user install.

2. Installing Python (step-by-step)

  1. Download: Go to https://www.python.org/downloads/ and choose the latest stable release for your OS.
  2. Windows:
    1. Run the downloaded installer (.exe).
    2. Important: check 'Add Python to PATH' on the first installer screen to make the python command available in Command Prompt.
    3. Click 'Install Now' (or choose 'Customize install' to change location).
  3. macOS: Use the official macOS installer from python.org or use Homebrew:
    brew install python
  4. Linux: Use the distribution package manager. Example for Debian/Ubuntu:
    sudo apt update
    sudo apt install python3 python3-pip idle-python3.9
    (package names vary by distro)
  5. Verify installation: Open a terminal/command prompt and run:
    python --version
    python3 --version
    You should see the installed Python version.

3. PATH and why it matters

When you type python in a terminal, the system looks for an executable in directories listed in the PATH environment variable. If Python's install directory (and Scripts) is not in PATH, the command won't be found. Example PATH addition on Windows (display only):

PATH = existing_paths;C:\Python39\;C:\Python39\Scripts\

4. What is IDLE?

IDLE (Integrated DeveLopment Environment) is the simple editor and shell that comes with standard Python distributions. It is lightweight and ideal for beginners. Main parts:

  • Shell window – interactive prompt where you can type Python expressions and see immediate output.
  • Editor window – create, edit and save .py files. Use Run > Run Module (F5) to execute a saved script; output appears in the Shell.
  • Features: syntax highlighting, basic autocompletion, indentation support, debugger, and basic configuration options.

5. First program in IDLE

  1. Open IDLE from Start menu (Windows) or via terminal command
    idle3
    (name may vary).
  2. In the Editor window type:
    print('Hello, World!')
  3. Save as hello.py and press F5 (Run Module). The Shell will show:
    Hello, World!

6. Installing packages (pip)

pip is the Python package installer. Example to install a package:

python -m pip install requests
# or, if python points to Python 2 on some systems
python3 -m pip install requests

7. Troubleshooting & tips

  • If python command not found: re-run installer and check 'Add to PATH', or manually add the Python install folder to PATH.
  • Use python3 on systems where python is Python 2 by default.
  • On Windows, run 'py' launcher:
    py -3 hello.py
    to select Python 3 explicitly.
  • For larger projects, consider more advanced IDEs/editors (VS Code, PyCharm) but IDLE is sufficient for learning basics.

8. Best practices for beginners

  • Keep scripts in a dedicated folder (e.g., Documents\PythonProjects).
  • Name files with .py extension and avoid names like math.py that shadow standard modules.
  • Save your file before running in IDLE (F5 requires a saved file).
📌 Examples
  • Hello world: Create hello.py containing print('Hello, World!') and run it in IDLE (F5).
  • Simple bill calculator: bill.py reads item price and quantity, computes total with a fixed tax rate, and prints the final amount.
  • Temperature converter: temp.py converts Celsius to Fahrenheit using the formula F = (C * 9/5) + 32 and prints the result.
  • Bulk rename script: a small script that renames files in a folder (useful for organizing photos). Example uses os.rename in a for loop.
  • Automated attendance: a script that appends student names and timestamps to a text file when they are marked present.
🧮 Formulas
  1. \[Check Python version: python --version or python3 --version\]
  2. \[Run script from terminal: python filename.py or python3 filename.py\]
  3. \[Install package with pip: python -m pip install package_name\]
  4. \[Windows PATH example (display): PATH = existing_paths\]
    \[C:\\Python39\\\]
    \[C:\\Python39\\Scripts\\\]
  5. \[Temperature conversion (example program formula): F = (C * 9/5) + 32\]
✍️4

Writing and Executing Python Programs

💻 COMPUTER SCIENCE / IT

Writing and Executing Python Programs

Key Point: Simple Interest: SI = (P * R * T) / 100

Overview: Writing and executing Python programs means creating source code files (with the .py extension) that contain Python statements, then running them using a Python interpreter. Python is an interpreted, high-level language; the interpreter reads your source, converts it to bytecode, then executes it on the Python Virtual Machine (PVM).

Basic steps:

  • Write code in a text editor or IDE (IDLE, VS Code, PyCharm) and save it with a .py extension.
  • Run it using the interpreter: python filename.py (or python3 filename.py on some systems) or use an IDE/run button or an online REPL.
  • Read program output and fix any syntax/runtime errors; repeat edit & run until correct.

Simple program structure and example:

# hello.py
print("Hello, World!")

Save as hello.py and run: python hello.py. The interpreter prints the output and returns control to the shell.

Writing correct Python:

  • Indentation matters: blocks are defined by consistent spaces or tabs (PEP 8 recommends 4 spaces).
  • Comments: # for single-line, triple quotes ("""...""") often used for docstrings.
  • Variables & data types: integers, floats, strings, booleans, lists, tuples, dictionaries, sets.
  • Input and output: use input() for console input and print() for output. Convert types with int(), float(), etc.
  • Functions: group reusable code with def and call them from main flow or other functions.

Execution pipeline (how the interpreter runs your code):

  • Source code (.py) → Lexical analysis/tokenization → Parsing → Abstract Syntax Tree (AST) → Bytecode generation (.pyc) → Python Virtual Machine executes bytecode.
  • Errors can occur at different stages: syntax errors (caught while parsing), exceptions at runtime (e.g., ZeroDivisionError), or logic errors (wrong output).

Running options / environments:

  • Command line/terminal: python file.py.
  • IDLE/IDE: press Run or use built-in console.
  • Interactive REPL: type python then enter statements directly.
  • Online interpreters: useful for quick tests (e.g., repl.it, online Python tutors).
  • Virtual environments (venv) to manage dependencies per project: python -m venv env, then activate.

Common pitfalls and debugging tips:

  • Watch indentation carefully; inconsistent use of tabs and spaces causes errors.
  • Read error messages: they show line numbers and error types.
  • Use print() or logging to inspect variable values; use a debugger (pdb or IDE debugger) to step through code.
  • Avoid naming your files the same as standard modules (e.g., don’t name your file random.py if you import random).

Real-life uses: quick scripts to automate file renaming, data cleaning, calculators (finance or health), simple web APIs, reading sensor data, generating reports, and classroom examples.

Good practices: keep short functions, meaningful variable names, add comments/docstrings, handle exceptions with try/except, and test with sample inputs.

Small annotated program with input:

# simple interest calculator: simple_interest.py
p = float(input("Principal (P): "))
r = float(input("Rate (R) in %: "))
t = float(input("Time (T) in years: "))
si = (p * r * t) / 100
print("Simple Interest:", si)

Save and run; the program reads user inputs, computes using the formula, and prints the result.

📌 Examples
  • Hello World # hello.py print("Hello, World!") # Run: python hello.py
  • Simple Interest Calculator # simple_interest.py p = float(input('P: ')) r = float(input('R (%): ')) t = float(input('T (years): ')) si = (p * r * t) / 100 print('Simple Interest =', si)
  • Temperature Converter (Celsius to Fahrenheit) # temp_conv.py c = float(input('Celsius: ')) f = (c * 9/5) + 32 print('Fahrenheit =', f)
  • Calculate BMI # bmi.py weight = float(input('Weight (kg): ')) height = float(input('Height (m): ')) bmi = weight / (height ** 2) print('BMI =', round(bmi, 2))
  • Sum of first N natural numbers (using loop) # sum_n.py n = int(input('Enter N: ')) s = 0 for i in range(1, n+1): s += i print('Sum =', s)
🧮 Formulas
  1. \[Simple Interest: SI = (P * R * T) / 100\]
  2. \[Area of circle: A = π * r^2 (use math.pi in Python: import math\]
    \[math.pi)\]
  3. \[Celsius to Fahrenheit: F = (C * 9/5) + 32\]
  4. \[Fahrenheit to Celsius: C = (F - 32) * 5/9\]
  5. \[Body Mass Index: BMI = weight(kg) / (height(m) ^ 2)\]
🧾5

Basic Syntax: Statements, Indentation and Blocks

💻 COMPUTER SCIENCE / IT

Basic Syntax: Statements, Indentation and Blocks

Key Point: Compound header rule: header_line + ':' → followed by an indented block.

Overview

In Python, program text is made up of statements. A statement is an instruction that the Python interpreter can execute (for example: assignment, function call, loop, conditional). Unlike many languages that use braces to group statements, Python uses indentation to define blocks (also called suites). Proper indentation is therefore part of Python's syntax.

Statements

There are two main kinds of statements:

  • Simple statements — a single logical line containing an action (e.g., x = 5, print(x)). Multiple simple statements can appear on the same physical line separated by semicolons, but this is discouraged.
  • Compound statements — these contain a header and a block (suite). Examples: if, for, while, def, class. The header ends with a colon (:) and is followed on the next lines by an indented block.

Blocks (Suites) and Indentation

A block (suite) is a group of statements controlled by a compound statement. All statements in the same block must have the same indentation level. Indentation level is measured by the number of spaces (or a single tab) at the start of the line. Common rules and conventions:

  • Use consistent indentation throughout a program — do not mix tabs and spaces. Mixing can cause IndentationError or behave unpredictably.
  • PEP 8 recommends 4 spaces per indentation level.
  • A compound statement header ends with a colon, e.g. if condition:, followed by an indented block on subsequent lines.
  • An empty block can be written using the pass statement.

Line Continuation and Grouping

Long logical statements may span multiple physical lines using:

  • An explicit backslash: total = a + b + \
  • Implicit continuation inside parentheses, brackets or braces: items = [a, b, c, d]

Common Errors

  • IndentationError: unexpected indent — a line is indented more than expected.
  • IndentationError: expected an indented block — a compound header has no following indented statements.
  • Logical errors due to wrong indentation (e.g., placing a statement outside a block when it should be inside).

Why this matters (real-world reasoning)

Indentation defines program structure and readability. It enforces a uniform style so that code is easier to read and maintain. Because the interpreter uses indentation to determine scope, consistent indentation prevents bugs related to variable scope and control flow.

Small examples (inline)

# Simple statement
x = 10
print(x)

# Compound statement with block (if)
if x > 5:
    print("x is greater than 5")
else:
    print("x is 5 or less")

# Function (block) and loop (nested block)
def greet(names):
    for name in names:
        print("Hello", name)
📌 Examples
  • Example 1: if-else block x = 12 if x % 2 == 0: print("Even") else: print("Odd")
  • Example 2: nested blocks (for loop inside function) def show_squares(n): for i in range(1, n+1): print(i, "->", i*i) show_squares(5)
  • Example 3: multi-line statement with parentheses total = (100 + 200 + 300 + 400 + 500) print("Total:", total)
🧮 Formulas
  1. \[Compound header rule: header_line + ':' → followed by an indented block.\]
  2. \[Block consistency rule: All statements in the same block must have the same indentation level.\]
  3. \[Indentation convention: Use 4 spaces per level (PEP 8 recommendation).\]
  4. \[Line continuation: Use backslash (\) or enclose expression in (), []\]
    \[or {} for implicit continuation.\]
  5. \[Empty block: use 'pass' to create a placeholder statement.\]
💻6

Comments and Documentation

💻 COMPUTER SCIENCE / IT

Comments and Documentation

Key Point: # comment syntax: # your comment here

What are comments and documentation?
Comments are human-readable notes in source code that the Python interpreter ignores. Documentation (often provided as docstrings) explains the purpose, usage, inputs, outputs, and behaviour of modules, classes and functions. Good comments and documentation make code easier to read, maintain and reuse.

Types in Python

  • Single-line comment: Starts with #. Used for short notes or to disable a line of code.
  • Block (multi-line) comments: Multiple single-line comments one after another (each line begins with #), or a sequence of comments describing a block.
  • Docstrings: Triple-quoted strings ('''...''' or """...""") placed as the first statement in a module, class, or function. These are accessible at runtime via the __doc__ attribute and help().

Example usages

# single-line comment: explains a single statement
x = 10  # x stores the current count

# block comment: explain a following block of logic
# The next loop computes factorial of n
# using iterative multiplication
factorial = 1
for i in range(1, x + 1):
    factorial *= i

# docstring for a function:
def add(a, b):
    '''Return the sum of a and b.\n
    Parameters:\n      a (int or float): first addend\n      b (int or float): second addend\n
    Returns:\n      int or float: the sum of a and b\n    '''
    return a + b

Why comments and documentation matter

  • Improve readability: Explain intent rather than restating code.
  • Help maintenance: Future you or other developers understand design decisions.
  • Enable automated docs: Docstrings can be used by tools (pydoc, Sphinx) to generate documentation.
  • Make code safer: TODOs and warnings highlight unfinished parts or pitfalls.

Best practices

  • Prefer clear code over comments: write expressive names and modular code; use comments to explain why, not what.
  • Keep docstrings for public APIs: every module, class and function that will be reused should have a docstring.
  • Follow a docstring style (Google, NumPy, or reST) for consistency: include short summary, parameters, return values, and examples.
  • Update comments when code changes; stale comments are misleading.
  • Use TODO/FIXME tags for unfinished work and searchable notes.

Accessing docstrings at runtime

print(add.__doc__)   # prints the docstring of the function
help(add)             # opens a readable help page for the function

Summary
Comments and documentation are essential tools for communication in software development. Use # for short notes and triple-quoted docstrings for documenting modules, classes and functions. Adopt consistent style and keep documentation up to date.

📌 Examples
  • Single-line comment: # This variable stores the score score = 95
  • Block comment: # Calculate area of a rectangle # using length and breadth length = 5 breadth = 3 area = length * breadth
  • Function docstring example: def greet(name): '''Return a greeting message for name. Parameters: name (str): Person's name Returns: str: Greeting message ''' return 'Hello, ' + name + '!' # Usage: print(greet.__doc__) print(greet('Asha'))
  • Module docstring (top of file): '''utilities.py: helper functions for string processing''' def to_upper(s): '''Convert string s to uppercase.''' return s.upper()
🧮 Formulas
  1. \[# comment syntax: # your comment here\]
  2. \[Docstring syntax (function/class/module): '''Short description.\n\nOptional longer description\]
    \[parameters\]
    \[returns\]
    \[examples.'''\]
  3. \[__doc__ access: object.__doc__ (e.g.\]
    \[my_function.__doc__)\]
  4. \[help() usage: help(object) (e.g.\]
    \[help(my_function))\]
  5. \[Docstring template (concise): Short summary.\n\nParameters:\n name (type): description\n\nReturns:\n type: description\]
💻7

Tokens of Python

💻 COMPUTER SCIENCE / IT

Tokens of Python

Key Point: Identifier naming rule (regex): ^[A-Za-z_][A-Za-z0-9_]*$ (must not start with a digit, case-sensitive, cannot be a keyword)

What are tokens? Tokens are the smallest meaningful units in a Python program — the lexical building blocks that the interpreter recognizes during the scanning (lexical analysis) phase. The interpreter groups characters from source code into tokens before parsing.

  • Types of tokens:
    • Keywords — reserved words with special meaning (e.g., if, for, def, return, import).
    • Identifiers — names given to variables, functions, classes (must follow naming rules).
    • Literals — fixed values: numeric (integers, floats, complex), string, Boolean (True, False) and None.
    • Operators — symbols that perform operations (arithmetic +, -, comparison ==, logical and/or, etc.).
    • Delimiters / Punctuators — characters that separate code elements: parentheses ( ), brackets [ ], braces { }, comma ,, colon :, semicolon ;, dot ..
    • Comments — text ignored by interpreter (start with # for single-line; triple quotes for multi-line docstrings). Comments are not executed but are part of source text for readability.
    • Whitespace and indentation — in Python, indentation is significant (INDENT / DEDENT tokens) and newlines separate statements; spaces separate tokens but are otherwise ignored.

How tokenization works (brief): The lexer reads characters and groups them into token objects such as NAME (identifier/keyword), NUMBER, STRING, OP (operator), NEWLINE, INDENT, DEDENT, etc. Keywords are recognized when a NAME token matches a reserved word.

Simple annotated example:

# Source line
if score >= 90:
    grade = "A"  # top grade

# Tokens (examples):
# 'if' (keyword), 'score' (identifier), '>=' (operator), '90' (numeric literal), ':' (delimiter), NEWLINE, INDENT,
# 'grade' (identifier), '=' (operator), '"A"' (string literal), NEWLINE, DEDENT

Why tokens matter: Understanding tokens helps you read how the interpreter breaks down code, diagnose syntax errors (wrong token sequences), and write correct identifiers, literals and expressions.

📌 Examples
  • if a > 10: print("High") # Tokens: 'if'(keyword), 'a'(identifier), '>'(operator), '10'(literal), ':'(delimiter), NEWLINE, INDENT, 'print'(identifier), '(' , '"High"'(string literal), ')', NEWLINE, DEDENT
  • def add(x, y): return x + y # Tokens: 'def'(keyword), 'add'(identifier), '(' , 'x'(identifier), ',' , 'y'(identifier), ')', ':' , NEWLINE, INDENT, 'return'(keyword), 'x'(identifier), '+'(operator), 'y'(identifier), NEWLINE, DEDENT
  • count = 42 # integer literal price = 19.99 # float literal # Tokens include NAME, '=', NUMBER, COMMENT
  • name = 'Alice' # string literal # Tokens: 'name'(identifier), '='(operator), 'Alice'(string literal)
  • x, y = 1, 2 # delimiters: comma # Tokens: 'x'(id), ','(delimiter), 'y'(id), '='(op), '1'(lit), ','(delim), '2'(lit)
  • # Indentation matters: for i in range(3): print(i) print('done') # INDENT/DEDENT tokens mark the block under the for-loop
🧮 Formulas
  1. \[Identifier naming rule (regex): ^[A-Za-z_][A-Za-z0-9_]*$ (must not start with a digit\]
    \[case-sensitive\]
    \[cannot be a keyword)\]
  2. \[Numeric literal forms: - Integer: 123, 0, 0b101 (binary), 0o77 (octal), 0x1A (hex) - Float: 3.14, 2e-3 - Complex: 2+3j\]
  3. \[String literals: single ('...') or double quotes ("...") or triple quotes for multi-line ('''...''' or """...""")\]
  4. \[Operator precedence (high → low\]
    \[abbreviated): 1. () 2. ** 3. + - (unary) 4. * / // % 5. + - (binary) 6. << >> 7. & 8. ^ 9. | 10. comparisons 11. not 12. and 13. or 14. assignment (=, +=, ...)\]
  5. \[Common token types mapping to lexer tokens: NAME (identifier/keyword)\]
    \[NUMBER\]
    \[STRING\]
    \[OP (operator)\]
    \[NEWLINE\]
    \[INDENT\]
    \[DEDENT\]
    \[COMMENT\]
💻8

Keywords and Identifiers

💻 COMPUTER SCIENCE / IT

Keywords and Identifiers

Key Point: Identifier pattern (regular expression): ^[A-Za-z_][A-Za-z0-9_]*$ (starts with letter/_ then letters/digits/_ allowed).

Keywords are a fixed set of reserved words in Python that have a special meaning to the interpreter and cannot be used as names for variables, functions or identifiers. Examples: if, for, def, return, import, class.

Identifiers are names you create in a program to identify variables, functions, classes, modules, etc. Identifiers give a readable name to values or blocks of code.

Key differences: Keywords are built‑in and fixed; identifiers are user-defined. Keywords cannot be changed or reused as identifiers.

Rules for valid identifiers (use these when naming):

  • An identifier must start with a letter (A–Z or a–z) or an underscore (_) — it cannot start with a digit.
  • After the first character, it may contain letters, digits (0–9) and underscores only.
  • Identifiers are case-sensitive: age and Age are different.
  • Identifiers cannot be the same as Python keywords or contain special characters or spaces.
  • There is no strict length limit, but names should be short and meaningful.

Naming conventions (recommended style):

  • Use lowercase with underscores for variables and functions: student_name.
  • Use CapitalizedWords (PascalCase) for class names: StudentRecord.
  • Use ALL_CAPS for constants: PI = 3.14.
  • Avoid using built-in function names (like list, max, input) as identifiers.

Examples (quick view):

# Valid identifiers
name = 'Asha'
_age = 18
score1 = 95

# Invalid identifiers (errors)
1stScore = 70    # starts with a digit
my-name = 50     # contains hyphen
class = 5        # 'class' is a keyword

Practical / real-life idea: Think of identifiers as labels you put on boxes in a storehouse — the label must follow store rules (no special symbols, meaningful name) and cannot be a reserved label used by the store manager (keywords).

Important tip for students: Always choose meaningful names (for readability) and never reuse keywords or built-in names as identifiers to avoid bugs and confusing errors.

📌 Examples
  • Valid identifiers: student_name, _temp, score1, Age, PI — use these to store values like strings, numbers, constants.
  • Invalid identifiers: 1name (starts with digit), my-name (hyphen not allowed), total$ (special character), break (keyword cannot be used).
  • Keywords examples (cannot be identifiers): False, None, True, and, as, assert, async, await, break, class, continue, def, del, elif, else, except, finally, for, from, global, if, import, in, is, lambda, nonlocal, not, or, pass, raise, return, try, while, with, yield, match, case.
🧮 Formulas
  1. \[Identifier pattern (regular expression): ^[A-Za-z_][A-Za-z0-9_]*$ (starts with letter/_ then letters/digits/_ allowed).\]
  2. \[Case sensitivity rule: identifier1 != Identifier1 (names with different letter cases are distinct).\]
  3. \[Keyword restriction: identifier ∉ Keywords (an identifier must not be equal to any reserved keyword).\]
  4. \[Naming guidance (not a strict formula): Use descriptive_name ≈ purpose_of_variable (e.g.\]
    \[student_age for a student's age).\]
📊9

Literals and Data Types

💻 COMPUTER SCIENCE / IT

Literals and Data Types

Key Point: type(x) -> returns the data type of x (e.g., type(5) -> )

What is a literal? A literal is a fixed value written directly in a program. Examples: 10, 3.14, 'Hello', True. Literals represent data items of specific data types.

What is a data type? A data type tells the interpreter what kind of value a variable holds and what operations are valid on it. Python is dynamically typed: a variable can refer to values of different types during execution.

Common literal categories and corresponding Python data types

  • Numeric literals
    • Integer (int): whole numbers, e.g., 0, -7, 2025
    • Floating-point (float): numbers with a decimal point or in exponential form, e.g., 3.14, -0.5, 1e3
    • Complex (complex): a + bj, e.g., 2+3j
  • String literals (str): sequence of characters enclosed in single, double or triple quotes, e.g., 'Alice', "Hello", '''multi-line'''
  • Boolean literals (bool): True or False. Useful for conditions and flags.
  • None literal (NoneType): None indicates absence of a value.
  • Collection literals:
    • List: [1, 2, 3] — ordered, mutable
    • Tuple: (1, 2, 3) — ordered, immutable
    • Dictionary: {'key': 'value'} — key-value pairs, keys must be immutable
    • Set: {1, 2, 3} — unordered, unique elements

Mutable vs Immutable: Immutable types cannot be changed after creation (int, float, bool, str, tuple). Mutable types can be changed in place (list, dict, set).

Type checking and conversion: Use type(value) to find the data type. Convert between types using functions such as int(), float(), str(), bool(), list(), tuple(), dict(). Be careful: conversion may fail if the value is not compatible (e.g., int('abc') raises an error).

Truthiness rules: In conditional contexts, the following are considered False: 0, 0.0, '', "", [], (), {}, set(), None, and False. Everything else is True.

Real-life analogies:

  • int: counting whole apples in a basket
  • float: measuring rupees and paise (money with decimals)
  • str: a person's name or a street address
  • bool: a light switch (on/off)
  • list: a grocery list you can change
  • tuple: a fixed schedule (days of week)
  • dict: a phone book mapping names to numbers

Good practices:

  • Choose the simplest type that models the data (use int for counts, float for measurements, dict for keyed records).
  • Name variables clearly to reflect the data they hold (e.g., student_count, price, address_dict).
  • Prefer immutability when values should not change (use tuple instead of list where appropriate).

Small example (concept):

name = 'Riya'         # string literal
age = 16               # integer literal
marks = [85, 92, 78]   # list literal
passed = True          # boolean literal
print(type(age))       # <class 'int'>
📌 Examples
  • 1) Integer literal and type: age = 16 print(age, type(age)) # Output: 16 <class 'int'>
  • 2) Float literal: price = 249.50 print(price, type(price)) # Output: 249.5 <class 'float'>
  • 3) String and escape sequences: msg = "He said, \"Hello\"" print(msg) # Output: He said, "Hello"
  • 4) Boolean and truthiness: is_valid = False if not is_valid: print('Invalid')
  • 5) List (mutable) vs Tuple (immutable): nums = [1,2,3] nums[0] = 10 # allowed coords = (0, 5) # coords[0] = 1 # error: tuples are immutable
  • 6) Dictionary literal: phone = {'Asha': 9876543210, 'Ravi': 9123456780} print(phone['Asha']) # Access by key
🧮 Formulas
  1. \[type(x) -> returns the data type of x (e.g.\]
    \[type(5) -> <class 'int'>)\]
  2. \[int(x)\]
    \[float(x)\]
    \[str(x)\]
    \[bool(x)\]
    \[complex(a\]
    \[b) -> type conversion functions\]
  3. \[len(s) -> length of a sequence or collection (strings\]
    \[lists\]
    \[tuples\]
    \[dict keys)\]
  4. \[True == 1 and False == 0 -> boolean to integer equivalence in numeric contexts\]
  5. \[a + b\]
    \[a - b\]
    \[a * b\]
    \[a / b\]
    \[a // b\]
    \[a % b\]
    \[a ** b -> numeric operators (resulting type depends on operands\]
    \[e.g.\]
    \[int/float)\]
  6. \[x in collection -> membership test (works for strings\]
    \[lists\]
    \[tuples\]
    \[sets\]
    \[dict keys)\]
💻10

Variables and Assignment

💻 COMPUTER SCIENCE / IT

Variables and Assignment

Key Point: Assignment: variable = expression

What is a variable?

A variable is a name (identifier) that refers to a value stored in the computer's memory. In Python a variable holds a reference to an object (number, text, list, etc.). You create a variable by assigning a value to a name using the equals sign =.

Naming rules for identifiers

  • Must start with a letter (a–z, A–Z) or underscore (_).
  • Can contain letters, digits and underscores (no spaces or special characters).
  • Case sensitive: age and Age are different.
  • Cannot use Python keywords (like for, if, class).

Assignment statement

Basic form: variable = expression. The expression on the right is evaluated and the resulting object is bound to the name on the left.

# examples
x = 10         # integer
name = 'Asha'  # string
pi = 3.14      # float

Types of assignment

  • Single assignment: a = 5.
  • Multiple (parallel) assignment: a, b = 5, 10 assigns 5 to a and 10 to b.
  • Chained assignment: a = b = 0 binds the same immutable value to both names.
  • Augmented assignment: a += 2 (equivalent to a = a + 2).

Dynamic typing and types

Python is dynamically typed: the type of a variable is the type of the object it currently refers to and can change at runtime (for example x = 5 then x = 'five'). Use type(x) to check a variable's type.

Input and type conversion

Function input() always returns a string. To use numeric input convert it: n = int(input()) or f = float(input()). Use str(), int(), float() for conversions.

Variables and memory (conceptual)

Think of variables as labelled boxes pointing to values. Immutable objects (like integers, strings, tuples) cannot be changed; mutable objects (lists, dictionaries) can be changed through the same reference. When you reassign a variable, it points to a new object; the old object may be garbage-collected if no names reference it.

Constants

Python has no true constant enforcement; by convention use uppercase names for values meant to stay constant (for example PI = 3.14159).

Common operations and patterns

  • Swap two variables: a, b = b, a (no temporary needed).
  • Multiple assignment from expressions: x, y = y+1, x-1.
  • Unpacking iterables: first, *rest = [1,2,3,4].

Good practices

  • Choose descriptive names (e.g., student_count not sc).
  • Follow naming conventions: lower_case_with_underscores for variables.
  • Avoid using single-letter names except in short loops or mathematical contexts.
📌 Examples
  • Bank balance: balance = 1500.50 # store a customer's account balance
  • Student marks: physics, chemistry, math = 78, 85, 92 # parallel assignment
  • Swap two values: a, b = b, a # exchanges contents without a temporary variable
  • Reading integer input: age = int(input('Enter your age: ')) # convert string input to int
  • Running total using augmented assignment: total = 0; total += price # add price to total
🧮 Formulas
  1. \[Assignment: variable = expression\]
  2. \[Multiple assignment: a\]
    \[b\]
    \[c = expr1\]
    \[expr2\]
    \[expr3\]
  3. \[Chained assignment: a = b = value\]
  4. \[Augmented assignment: a op= expr (example: a += 1 is a = a + 1)\]
  5. \[Type conversion: int(s)\]
    \[float(s)\]
    \[str(x)\]
  6. \[Swap: a\]
    \[b = b\]
    \[a\]
💻11

Operators

💻 COMPUTER SCIENCE / IT

Operators

Key Point: Arithmetic: a + b (addition), a - b (subtraction), a * b (multiplication), a / b (true division, float), a // b (floor division, int), a % b (remainder), a ** b (power)

Operators are special symbols in Python that perform operations on values (operands). They take one or more operands and return a result. In Class 11 Python (Getting Started with Python) you should know the categories of operators, their behaviour, precedence and common uses.

  • Arithmetic operators: +, -, *, /, // (floor division), % (modulo), ** (power). Work on numbers and return numeric results.
  • Relational (comparison) operators: ==, !=, <, >, <=, >=. Compare values and return boolean True/False.
  • Logical operators: and, or, not. Combine boolean expressions. They use short-circuit evaluation (stop early when result determined).
  • Assignment operators: =, +=, -=, *=, /=, //=, %=, **=. Assign values to variables; compound forms update the variable using an operation.
  • Bitwise operators: &, |, ^, ~, <<, >>. Operate on binary representation of integers.
  • Membership operators: in, not in. Test presence of a value in a sequence (string, list, tuple, dictionary keys).
  • Identity operators: is, is not. Test whether two references point to the same object (not just equal values).

Key points:

  • Relational and logical operators return boolean values (True or False).
  • Operator precedence determines the order expressions are evaluated (for example, * before +). Use parentheses to make evaluation explicit.
  • Short-circuiting: in expr1 and expr2, if expr1 is False evaluation stops and expr1 is returned; in expr1 or expr2, if expr1 is True evaluation stops and expr1 is returned. In Python these also return the actual operand, not only True/False.
  • Assignment is not an expression in Python, so you cannot use it inside another expression (unlike some other languages).

Example snippets:

# arithmetic
x = 7 // 2   # floor division => 3
y = 7 % 2    # remainder => 1
z = 2 ** 3   # power => 8

# relational
age = 18
is_adult = age >= 18   # True

# logical
can_vote = (age >= 18) and (citizenship == 'India')

# membership
item_in_cart = 'apple' in ['banana', 'apple', 'mango']  # True

# identity
a = [1,2]
b = a
c = [1,2]
a is b   # True
a is c   # False (same contents but different objects)
📌 Examples
  • Arithmetic (calculator): Code: a = 15; b = 4; print(a + b, a - b, a * b, a / b, a // b, a % b, a ** b) Output: 19 11 60 3.75 3 3 50625
  • Relational (age check): Code: age = 17; print(age >= 18) Output: False
  • Logical (access control): Code: logged_in = True; has_permission = False; print(logged_in and has_permission) Output: False
  • Assignment (bank balance): Code: balance = 1000; balance += 500 # deposit; balance -= 200 # withdrawal Result: balance becomes 1300 then 1100
  • Bitwise (flags): Code: a = 0b1100; b = 0b1010; print(bin(a & b), bin(a | b), bin(a ^ b)) Output: 0b1000 0b1110 0b0110
  • Membership (cart): Code: cart = ['pen','notebook']; print('pen' in cart, 'eraser' not in cart) Output: True True
🧮 Formulas
  1. \[Arithmetic: a + b (addition)\]
    \[a - b (subtraction)\]
    \[a * b (multiplication)\]
    \[a / b (true division\]
    \[float)\]
    \[a // b (floor division\]
    \[int)\]
    \[a % b (remainder)\]
    \[a ** b (power)\]
  2. \[Relational: a == b (equal)\]
    \[a != b (not equal)\]
    \[a < b\]
    \[a > b\]
    \[a <= b\]
    \[a >= b => all return boolean\]
  3. \[Logical: A and B\]
    \[A or B\]
    \[not A (use booleans or expressions that evaluate to booleans)\]
    \[Short-circuit: (A and B) returns A if A is falsy else B\]
    \[(A or B) returns A if A is truthy else B.\]
  4. \[Assignment compound: x op= y is equivalent to x = x op y (op can be +, -, *, /, //, %, **, &, |, ^, <<, >>)\]
  5. \[Bitwise: a & b (AND)\]
    \[a | b (OR)\]
    \[a ^ b (XOR), ~a (bitwise NOT = -a-1 in two's complement)\]
    \[a << n (left shift = multiply by 2^n)\]
    \[a >> n (right shift = floor divide by 2^n for positive ints)\]
  6. \[Membership and identity: x in seq => True if an element equal to x is found\]
    \[x is y => True if x and y are the same object (same id)\]
💻12

Expressions, Precedence and Associativity

💻 COMPUTER SCIENCE / IT

Expressions, Precedence and Associativity

Key Point: Parentheses first: ( ... )

What is an expression? An expression is any combination of values, variables, operators and calls that the Python interpreter can evaluate to produce another value. Examples: 2 + 3, price * (1 - discount), a > b and b != 0.

Evaluation steps: When Python evaluates an expression it follows rules:

  • Parentheses first — expressions inside () are evaluated before anything outside.
  • Operator precedence — operators with higher precedence are applied before lower-precedence operators.
  • If two operators have the same precedence, associativity (left-to-right or right-to-left) decides the order.

Precedence (concept): Think of precedence as priority levels; a higher-priority operator 'binds' its operands first. For example, multiplication has higher precedence than addition, so 2 + 3 * 4 is evaluated as 2 + (3 * 4), not (2 + 3) * 4.

Associativity (concept): When two operators of the same precedence appear, associativity tells which side to evaluate first. Most binary arithmetic operators (like +, -, *, /) are left-associative: a - b - c means (a - b) - c. Exponentiation (**) is right-associative: 2 ** 3 ** 2 means 2 ** (3 ** 2).

Special points for Python (useful for Class 11):

  • Parentheses () can override precedence and are the best way to make expressions clear.
  • Unary operators (like +x, -x) have higher precedence than binary + and -.
  • Logical operators not, and, or have lower precedence than comparison operators.
  • Chained comparisons are supported: 1 < x < 10 means (1 < x) and (x < 10).

Examples and quick checks

  • 2 + 3 * 4 → multiplication first → 2 + 12 = 14
  • (2 + 3) * 4 → parentheses first → 5 * 4 = 20
  • 5 - 3 - 1 → left-associative → (5 - 3) - 1 = 1
  • 2 ** 3 ** 2 → right-associative → 2 ** (3 ** 2) = 2 ** 9 = 512
  • not 0 and 5not first (not 0 is True) then and → result True.

Good practice: Use parentheses to make complex expressions explicit and readable. That avoids subtle bugs caused by forgetting operator precedence or associativity.

Short code examples (try in Python REPL):

# precedence example
result1 = 2 + 3 * 4    # 14

# parentheses override
result2 = (2 + 3) * 4  # 20

# associativity
a = 5 - 3 - 1          # (5-3)-1 = 1
exp = 2 ** 3 ** 2      # 2 ** (3 ** 2) = 512

# logical and comparison
ok = (10 > 5) and (5 != 0)  # True

print(result1, result2, a, exp, ok)

📌 Examples
  • Final price calculation: final_price = base_price * (1 - discount_rate) * (1 + gst_rate). Precedence: multiplication evaluated before subtraction if no parentheses, so use parentheses to show discount applied first.
  • Average marks: average = (math + physics + chemistry) / 3. Parentheses ensure sum is computed before division.
  • Compound subtraction: x = 10 - 3 - 2 -> evaluated as (10 - 3) - 2 = 5 (left-associative).
  • Exponentiation chaining: val = 2 ** 3 ** 2 -> 2 ** (3 ** 2) = 512 (right-associative).
  • Access check: allow = (age >= 18) and (has_id is True). Comparison evaluated before logical AND.
🧮 Formulas
  1. \[Parentheses first: ( ... )\]
  2. \[Exponentiation: ** (right-associative) -> a ** b ** c = a ** (b ** c)\]
  3. \[Unary operators: +x, -x evaluated before binary + and -\]
  4. \[Multiplicative: *, /, //, % evaluated before additive + and -\]
  5. \[Additive: +, -\]
  6. \[Relational/comparison: ==, !=, <, >, <=, >= (typically after arithmetic)\]
💻13

Input and Output

💻 COMPUTER SCIENCE / IT

Input and Output

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

Definition: Input and Output (I/O) are the ways a program interacts with the outside world. Input is data provided to the program (keyboard, file, network), and output is data produced by the program (screen, file, printer).

Basic console I/O in Python

  • input(prompt): reads a line from the user as a string. The optional prompt is displayed before reading.
  • print(value1, value2, ..., sep=' ', end='\n'): writes values to the console. sep sets separator between values; end sets what follows the printed text (default newline).

Type conversion: input() returns strings. Convert using int(), float(), str(), bool(). Example: n = int(input('Enter n: ')).

Reading multiple values: use split() and map() to parse space-separated inputs:

a, b = map(int, input('Enter two integers: ').split())

Formatted output: use f-strings (Python 3.6+) or format() for readable output:

print(f'Sum of {a} and {b} is {a+b}')
# or
print('Sum = {}'.format(a+b))

File I/O (basic):

  • Open a file: open('file.txt', 'r') (modes: 'r', 'w', 'a', 'rb', 'wb').
  • Preferred pattern: use context manager so files are closed automatically:
    with open('data.txt', 'r') as f:
        contents = f.read()
  • Write: with open('out.txt', 'w') as f: f.write('Hello\n')

Error handling & validation: converting input may raise ValueError. Validate or use try-except:

try:
    x = int(input('Enter an integer: '))
except ValueError:
    print('Invalid number')

Good practices:

  • Prompt clearly (e.g., include units).
  • Validate user input before using it.
  • Prefer context managers for files.
  • Use f-strings for readable formatted output.

📌 Examples
  • Example 1 — Simple input & output: name = input('Enter your name: ') print('Hello,', name)
  • Example 2 — Integer input & arithmetic: a = int(input('Enter first integer: ')) b = int(input('Enter second integer: ')) print(f'Sum = {a + b}')
  • Example 3 — Multiple inputs in one line: # Input: 10 20 x, y = map(int, input('Enter two integers: ').split()) print('Product =', x * y)
  • Example 4 — Read list of numbers and compute average: nums = list(map(float, input('Enter numbers: ').split())) avg = sum(nums) / len(nums) print(f'Average = {avg:.2f}')
  • Example 5 — File I/O (write then read): with open('notes.txt', 'w') as f: f.write('Line 1\nLine 2\n') with open('notes.txt', 'r') as f: print(f.read())
🧮 Formulas
  1. \[Sum of two numbers: sum = a + b\]
  2. \[Average of n numbers: average = (x1 + x2 + ... + xn) / n\]
  3. \[Type conversion: integer = int(string)\]
    \[float = float(string)\]
    \[string = str(value)\]
  4. \[Multiple input parsing: a\]
    \[b = map(int\]
    \[input().split())\]
  5. \[Formatted output (f-string): print(f'Value = {value:.2f}')\]
⚖️14

String Operations and Common Methods

💻 COMPUTER SCIENCE / IT

String Operations and Common Methods

Key Point: Indexing: s[i] where 0 <= i < len(s) or negative indexing s[-k] for k from 1..len(s)

Overview

In Python, a string is an ordered, immutable sequence of characters used to store text. Strings are created by enclosing characters in single (') or double (") quotes or triple quotes for multi-line text. Because strings are immutable, any operation that appears to modify a string actually creates and returns a new string.

Basic Operations

  • Concatenation: join two strings using +. Example: 'Hello' + ' ' + 'World' => 'Hello World'.
  • Repetition: multiply strings by an integer. 'ha' * 3 => 'hahaha'.
  • Indexing: access a single character by position: s[0], s[-1] (last character). Indexing is O(1).
  • Slicing: extract substrings using s[start:stop:step]. Omitting start/stop uses defaults 0/len(s). Slicing returns a new string.
  • Length: len(s) returns the number of characters.
  • Membership: use 'in' and 'not in' to test substring presence.
  • Escapes & Raw Strings: backslash (\) introduces escape sequences (\n, \t). Raw strings r'\path\to' treat backslashes literally.
  • Immutability: modifying means creating a new string, e.g., s = s.replace('a', 'b').

Common Methods (grouped)

  • Case conversions: s.lower(), s.upper(), s.capitalize(), s.title(), s.swapcase()
  • Trimming: s.strip(), s.lstrip(), s.rstrip() remove whitespace (or specified chars)
  • Searching & counting: s.find(sub), s.rfind(sub), s.index(sub) (raises ValueError if not found), s.count(sub)
  • Testing: s.isalpha(), s.isdigit(), s.isalnum(), s.isspace(), s.isupper(), s.islower()
  • Split & join: s.split(sep) returns a list; sep.join(list) joins list into a string
  • Replacing: s.replace(old, new[, count]) returns a new string with replacements
  • Starts/Ends: s.startswith(prefix), s.endswith(suffix)
  • Formatting & padding: 'Hello {}'.format(name), f-strings (f'Name: {name}'), s.zfill(width), s.center(width), s.ljust(width), s.rjust(width)
  • Encoding: s.encode(encoding) to convert to bytes

Performance notes

  • Indexing and len(s) are O(1).
  • Slicing, concatenation, replace, join, split, and other operations typically take O(n) time where n is the length of the resulting or scanned string.
  • To build a large string efficiently from many pieces, gather pieces in a list and use ''.join(list_of_pieces) rather than repeated concatenation.

Small code examples

# indexing & slicing
s = 'Python'
first = s[0]        # 'P'
last = s[-1]        # 'n'
slice_mid = s[1:4]  # 'yth'

# methods
name = '  Alice@example.COM  '
clean = name.strip().lower()    # 'alice@example.com'
parts = clean.split('@')        # ['alice', 'example.com']

# join example
words = ['This', 'is', 'good']
sentence = ' '.join(words)      # 'This is good'

# test example
pwd = 'Abc123'
valid = any(ch.isdigit() for ch in pwd) and any(ch.isalpha() for ch in pwd)

Understanding these operations allows you to parse input, validate text, format output, and manipulate textual data for real-world tasks such as data cleaning, user input handling, report generation, and basic natural-language tasks.

📌 Examples
  • Normalize email input: user_input.strip().lower() to compare or store addresses consistently. Example: ' JOHN@Example.COM ' -> 'john@example.com'.
  • Extract domain from URL: url = 'https://www.example.com/page'; domain = url.split('//',1)[1].split('/',1)[0] -> 'www.example.com'.
  • Validate password composition: check with any(c.isdigit() for c in pwd) and any(c.isalpha() for c in pwd) and len(pwd) >= 8.
  • Create repeated patterns: separator = '-' * 40 creates a 40-character dash line for console output.
  • CSV row build: ','.join([name, age, city]) to create a CSV-formatted line from fields.
🧮 Formulas
  1. \[Indexing: s[i] where 0 <= i < len(s) or negative indexing s[-k] for k from 1..len(s)\]
  2. \[Slicing: s[start:stop:step] (start inclusive\]
    \[stop exclusive)\]
    \[defaults: start=0\]
    \[stop=len(s)\]
    \[step=1\]
  3. \[Length: len(s) -> integer count of characters\]
  4. \[Concatenation: s + t -> new string\]
  5. \[Repetition: s * n where n is non-negative integer\]
  6. \[Find: s.find(sub) returns lowest index or -1\]
    \[s.index(sub) raises ValueError if not found\]
💻15

Simple Programs and Examples

💻 COMPUTER SCIENCE / IT

Simple Programs and Examples

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

Overview: "Simple Programs and Examples" introduces writing small Python programs that illustrate basic concepts: variables, data types, input/output, arithmetic and logical operations, control flow (if, loops), functions and comments. These programs help you understand how the Python interpreter executes statements sequentially and how data is stored and manipulated.

Building blocks:

  • Variables: names that store values (e.g., x = 5).
  • Data types: int, float, str, bool. Use type conversion when needed (int(), float(), str()).
  • Input/Output: input() reads text, print() displays results.
  • Expressions and operators: +, -, *, /, //, %, **, and, or, not, comparison operators (<, >, ==, !=, etc.).
  • Comments: start with # for single-line explanation.
  • Control flow: if/else for decisions; for and while for repetition.

Program structure and execution: A simple program is a sequence of statements executed top-to-bottom. Use meaningful variable names and comments. For example tasks such as computing sums, averages, areas, or simple algorithms (factorial, Fibonacci), you combine input, computation, and output.

Good practices:

  • Readability: use indentation and clear names.
  • Convert input to the right type: e.g., n = int(input('Enter integer: ')).
  • Handle errors lightly in simple programs (brief checks for zero or negative where relevant).

Short code examples (these illustrate common patterns):

# Hello World
print('Hello, World!')

# Sum of two numbers (input, conversion, arithmetic)
a = int(input('Enter first number: '))
b = int(input('Enter second number: '))
print('Sum =', a + b)

# Average of three numbers
x = float(input('x: '))
y = float(input('y: '))
z = float(input('z: '))
avg = (x + y + z) / 3
print('Average =', avg)

# Even / Odd
n = int(input('n: '))
if n % 2 == 0:
    print(n, 'is even')
else:
    print(n, 'is odd')

# Factorial (iterative)
def factorial(n):
    result = 1
    i = 1
    while i <= n:
        result *= i
        i += 1
    return result

print('5! =', factorial(5))
📌 Examples
  • Hello World: print('Hello, World!') — the first simple program to learn syntax and output.
  • Sum of two numbers: a = int(input('Enter a: ')); b = int(input('Enter b: ')); print('Sum =', a + b) — shows input, type conversion, arithmetic.
  • Temperature converter (Celsius to Fahrenheit): c = float(input('C: ')); f = (9/5) * c + 32; print('F =', f) — real-life utility converting units.
  • Simple interest calculator: p = float(input('Principal: ')); r = float(input('Rate%: ')); t = float(input('Time (yrs): ')); si = (p * r * t) / 100; print('Simple Interest =', si).
  • Swap two numbers without third variable: a, b = b, a — demonstrates tuple unpacking as a Pythonic trick.
  • Fibonacci sequence (first n terms): use a loop to generate sequence and print or store values — useful to demonstrate iteration and lists.
🧮 Formulas
  1. \[Sum of two numbers: S = a + b\]
  2. \[Average of n numbers: avg = (x1 + x2 + ... + xn) / n\]
  3. \[Simple Interest: SI = (P * R * T) / 100 (P = principal\]
    \[R = rate%\]
    \[T = time in years)\]
  4. \[Area of rectangle: A = length * breadth\]
  5. \[Area of circle: A = π * r^2 (use math.pi in Python or 3.14159)\]
  6. \[Perimeter of circle (circumference): C = 2 * π * r\]
💻16

Errors and Exceptions (Introduction)

💻 COMPUTER SCIENCE / IT

Errors and Exceptions (Introduction)

Key Point: try: except : else: finally:

What are Errors and Exceptions?

In Python (and in programming), an error is a problem in the program that either prevents the program from running (compile-time/syntax error) or causes it to fail while running (runtime error). An exception is a runtime event that interrupts normal program flow; it can be caught and handled using exception-handling constructs.

Why this matters (CBSE context): Programs must be robust. Understanding errors and exceptions helps you find bugs, prevent crashes, and write safe programs that behave predictably under unexpected conditions.

Main categories

  • Syntax Errors (Compile-time): Mistakes in code structure (e.g., missing colon, wrong indentation). The interpreter reports these before execution continues.
  • Runtime Errors / Exceptions: Errors that occur during execution (e.g., dividing by zero, accessing missing list index). These raise exception objects that can be handled.
  • Logical Errors: Program runs without crashing but gives incorrect results (e.g., wrong formula). These are found by testing and debugging.

Common Python exceptions: ZeroDivisionError, NameError, TypeError, IndexError, KeyError, ValueError, ImportError, IndentationError.

Exception handling constructs (concept): Use try to run code that may fail, except to handle specific exceptions, else to run when no exception occurs, and finally to run cleanup code whether or not an exception occurred.

Simple flow: try → (if exception occurs) except → finally → end. If no exception: try → else → finally → end.

How exceptions help: They separate normal code from error-handling code, allow selective handling of problems, and let you either recover from an error or fail gracefully with a meaningful message.

Best practices

  • Catch specific exception types rather than a bare except.
  • Use finally to release resources (files, network connections).
  • Use raise to create meaningful exceptions in your functions when preconditions fail.
  • Use assert for debugging checks (not for regular runtime error handling).

Short code examples:

# Handling division by zero
try:
    result = 10 / 0
except ZeroDivisionError:
    print('Cannot divide by zero')
else:
    print('Result is', result)
finally:
    print('End of operation')

# Raising an exception for invalid input
if age < 0:
    raise ValueError('Age cannot be negative')

# Using assert for a sanity-check
assert len(name) > 0, 'name must not be empty'

Summary: Errors stop or alter program execution. Exceptions are runtime events you can catch and handle to make programs robust. Learning to recognize and handle common exceptions is an essential skill in Class 11 Computer Science.

📌 Examples
  • Real-life analogy: Driving a car — a red traffic light is an event that interrupts normal driving (like an exception). You can handle it by stopping (exception handling). A flat tire while on a trip is an unexpected problem you must handle to continue.
  • Division by zero (Python): try: x = 5 / 0 except ZeroDivisionError: print('Handle division by zero')
  • Missing list index (Python): mylist = [10, 20] try: print(mylist[5]) except IndexError: print('Index out of range')
  • Invalid numeric input (Python): try: n = int('abc') except ValueError: print('Cannot convert to integer')
  • Raising an exception in a function (Python): def withdraw(balance, amount): if amount &gt; balance: raise ValueError('Insufficient funds') return balance - amount
🧮 Formulas
  1. \[try: <risky_statements> except <ExceptionType>: <handler_statements> else: <statements_if_no_exception> finally: <cleanup_statements>\]
  2. \[raise <ExceptionType>(<message>) # create/propagate an exception\]
  3. \[assert <condition>, <message> # check assumptions during debugging\]
💻17

Good Programming Practices

💻 COMPUTER SCIENCE / IT

Good Programming Practices

Key Point: Time complexity basics (informal): - Single loop over n items: O(n) - Nested loop over n items twice: O(n^2) - Binary search on sorted list: O(log n) (These describe how time grows as input size n grows.)

Good programming practices are simple rules and habits that make code easier to read, maintain, test, and reuse. They are especially useful for beginners in Class 11 who are learning Python. Following these practices reduces bugs, improves collaboration, and helps you develop programmes that last.

Key practices (with short explanation):

  • Meaningful names: Use descriptive variable, function and constant names so the purpose is clear (for example, student_count rather than n).
  • Consistent naming conventions: In Python use snake_case for variables and functions (e.g., calculate_total) and CamelCase for classes (e.g., StudentRecord).
  • Indentation and spacing: Use 4 spaces per indentation level. Proper spacing around operators and after commas improves readability.
  • Comments and documentation: Write short comments to explain why (not what) and use docstrings for functions to describe purpose, parameters and return values.
  • Modularity and functions: Break large tasks into small functions, each doing one thing (single responsibility). This makes testing and reuse easier.
  • Avoid hardcoding (magic numbers): Use named constants for values that may change (e.g., MAX_STUDENTS = 30).
  • Error handling and input validation: Validate inputs and use try/except to handle runtime errors gracefully.
  • Don't repeat yourself (DRY): Avoid copying similar code; use functions or loops instead.
  • Keep it simple (KISS): Prefer simple, clear solutions over clever but obscure ones.
  • Testing and debugging: Test small parts separately, use prints or a debugger to trace errors, and write simple test cases.
  • Version control and backups: Save versions of code (even simple copies) or use tools like Git when collaborating.

Benefits: better readability, easier maintenance, fewer bugs, simpler testing, and easier teamwork.

Short Python example showing several practices (indentation, meaningful names, docstring, input validation, error handling, constants and main guard):

MAX_AGE = 120  # constant in uppercase (no magic number)
def get_positive_integer(prompt):
    '''Read an integer from user and ensure it is positive.'''
    while True:
        try:
            value = int(input(prompt))
            if value > 0:
                return value
            print('Please enter a positive integer.')
        except ValueError:
            print('Invalid input. Enter an integer.')


def calculate_age_in_days(age_years):
    '''Return approximate age in days using 365 days per year.'''
    return age_years * 365


if __name__ == '__main__':
    age = get_positive_integer('Enter age in years: ')
    if age > MAX_AGE:
        print('Age seems unrealistic. Please check input.')
    else:
        days = calculate_age_in_days(age)
        print(f'Approx age in days: {days}')

Follow standards such as PEP 8 (Python style guide) as you advance. Start small: use clear names, keep functions short, and comment only when needed. These habits will make learning and collaborating easier.

📌 Examples
  • Factorial function with docstring, validation and meaningful names: '''def factorial(n): '''Return factorial of non-negative integer n.''' if n < 0: raise ValueError('n must be non-negative') result = 1 for i in range(1, n + 1): result *= i return result '''
  • Safe integer input using try/except and a loop: '''def read_int(prompt): while True: try: return int(input(prompt)) except ValueError: print('Please enter a valid integer') '''
  • Using constants instead of magic numbers: '''MAX_STUDENTS = 30 if current_students > MAX_STUDENTS: print('Cannot admit more students') '''
  • Modular program with main guard: '''def main(): # program logic here pass if __name__ == '__main__': main() '''
🧮 Formulas
  1. \[Time complexity basics (informal): - Single loop over n items: O(n) - Nested loop over n items twice: O(n^2) - Binary search on sorted list: O(log n) (These describe how time grows as input size n grows.)\]
  2. \[Space-time trade-off: using extra memory (space) can sometimes reduce time\]
    \[No single formula\]
    \[but note higher space for faster lookup (e.g.\]
    \[using a dictionary).\]
  3. \[Basic example calculations: - Linear operation count: for i in range(n): count += 1 -> operations ~ n - Nested loops: for i in range(n): for j in range(n): -> operations ~ n * n = n^2\]
💻18

Useful Built-in Functions and Help

📐 MATHEMATICAL FORMULA / THEOREM

Useful Built-in Functions and Help

Key Point: len(s) -> integer length of sequence or collection

Overview
Python provides many built-in functions that make common tasks easy — reading input, converting types, operating on sequences, computing simple statistics, and inspecting objects. Knowing the frequently used built-ins and how to use help() makes learning and debugging faster.

Common groups of built-in functions

  • Input / Output: print(...) to display, input(prompt) to read a line as a string.
  • Type conversion: int(x), float(x), str(x), bool(x).
  • Numeric helpers: abs(x), round(x, n), pow(x, y), divmod(a,b).
  • Sequence / collection helpers: len(s), sum(iterable), min(...), max(...), sorted(iterable), reversed(seq), enumerate(iterable), zip(...).
  • Introspection & help: type(x), dir(obj), help(obj), and the __doc__ attribute.

How to use help()
Type help(name) in the interactive interpreter (or in a Jupyter cell) to see the documentation string and usage examples for a function, class or module. Example: help(sorted) or help(str.replace). If you call help() with no arguments you enter an interactive help system.

Introspection with dir() and __doc__
Use dir(obj) to list attributes and methods of an object. Use object.__doc__ or help(object) to read the documentation string for quick guidance.

Practical notes and tips

  • Prefer int()/float() for explicit conversions rather than relying on implicit conversions.
  • Use sum(list) and len(list) to compute averages: avg = sum(lst) / len(lst) (ensure len>0).
  • Learn enumerate() to get index+value pairs instead of managing an index variable.
  • Use sorted(..., key=..., reverse=...) to sort complex items (e.g., sort students by score).
  • If a function name is unknown, use help() or search online using the exact function name; Python docs are authoritative.

Short code snippets (inside interpreter)

# read a number and print its absolute value
n = int(input('Enter integer: '))
print('Absolute:', abs(n))

# average of numbers
nums = [10, 20, 30]
avg = sum(nums) / len(nums)
print('Average:', avg)

# showing available methods and doc
print(dir(str))          # list string methods
print(str.replace.__doc__)  # docstring for replace
help(sorted)             # detailed help for sorted

Real-life use: A teacher uses input() to enter students' marks, sum() and len() to compute class average, sorted() to display top performers, and help() to check how to use sorted() with a key function.

📌 Examples
  • Example 1 — Compute average and top score: code: nums = [72, 85, 64, 91, 78] avg = sum(nums) / len(nums) print('Average:', round(avg, 2)) print('Top score:', max(nums)) explanation: Uses sum(), len(), round(), and max().
  • Example 2 — Using enumerate while printing index and value: code: names = ['Asha', 'Rahul', 'Meera'] for i, name in enumerate(names, start=1): print(i, name) explanation: enumerate() provides the index so you don't need a separate counter.
  • Example 3 — Type conversion and error handling: code: val = input('Enter an integer: ') try: n = int(val) print('Double:', 2 * n) except ValueError: print('Please enter a valid integer') explanation: int() converts string to integer; handle ValueError when input is invalid.
  • Example 4 — Using help() and __doc__: code: print('Methods of list:', dir(list)) print('Doc for list.append:\n', list.append.__doc__) # or just call # help(list.append) explanation: dir() lists attributes; __doc__ gives the method documentation; help() shows richer docs.
  • Example 5 — Sorting students by score using sorted with key: code: students = [('Asha', 85), ('Rahul', 92), ('Meera', 88)] by_score = sorted(students, key=lambda x: x[1], reverse=True) print(by_score) explanation: sorted(..., key=...) sorts tuples by the second item (score).
🧮 Formulas
  1. \[len(s) -> integer length of sequence or collection\]
  2. \[type(x) -> returns the type object of x (e.g., <class 'int'>)\]
  3. \[int(x) / float(x) / str(x) -> type conversions (may raise ValueError for invalid input)\]
  4. \[sum(iterable) -> numeric total of elements\]
  5. \[min(iterable)\]
    \[max(iterable) -> smallest and largest elements\]
  6. \[sorted(iterable\]
    \[key=None\]
    \[reverse=False) -> returns a new sorted list\]

Key Concepts

Python
A high-level, interpreted, general-purpose programming language known for readable syntax and quick development.
Interpreter
A program that executes Python code line by line without a separate compilation step.
REPL
Read–Eval–Print Loop: the interactive Python prompt where you type expressions and get immediate results.
IDLE
Integrated Development and Learning Environment bundled with Python for editing, running and debugging code.
Script
A file (usually .py) containing a sequence of Python statements to be executed by the interpreter.
Statement
A complete instruction in Python that performs an action, such as assignment or a function call.
Expression
A combination of values, variables and operators that evaluates to a single value.
Variable
A named storage location that holds a value which can be changed during program execution.
Identifier
A name used for variables, functions or classes; must start with a letter or underscore and not be a keyword.
Keyword
A reserved word that has a special meaning in Python and cannot be used as an identifier.
Data type
Classification of values that determines the operations possible on them (e.g., int, float, str, bool).
Integer
A data type representing whole numbers without fractional parts.
Float
A data type representing real numbers with a decimal point.
String
A sequence of characters enclosed in single or double quotes.
Boolean
A data type with two values: True or False, often used in conditions.
Comment
Non-executing text in code used to explain or document; single-line comments start with #.
Indentation
Leading whitespace used in Python to define code blocks (no braces); consistent indentation is required.
input()
Built-in function that reads a line of text from the user and returns it as a string.
print()
Built-in function that displays values to the console with optional separators and end character.
Type conversion (casting)
Explicitly converting a value from one data type to another using functions like int(), float(), str().

Practice Questions

  1. List any four key features of Python that make it suitable for beginners. / पायथन की कोई चार प्रमुख विशेषताएँ बताइए जो इसे शुरुआती लोगों के लिए उपयुक्त बनाती हैं।
    Show answer

    Python is interpreted (run line by line), has a readable indentation-based syntax, is dynamically typed (no type declarations), and ships with an extensive standard library; it is also cross-platform. / पायथन इंटरप्रेटेड है (पंक्ति-दर-पंक्ति चलता है), इसका इंडेंटेशन-आधारित पठनीय सिंटैक्स है, यह डायनैमिकली टाइप्ड है (टाइप घोषित करने की आवश्यकता नहीं), और इसमें विस्तृत मानक लाइब्रेरी होती है; यह क्रॉस-प्लेटफ़ॉर्म भी है।

  2. What is the difference between an interpreter and a compiler in the context of how Python runs? / पायथन कैसे चलता है, इस संदर्भ में इंटरप्रेटर और कंपाइलर में क्या अंतर है?
    Show answer

    An interpreter executes source code line by line without a separate executable step, which is how Python runs, whereas a compiler translates the whole program into machine code first and then runs the executable. / इंटरप्रेटर स्रोत कोड को बिना अलग एग्जीक्यूटेबल चरण के पंक्ति-दर-पंक्ति निष्पादित करता है, पायथन इसी तरह चलता है, जबकि कंपाइलर पहले पूरे प्रोग्राम को मशीन कोड में अनुवादित करता है और फिर एग्जीक्यूटेबल चलाता है।

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

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

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

    input() always returns a string, so it must be converted to a number using int() or float() before arithmetic, for example n = int(input()). / input() हमेशा एक स्ट्रिंग लौटाता है, इसलिए अंकगणित से पहले इसे int() या float() का उपयोग करके संख्या में बदलना होता है, जैसे n = int(input())।

  5. Predict the output of the expression 3 + 4 * 2 ** 2 and explain using operator precedence. / व्यंजक 3 + 4 * 2 ** 2 का आउटपुट बताइए और संक्रिया अग्रता का उपयोग करके समझाइए।
    Show answer

    Exponent first: 2 ** 2 = 4; then multiplication: 4 * 4 = 16; then addition: 3 + 16 = 19, because ** has highest precedence, then *, then +. / पहले घात: 2 ** 2 = 4; फिर गुणा: 4 * 4 = 16; फिर जोड़: 3 + 16 = 19, क्योंकि ** की सर्वोच्च अग्रता है, फिर *, फिर +।

  6. Write a Python program to convert a Celsius temperature entered by the user into Fahrenheit. / उपयोगकर्ता द्वारा दर्ज सेल्सियस तापमान को फ़ारेनहाइट में बदलने के लिए एक पायथन प्रोग्राम लिखिए।
    Show answer

    c = float(input('Celsius: ')); f = (c * 9/5) + 32; print('Fahrenheit =', f) uses the formula F = (C * 9/5) + 32. / c = float(input('Celsius: ')); f = (c * 9/5) + 32; print('Fahrenheit =', f) सूत्र F = (C * 9/5) + 32 का उपयोग करता है।

  7. Name the categories of Python tokens and give one example of each. / पायथन टोकनों की श्रेणियाँ बताइए और प्रत्येक का एक उदाहरण दीजिए।
    Show answer

    Tokens include keywords (if), identifiers (score), literals (42), operators (+), and delimiters (such as the colon : or comma ,). / टोकनों में कीवर्ड (if), आइडेंटिफायर (score), लिटरल (42), ऑपरेटर (+), और डिलिमिटर (जैसे कोलन : या कॉमा ,) शामिल हैं।

  8. Why is consistent indentation mandatory in Python, and what error results if it is wrong? / पायथन में सुसंगत इंडेंटेशन अनिवार्य क्यों है, और गलत होने पर कौन-सी त्रुटि आती है?
    Show answer

    Python uses indentation (not braces) to define blocks/suites, so all statements in a block must share the same indentation; inconsistent 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 249 content files · LLOS Learn · browse all chapters