L
LLLOS.ai
Learn
L

Chapter 12 — Introduction to python

Class 11 · Computer Science

Overview

This unit introduces Python programming to Class 11 Computer Science students. It covers the basic concepts, Python syntax, data types, operators, control structures, functions, strings and collections, file handling, error handling, modules, basic algorithms and a small project that brings these pieces together. Emphasis is on writing correct, readable code: using functions to organise tasks, choosing appropriate data structures and handling user input and files safely. Students learn to trace program flow, debug simple errors and apply standard library modules for common tasks. Practical examples reinforce concepts such as iteration, recursion and searching/sorting. This foundation matters because Python is widely used as a first language in schools and colleges and is also a practical tool in data processing, scripting and problem solving. Mastery of these basics prepares students for ISC level topics, project work and competitive programming where clear logic, correct use of data structures and careful input/output handling are crucial.

Learning Objectives

  • Understand and use the Python programming environment to write and execute simple programs.
  • Declare and manipulate basic data types: integers, floats, strings and booleans.
  • Apply decision-making constructs (if, if-else, elif) to implement conditional logic.
  • Use loops (for, while) and control statements (break, continue) to perform repetitive tasks.
  • Define and call functions with parameters and return values to structure programs.
  • Work with Python collections: lists, tuples, sets and dictionaries and perform common operations.
  • Read from and write to text files safely and use file I/O in simple applications.
  • Identify and handle runtime errors using try-except and use basic debugging techniques.

Topics in this chapter

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

🌍1

Introduction to Python and setting up the environment

What Python is and where it is used
Python is a high-level, interpreted programming language designed for readability and rapid development. It supports procedural and object-oriented programming, and offers many built-in libraries for common tasks. Because its syntax is concise and close to natural language, beginners can focus on problem solving instead of low-level details. Python is used for scripting, data analysis, web development, automation, scientific computing and teaching.

Choosing the right version and installing
Use Python 3.x for all new learning. Installation on Windows, macOS or Linux is straightforward: download from the official source or use a distribution. Many systems come with Python preinstalled (often on Linux and macOS). For students, an easy option is an installer that adds python and pip to PATH. Check the installed version by running python --version or python3 --version in a terminal or command prompt.

Interactive vs script mode
Interactive mode (REPL) lets you type statements and see results immediately; it is excellent for testing small expressions and learning. Start by typing python or python3 in a terminal then experiment with arithmetic and functions. Script mode is how real programs are written: save code in a file with .py extension and run it using python filename.py. Scripts are repeatable and saved for later editing.

IDEs and editors
An Integrated Development Environment (IDE) like IDLE, Thonny or Visual Studio Code helps students by providing editing, running and debugging tools. Choose an environment with syntax highlighting and an easy run button. Use version control (simple backups) for projects if comfortable.

First program and basic workflow
Create a file hello.py containing print('Hello, World!') and run it. Learn a basic workflow: edit -> save -> run -> test -> debug. Use comments with # to explain code; write readable names for files and variables. Practice small programs often, test edge cases, and keep code modular by separating tasks into functions.

Safety and good habits
Be cautious when copying code from unknown sources. Always test with simple inputs first and keep a backups folder for school assignments. Learn to read error messages when a program fails—they give clues to the problem and help you learn. This unit uses these fundamentals as the basis for the rest of the topics.

📌 Examples
  • Create hello.py with: print('Hello, World!') and run using python hello.py.
  • Open Python interactive shell and try arithmetic: >>> 7*8 and >>> 'Hi'.upper().
  • Use an IDE to create a new file, run it and fix a deliberate syntax error to see error messages.
🧮 Formulas
  1. Print: print(expression)
  2. Comment: # This is a comment
📊 Visual ideas
A simple flow chart showing 'Start -> Execute script -> print output -> End' to represent program execution.
📊2

Variables, identifiers and basic data types

Understanding variables and identifiers
Variables are names that hold values. In Python you bind a name to a value using the assignment operator =. An identifier is the name you choose for a variable; it must start with a letter (a–z, A–Z) or underscore (_) and may contain letters, digits and underscores. Identifiers are case-sensitive: Total and total refer to different variables. Choose meaningful names like student_name or total_marks to document purpose.

Primary data types
Python has several basic data types that you will use frequently:

  • int – integers, e.g., 42, -7. Python integers have arbitrary precision.
  • float – floating-point numbers, e.g., 3.14, -0.5. Use these for fractional values.
  • str – strings, sequences of Unicode characters enclosed in single or double quotes: 'hello' or "hello".
  • bool – boolean values True and False, often results of comparisons.

Dynamic typing and type safety
Python is dynamically typed: the interpreter keeps track of types at run time, so the same variable can be reassigned to a value of a different type (x = 10 then x = 'ten'). This flexibility helps rapid development but requires attention: avoid mixing types unintentionally. Using consistent types reduces errors and makes code easier to understand and maintain.

Type inspection and conversion
Use type(x) to inspect the type of a value. Convert between types explicitly with int(), float(), str() and bool(). For example, int('123') gives 123. Converting invalid strings leads to ValueError; handle such cases by validating input first or using try-except.

Literals and representation
Numeric literals can include underscores for readability (e.g., 10_000). Strings may be single-line or multi-line (triple quotes). Boolean values are capitalised True and False. Understand that some operations behave differently by type: + adds numbers but concatenates strings.

Best practices
Initialise variables before use, keep names descriptive but not overly long, and avoid using Python built-in names (e.g., list, str) as variable names. Keep related variables grouped and comment where meaning is not obvious. These simple habits prevent many beginner mistakes and improve program clarity.

📌 Examples
  • age = 16 # integer; print(type(age)) shows <class 'int'>
  • height = 1.65 # float; bmi = weight / (height*height)
  • name = 'Rita' and greeting = f'Hello, {name}' to combine variables in strings
🧮 Formulas
  1. Assignment: variable = expression
  2. Type conversion: int(x), float(x), str(x), bool(x)
📊 Visual ideas
Diagram of a variable box labeled 'age' pointing to value 16, and 'name' pointing to 'Rita'.
A small table showing examples: 10 -> int, 2.5 -> float, 'hi' -> str, True -> bool.
💻3

Operators and expressions

What are operators?
Operators are symbols or words that perform operations on values to produce new values. Expressions combine values, variables and operators and are evaluated by Python to yield results. Familiarity with operator classes helps you write correct conditions and calculations.

Arithmetic operators
Standard arithmetic operators are + (addition), - (subtraction), * (multiplication), / (true division), // (floor or integer division), % (modulus or remainder) and ** (exponent). Note: / always returns a float even for divisible integers; // returns the floor integer for mixed types. Modulus gives the remainder: 7 % 3 = 1.

Comparison operators
Compare values with == (equal), != (not equal), <, >, <= and >=. Comparisons return boolean values True or False. Chained comparisons are allowed (e.g., 0 < x <= 10) and are evaluated logically in sequence.

Logical operators
and, or and not combine boolean expressions. Use parentheses to make complex conditions clear: (x > 0 and x <= 100) or not valid. Remember Python follows short-circuit evaluation: in (A and B), if A is False, B is not evaluated.

Membership and identity operators
in checks if an element is present in a sequence (e.g., 'a' in 'cat' True). is checks object identity (whether two names refer to the same object) — use equality (==) to compare values, not is, except when checking for singletons like None (x is None).

Assignment and augmented assignment
= assigns a value to a name. Augmented assignment operators combine an operation and assignment: x += 1 updates x by adding 1. They provide concise code and may be slightly more efficient.

Operator precedence and associativity
Operators have an order of evaluation; parentheses override precedence. Exponentiation has higher precedence than multiplication/division, which have higher precedence than addition/subtraction, then comparisons, then logical operators. When in doubt, use parentheses to state intent clearly.

Expression planning
Break complex expressions into sub-expressions using temporary variables to make code easier to read and debug. This is especially helpful when combining arithmetic with function calls or conditionals.

📌 Examples
  • Area: area = length * breadth using * for multiplication.
  • Even check: if n % 2 == 0: print('Even') using modulus operator.
  • Augmented: x = 5; x += 3 # now x is 8
🧮 Formulas
  1. Arithmetic: +, -, *, /, //, %, **
  2. Comparison: ==, !=, <, >, <=, >=
  3. Logical: and, or, not
  4. Augmented assignment: x += y, x *= y
📊 Visual ideas
A precedence pyramid diagram showing parentheses at top, then **, then *,/,//,%, then +,-, then comparisons, then logical operators.
💻4

Input and output (I/O)

Basic output with print()
Use print() to display values and messages to the screen. It can take multiple arguments and separates them by a space by default: print('Sum is', total). The end parameter controls what prints at line end (default '\n'); use print(x, end=' ') to avoid new line. For formatted output, Python supports f-strings: name = 'Asha'; print(f'Hello, {name}') inserts variable values directly into text.

Taking input from the user
input(prompt) reads a line of text from the user and returns it as a string. Always provide a prompt so the user knows what to enter: age_str = input('Enter age: '). Convert the string to other types as needed: age = int(age_str). Handle invalid input using try-except or validation logic to avoid program crashes.

Reading multiple inputs
Commonly, several values are given in one line separated by spaces. Use split() to break the input into parts and map() to convert types: a, b = map(int, input().split()). For other separators, pass an argument to split(',') or use strip() to trim whitespace before splitting.

Formatting numbers and strings
Format decimals with f-strings or format(): print(f'Marks: {score:.2f}') shows two decimal places. Use padding to align columns: print(f'{name:10s}{score:6.2f}') for simple tabular output in the console.

File I/O basics
To store data persistently, open files using open(filename, mode) and perform read or write operations. Modes include 'r' (read), 'w' (write), 'a' (append) and 'r+' (read/write). Prefer using with open(...) as f: to ensure the file is closed automatically even if errors occur. Read using f.read(), f.readline(), or iterate for line in f: to process large files efficiently.

Practical tips
Never trust raw user input; validate and convert carefully. For files, use encoding='utf-8' when needed and check for FileNotFoundError when opening. Test I/O code with sample inputs and files to ensure correct behaviour before using in larger programs.

📌 Examples
  • Prompt and read: name = input('Name: '); print(f'Welcome, {name}')
  • Read two ints: a, b = map(int, input().split()); print(a + b)
  • Write to file: with open('out.txt', 'w') as f: f.write('Hello\n')
🧮 Formulas
  1. Read input: s = input(prompt)
  2. Read multiple: a, b = map(int, input().split())
  3. Open file: with open(filename, mode) as f: ...
📊 Visual ideas
Diagram showing keyboard -> program (input()) -> processing -> print() -> screen.
File flow: program <-> file on disk with arrows showing read and write.
💻5

Control flow: if, if-else and nested if

Decision making in programs
Control flow allows programs to choose different actions based on conditions. The basic building block is the if statement. An if statement evaluates a condition; if it is True, the indented block after it executes. Otherwise the block is skipped. This simple mechanism lets programs respond differently to different inputs or computed values.

If-else and elif for multiple branches
When a choice between two alternatives is needed, use if ... else. For more than two mutually exclusive possibilities, use if ... elif ... elif ... else. Python evaluates each condition in order until one is True and then executes its block, skipping the rest. This avoids nested indentation for clear sequential checks, for example when assigning grades based on marks ranges.

Combining conditions with logical operators
Conditions are expressions that return boolean values; combine them with and, or and not to form complex tests. Parentheses improve readability and control evaluation order in compound conditions. Remember Python uses short-circuit evaluation: in A and B, if A is False, B is not evaluated; in A or B, if A is True, B is not evaluated. This behaviour can be used to avoid unnecessary or unsafe evaluations (such as avoiding indexing when a list is empty).

Nested if statements and design considerations
Sometimes a test only makes sense when a previous condition is True; nested if statements express this: first check a high-level condition, then inside its block check a more specific condition. However, deep nesting makes code harder to read and maintain. Where possible, combine conditions or extract code into functions to flatten control flow and improve clarity. Use elif chains instead of nested if-else where checks are at the same level.

Truthiness and common pitfalls
In Python many objects have truth values beyond True/False: non-empty sequences and non-zero numbers are truthy; empty sequences, 0 and None are falsy. This allows compact expressions like if lst: to check for non-empty lists. Be explicit when clarity matters, and avoid relying on subtle truthiness rules for critical conditions. Also remember that assignment = is not allowed in conditions; use == for comparison.

Practical examples and testing
Use small test cases and boundary values to ensure conditions classify inputs correctly. For example, when checking ranges use <= and >= consciously to avoid gaps or overlaps. Use unit tests or simple input-output checks to verify behavior. Document assumptions such as whether 75 marks qualifies for grade B or A to keep logic transparent for evaluators.

📌 Examples
  • Check sign: if n>0: print('Positive') elif n==0: print('Zero') else: print('Negative')
  • Pass/fail: if marks>=35: print('Pass') else: print('Fail')
  • Nested: if registered: if paid: allow_entry() else: print('Pay fee') else: print('Register first')
🧮 Formulas
  1. if condition: statements elif condition: statements else: statements
📊 Visual ideas
Flowchart with a decision diamond showing a condition true branch and false branch leading to different steps.
A tree diagram showing if -> elif -> else branches for grade classification.
💻6

Loops: while and for

Why use loops?
Loops let a program repeat code until a condition changes or until items in a sequence are processed. They prevent code duplication and are central to tasks such as summing values, searching, generating lists and automating repetitive work.

The while loop
while condition: body repeats as long as the condition remains True. Use while when the number of iterations is not known in advance and depends on dynamic conditions like user input. Always ensure the loop’s body changes state so the condition will become False; otherwise an infinite loop occurs. Use break inside a while to exit early when needed.

The for loop
for variable in sequence: body iterates over each element of a sequence (list, string, tuple) or over numbers produced by range(). For is the natural choice when you have a known sequence or number of iterations. In Python, for abstracts the iterator protocol so it works with many iterable types.

range() and numeric loops
range(start, stop, step) generates integer sequences for loops. range(stop) starts at 0. Values from range are memory-efficient and commonly used for indexed loops. Use for i in range(len(lst)): when you need indexes, or enumerate(lst) to get both index and element neatly.

Control statements: break & continue
break exits the loop immediately, useful when a search finds the target. continue skips to the next iteration, useful to ignore certain items. Use them sparingly; overuse can make code hard to follow. The optional else clause on loops runs when the loop finishes normally (no break) and is handy for search patterns to detect absence.

Nested loops and complexity
Loops can be nested to process 2D data like matrices. Be mindful of performance: nested loops often have quadratic time complexity (O(n^2)) and become slow for large inputs. Prefer algorithmic improvements when possible. Practice by tracing loop execution with small inputs to understand iteration counts and effects of break/continue.

📌 Examples
  • while example: n = 5; while n>0: print(n); n -= 1
  • for example: for i in range(1,11): print(i) prints 1 to 10.
  • Use enumerate: for i, val in enumerate(['a','b']): print(i, val)
🧮 Formulas
  1. while condition: statements
  2. for variable in sequence: statements
  3. range: range(start, stop, step)
📊 Visual ideas
Flowchart showing loop start, test condition, body, update and loop back.
Diagram illustrating nested loops with outer and inner iteration counts.
💻7

Functions: definition, parameters and return values

Why functions matter
Functions allow you to encapsulate a task into a named block of code which can be reused. They reduce repetition, make programs modular and easier to test. Breaking a program into functions clarifies its structure and helps in debugging and maintenance.

Defining functions
Use def function_name(parameters): followed by an indented block. The parameter list specifies names that receive values when the function is called. A docstring (a short string literal under the def line) documents the function’s purpose and expected inputs and outputs. Good docstrings make functions easier to use and maintain. For example:

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

Calling and returning
Call a function by writing its name and passing arguments in parentheses: result = add(3, 4). Use return to send a value back; if no return is present the function returns None. Functions can return multiple values as tuples which the caller can unpack: q, r = divmod(7, 3). Returning values rather than printing them makes functions more reusable and easier to test.

Parameters and argument types
Parameters can be positional or keyword-based. Default parameter values make some arguments optional: def greet(name='Student'): print(f'Hello, {name}'). Python also supports variable-length positional arguments (*args) and variable-length keyword arguments (**kwargs) for flexible function interfaces. Use these features when the exact number of inputs is not fixed.

Scope, side effects and purity
Variables defined inside a function are local and do not affect variables outside, unless declared global (which is discouraged). A function that modifies external state (like writing to a file or changing a global variable) has side effects. Prefer functions that compute and return values (pure functions) when possible, because they are easier to reason about and test. Use side effects only when the task requires interaction with the outside world.

Error handling and validation
Validate parameters and handle expected errors inside functions using try-except where necessary. For example, a divide function can check divisor != 0 and raise ValueError or return a special value. Document preconditions and postconditions in the function docstring so callers know how to use it safely.

Testing and decomposition
Write small functions that do one job and test them independently. Compose larger behaviour by calling functions from a main routine. Use simple assertions during development: assert condition, 'error message' to catch incorrect assumptions early. Clear function design speeds up development and simplifies debugging.

📌 Examples
  • Simple add: def add(a, b): return a + b ; print(add(3,4)) gives 7.
  • Default parameter: def greet(name='Student'): print(f'Hello, {name}')
  • Return multiple: def divmod(a, b): return a//b, a%b ; q, r = divmod(7,3)
🧮 Formulas
  1. Function definition: def name(parameters): statements return value
  2. Default param: def f(a, b=10): ...
  3. Variable args: def f(*args, **kwargs): ...
📊 Visual ideas
A block diagram showing main program calling a function with parameters and receiving a return value.
Call stack sketch showing main -> function -> return to main.
⚖️8

Strings: operations and methods

Strings as sequences
Strings are ordered sequences of characters. Each character has an index: s[0] gives the first character and s[-1] gives the last. Because strings are sequences, you can slice them: s[start:stop] returns characters from start up to but not including stop. Slices can include a step: s[::2] picks every second character. Important: strings are immutable, so slicing and other operations produce new strings rather than modifying the original.

Basic operations and concatenation
Concatenate strings with + and repeat with *. Use len(s) to get length and the membership operator in to check presence of a substring. Converting between types is common: str() casts values to strings for printing, while int() and float() parse numeric strings when valid. Be mindful of whitespace when parsing and trim using strip() when necessary.

Useful built-in methods
Python provides many helpful string methods: lower()/upper() change case; strip(), lstrip(), rstrip() remove surrounding whitespace; split(sep) breaks a string into a list of substrings based on a separator (default whitespace); join(iterable) combines a list of strings into one with a separator. replace(old, new) substitutes all occurrences, while find(sub) returns the index of the first occurrence or -1 if absent. startswith() and endswith() test prefixes and suffixes efficiently.

Formatting text
F-strings (f"...") allow embedding expressions directly into string literals, for example f"Name: {name}, Score: {score:.2f}" prints score with two decimal places. The format() method provides additional control for alignment and padding. Use formatting to generate readable tables or to ensure numeric precision in outputs.

Escape sequences and raw strings
Escape sequences like \n (newline), \t (tab) and \\" (double quote) represent special characters inside string literals. Raw strings prefixed with r""" treat backslashes literally and are useful for Windows file paths and simple regular expressions: r"C:\data\file.txt".

Unicode and encoding
Python 3 strings are Unicode by default, allowing many scripts and symbols. When reading or writing files, specify encoding='utf-8' to avoid unexpected errors. For tasks in this class, basic Unicode support is enough, but be aware that some characters may combine in ways that affect length or equality comparisons in advanced scenarios.

📌 Examples
  • Split and join: words = 'a b c'.split(); ','.join(words) gives 'a,b,c'.
  • Slice: s = 'python'; s[1:4] gives 'yth'.
  • Case-insensitive compare: if s.lower() == 'yes': ...
🧮 Formulas
  1. Indexing: s[i], Slicing: s[start:stop:step]
  2. Methods: s.lower(), s.upper(), s.strip(), s.split(sep), s.replace(old,new)
📊 Visual ideas
Diagram of a string with indexed positions 0,1,2... and negative indices -n...-1.
Illustration of slicing extracting a substring from the string.
⚖️9

Lists: creation, indexing and common operations

What a list is
A list is an ordered collection of items that can hold mixed types. Lists are mutable, meaning you can change, add or remove elements after creation. Create a list with square brackets: lst = [1, 'a', 3.5]. Lists are very common and useful for collections of student records, numbers or any sequence of items.

Accessing elements and slicing
Access list elements by index: lst[0] is the first element. Negative indices count from the end. Slicing works like strings: lst[1:4] yields a new list of those elements. Remember that slicing produces a shallow copy — the top-level list structure is new while mutable contained objects are still referenced.

Modifying lists
You can change elements by assignment: lst[2] = new_value. Use append() to add at the end, insert(index, value) to place at a specific position, and extend(iterable) to add multiple items. For removal, use pop() to remove and return an item (default last), remove(value) to delete the first occurrence of a value, and del to delete by index or a slice.

Traversal and common patterns
Iterate over lists with for item in lst:, or use for i in range(len(lst)) when indices are needed. Use enumerate(lst) to get both index and value. Accumulators collect results: total = 0; for x in lst: total += x. List comprehensions provide compact creation syntax: squares = [x*x for x in range(1,11) if x%2==0].

Searching and sorting
Use in to check membership and index() to locate the first occurrence. Use sort() to sort a list in place and sorted() to produce a new sorted list. Provide key functions for custom order (e.g., sort by length). Remember that sorting lists of mixed incomparable types raises a TypeError.

Nested lists and copying
Lists may contain lists to represent matrices. Access nested elements with multiple indices: matrix[0][1]. When copying lists, a simple assignment creates a reference; use list.copy() or list() for a shallow copy. For nested lists, deep copies are needed to avoid shared references.

📌 Examples
  • Create and append: lst = [10, 20]; lst.append(30) gives [10,20,30].
  • Enumerate: for i, v in enumerate(['a','b']): print(i, v).
  • Comprehension: evens = [x for x in range(1,21) if x%2==0].
🧮 Formulas
  1. Create: lst = [item1, item2, ...]
  2. Append: lst.append(x), Insert: lst.insert(i, x), Pop: lst.pop(), Remove: lst.remove(x)
📊 Visual ideas
A diagram of a list as boxes in order with indices 0..n-1 and negative indices -n..-1.
Representation of nested list (matrix) as rows and columns with indexes.
💻10

Tuples and sets

Tuples: ordered immutable sequences
Tuples resemble lists but are immutable: once created you cannot change their contents. Define a tuple with parentheses: t = (1, 2, 3) or simply t = 1, 2, 3. Because they are immutable and hashable if all items are hashable, tuples can be used as keys in dictionaries. For fixed collections like coordinates or records that should not change, tuples are appropriate. You can index and slice tuples like lists and use methods such as count() and index().

Tuple unpacking
Unpack tuple values into variables: x, y = (10, 20). This is very convenient for functions that return multiple values or when iterating over sequences of pairs.

Sets: unordered collections of unique items
Sets store unique elements and are unordered. Create a set with curly braces containing elements {1,2,3} or use set() to convert a sequence. Since sets do not maintain order and do not allow duplicates, they are ideal for removing duplicates and performing membership tests efficiently. Because sets are mutable, elements must be of immutable types (e.g., numbers, strings) to be added.

Set operations
Mathematical set operations are available: union (A | B), intersection (A & B), difference (A - B) and symmetric difference. Methods like add(), remove(), discard(), pop() and clear() manage elements. Use discard() when removal may fail without raising an error; remove() raises KeyError if the element is absent.

When to use which type
Choose tuples for fixed data, lists for ordered mutable sequences, and sets when uniqueness and fast membership checks are needed. For example, to find unique words in a text, convert the list of words to a set. For ordered unique collections preserving insertion order, consider using dictionaries or ordered structures in advanced topics.

Practical notes
Converting types is easy: list(set(seq)) removes duplicates but loses original order. Use sorted() to create an ordered list from a set if needed. These differences between tuples, lists and sets help match data structure to the problem requirements.

📌 Examples
  • Tuple unpacking: x, y = (10, 20) gives x=10, y=20.
  • Set creation: s = {1,2,2,3} results in {1,2,3}.
  • Intersection: {1,2,3} & {2,3,4} gives {2,3}.
🧮 Formulas
  1. Tuple: t = (a, b, c)
  2. Set operations: union: A | B, intersection: A & B, difference: A - B
📊 Visual ideas
Venn diagram showing two sets with intersection, union and difference regions.
Illustration contrasting a list (ordered boxes) and a set (unordered cloud).
🌬️11

Dictionaries (maps): key-value pairs

What a dictionary is
A dictionary stores data as key-value pairs and is implemented by braces with colon separators: d = {'name': 'Amit', 'age': 16}. Keys must be unique and of an immutable type (strings, numbers, tuples). Values can be of any type. Dictionaries are ideal when you need to look up information by a key quickly, like mapping roll numbers to student records or counting occurrences efficiently.

Accessing and modifying entries
Access values using d[key]. If a key may be missing, use d.get(key, default) to avoid a KeyError; this returns default if the key is absent. Add or update entries with d[key] = value. Remove entries with del d[key] (raises KeyError if absent) or use d.pop(key, default) which returns default when the key is not found; pop also returns the removed value when successful. Use d.clear() to remove all entries.

Iterating over dictionaries
Iterating directly over a dictionary loops over keys: for k in d:. To access values, use for v in d.values():. To iterate both, use for k, v in d.items(): which yields key-value pairs as tuples. Dictionaries in recent Python versions preserve insertion order; this can be useful when output order matters, but do not rely on this for algorithmic correctness unless explicitly required.

Common usage patterns
Dictionaries are frequently used for counting (frequency tables) and lookup tables. A common counting pattern is counts[x] = counts.get(x, 0) + 1 which initialises the count at 0 if the key is not present and increments it. For lookups, dictionaries provide average case O(1) access which is much faster than searching lists for large datasets.

Nested dictionaries and complex records
Dictionaries can contain lists or other dictionaries as values, enabling hierarchical data like student -> {'name': ..., 'marks': {'math': 80, 'sci': 75}}. Access nested values carefully and guard against missing keys using get() or conditional checks. For complex counting tasks, Python's collections module (defaultdict, Counter) simplifies common patterns, but basic dictionaries are sufficient for most ICSE tasks.

Best practices and pitfalls
Avoid modifying a dictionary while iterating over it; instead iterate over list(d.items()) or collect modifications and apply after iteration. Choose clear key names and validate keys before access when user input is involved. When printing dictionaries for reports, format entries for readability. Understanding dictionaries enables efficient solutions for many class problems and forms a foundation for more advanced data structures later.

📌 Examples
  • Create: d = {'roll': 12, 'name': 'Maya'}; print(d['name']) prints 'Maya'.
  • Count words: for w in words: counts[w] = counts.get(w, 0) + 1.
  • Iterate entries: for k, v in student.items(): print(k, v).
🧮 Formulas
  1. Create: d = {key1: value1, key2: value2}
  2. Access: value = d[key], Safe access: d.get(key, default)
  3. Add/modify: d[key] = value, Delete: del d[key]
📊 Visual ideas
Diagram showing dictionary as paired boxes: key -> value for each entry.
Nested dictionary tree showing student -> {name:..., marks: {math:..., sci:...}}
✍️12

File handling: reading and writing text files

Why file I/O matters
Files let programs preserve data between runs. Learning to read and write text files is important for tasks like saving user data, logging program activity, and processing data files. Understanding file modes and safe handling prevents data loss and resource leaks.

Opening files
Use open(filename, mode) to access a file. The most common modes are 'r' for read, 'w' for write (which creates or truncates), 'a' for append (to add data at the end) and 'r+' for read/write. When working with text, specify encoding='utf-8' to ensure correct handling of Unicode. Use with open(...) as f: to automatically close the file after the block finishes, even if exceptions occur.

Reading files
Read the whole file with f.read(), read a single line with f.readline(), or get all lines as a list with f.readlines(). Iterating with for line in f: reads line by line efficiently and is preferred for large files. Strip the trailing newline with line.rstrip('\n') or line.strip() when processing.

Writing files
Use f.write(string) to write text. Note write does not add a newline automatically. To write multiple lines, use f.writelines(list_of_strings) but ensure each string includes its newline. For tabular data choose a clear separator (comma, tab) and document the format so files can be parsed later. When overwriting is not desired, use append mode 'a'.

Error handling and safe patterns
Opening a non-existent file in 'r' mode raises FileNotFoundError. Use try-except to handle such cases gracefully or check existence with os.path.exists before opening. Always prefer the with statement to ensure closure. Avoid mixing text and binary operations on the same file unless the mode matches (e.g., 'rb').

Practical tasks and parsing
Common exercises include counting words, filtering lines, copying files and updating records. For structured data, represent each record as a CSV line (comma-separated) and parse using split(',') or use higher-level modules in later study. Test file operations with small files first and inspect results in a text editor to verify correctness.

📌 Examples
  • Read entire file: with open('data.txt','r', encoding='utf-8') as f: text = f.read()
  • Write lines: with open('out.txt','w', encoding='utf-8') as f: f.write('Line1\n')
  • Append a log entry: with open('log.txt','a') as f: f.write('New entry\n')
🧮 Formulas
  1. Open file: with open(filename, mode, encoding='utf-8') as f: ...
  2. Read: f.read(), f.readline(), f.readlines()
  3. Write: f.write(string), f.writelines(list_of_strings)
📊 Visual ideas
Flow diagram showing program opening file -> reading/writing -> closing file.
Sequence showing modes and their effect: 'r' read-only, 'w' overwrite, 'a' append.
💻13

Error handling and debugging

Types of programming errors
Errors fall into three broad categories: syntax errors (code not conforming to language rules), runtime errors or exceptions (errors that occur during execution like ZeroDivisionError, ValueError), and logical errors (program runs but results are incorrect). Recognising the type of error helps choose the right fix.

Using exceptions
Handle runtime errors using try-except. Place code that may raise exceptions inside try, and handle specific exceptions in except blocks. Use multiple except clauses to handle different exceptions differently. An else clause runs if no exception occurs; finally always runs for cleanup (closing files or releasing resources). Prefer catching specific exceptions instead of a bare except to avoid hiding programming errors.

Reading tracebacks
When an unhandled exception occurs, Python prints a traceback showing call stack frames and the line where the exception happened. Read tracebacks from bottom to top to locate the failing line and inspect variable values. Tracebacks often include helpful messages such as 'IndexError: list index out of range'.

Debugging techniques
Simple debugging uses print statements to display variable values at key points. A more powerful method is using an IDE debugger with breakpoints and step-by-step execution which allows inspecting variables and control flow interactively. Use assertions in development: assert condition, 'message' to state assumptions; these raise AssertionError if violated and help detect logic errors early.

Preventive practices
Validate inputs before processing, check boundaries (indexes, division by zero) and document function preconditions. Modular code with small functions is easier to test. Add unit tests for important functions if comfortable. Use clear variable names and comments to make reasoning about code easier, reducing logical mistakes.

Recovering from errors
When an error occurs in production, log useful information (time, input causing the error, stack trace) so the problem can be reproduced and fixed. For class projects, show how you tested edge cases and addressed exceptions; this demonstrates understanding and care in design.

📌 Examples
  • Handle invalid int input: try: n = int(input()) except ValueError: print('Enter a valid integer')
  • File handling with exception: try: with open('x.txt') as f: data = f.read() except FileNotFoundError: print('File missing')
  • Assertion example: assert len(lst)>0, 'List must not be empty' before accessing lst[0]
🧮 Formulas
  1. try: statements except ExceptionType: handler else: statements_if_no_exception finally: cleanup
📊 Visual ideas
Flowchart showing try block leading to normal path (else) or exception path (except) then finally.
Traceback reading guide showing chain of calls leading to an error line number.
💻14

Modules and standard library

Modularity and reuse
Modules let you organise related code into separate files and reuse it across programs. A module is simply a .py file defining functions, classes or variables. Importing modules avoids copying code and promotes a structured approach to programming. The Python standard library provides many useful modules so you do not need to implement common tasks from scratch.

Importing modules
Use import module to bring a module into scope and access its names as module.name. Use from module import name to import specific items directly. Use aliasing with as to give a shorter or clearer name: import math as m. Avoid polluting the global namespace by importing only what is needed.

Useful standard modules for students
math for mathematical functions (sqrt, floor, ceil), random for generating random numbers and selections, datetime for dates and times, os and sys for interacting with the operating system, json for reading/writing JSON, and statistics for basic statistical measures like mean and median. These modules are part of the standard library and available without separate installation.

Writing and importing your own modules
Put related helper functions into a file myutils.py and import it in your main program. Use the special variable __name__ to include test code that runs only when the module is executed directly: if __name__ == '__main__': test(). This keeps test or demo code separate from the reusable definitions.

Packages and pip
Collections of modules organised as folders with __init__.py files are packages. Third-party packages extend functionality and can be installed using pip; for classwork focus on the standard library first. When using external packages note installation steps and version compatibility if required.

Documentation and help
Use Python's help() in the interactive shell to learn about modules and functions, and refer to official documentation for exact behaviour. Reading documentation is a key skill for independent problem solving and using library functions correctly.

📌 Examples
  • Import math and compute math.sqrt(25) to get 5.0.
  • Use random.randint(1,6) to simulate a dice roll.
  • Create myutils.py with helper functions and import it from main.py.
🧮 Formulas
  1. Import forms: import module ; from module import name ; import module as alias
  2. __name__ check: if __name__ == '__main__': main()
📊 Visual ideas
Diagram showing program importing modules and calling their functions.
Hierarchy showing package -> module -> functions/variables.
💻15

Lists vs arrays and basic numeric computations

Lists for general use
Python lists are flexible containers for heterogeneous items and are suitable for many numeric tasks like summing values, computing averages and simple element-wise operations using loops or comprehensions. For typical school-level problems lists are sufficient and easy to use. Lists allow common operations such as indexing, slicing, appending and removing elements, so they are the first choice for most assignments.

Arrays and numeric performance
When doing heavy numerical computations on large datasets, specialised array types (from third-party libraries) provide better performance because they store data in contiguous memory and support vectorised operations. However, these are outside the standard ICSE syllabus. For classroom problems, focus on writing correct algorithms using lists and built-in functions like sum(), min() and max().

Accumulator patterns and reductions
Many numeric tasks follow the accumulator pattern: initialise a variable, loop over items, and update the accumulator. For example, total = 0; for x in nums: total += x computes the sum. Other reductions include product, min and max. Python's built-in functions (sum, min, max) often simplify code and are efficient for common tasks.

Common algorithms and examples
To compute factorial use a loop: fact = 1; for i in range(1, n+1): fact *= i. For computing averages, use sum(nums)/len(nums) but ensure len(nums) is not zero before dividing. Prime checks can be optimised by testing divisibility only up to int(n**0.5) rather than up to n, improving performance significantly for larger n encountered in problems.

Precision and numeric issues
Floating-point arithmetic has limited precision; avoid checking floats for exact equality. Instead compare absolute difference to a small tolerance: abs(a - b) < 1e-9. Be aware that integer division // and true division / behave differently: use / for real-valued averages and // when integer division is intended.

Practical suggestions
Use list comprehensions and built-in functions for concise and clear code where possible. For example, squares = [x*x for x in nums]. When performance matters, avoid repeated work inside loops (compute invariant values outside). Understanding these patterns prepares students to write correct, efficient solutions for typical numerical problems in the syllabus.

📌 Examples
  • Average: avg = sum(nums) / len(nums) where nums is a list of numbers.
  • Factorial: fact = 1; for i in range(1, n+1): fact *= i
  • Prime check: test divisibility from 2 to int(n**0.5)
🧮 Formulas
  1. Average: mean = sum(values) / len(values)
  2. Factorial: n! = 1 * 2 * ... * n (compute using loop or recursion)
  3. Prime test limit: check divisors up to floor(sqrt(n))
📊 Visual ideas
Flowchart for factorial calculation showing loop multiplying accumulator.
Diagram showing checking divisibility up to square root of n.
💻16

Recursion (introduction)

Understanding recursion
Recursion is a technique where a function calls itself to solve a smaller instance of the same problem. A correct recursive solution has at least two parts: one or more base cases that can be answered directly without recursion, and one or more recursive cases that reduce the problem size and call the same function. Thinking recursively often mirrors the mathematical definition of sequences or structures such as factorial, Fibonacci series, and tasks involving hierarchical data.

Designing a recursive solution
To design recursion, first identify the base case(s) — the simplest input(s) where no further recursion is needed. Then express a general input’s solution in terms of smaller inputs. For factorial, the base case is fact(0)=1 and the recursive case is fact(n)=n*fact(n-1). Always ensure the recursive step moves the input closer to the base case so that recursion terminates. Otherwise, the program will run until Python’s recursion limit is reached and raise a RecursionError.

Tracing recursion and call stack
Recursion unfolds as nested calls on the call stack. Visualise recursion by drawing a recursion tree or writing entry and exit print messages in the function to follow parameter values. Each call has its own local variables and execution context; when a recursive call returns, its result is used by the caller. This return path is important to understand how partial results are combined to form the final answer.

Recursive patterns and examples
Common recursive patterns include linear recursion (e.g., factorial, sum of list), tail recursion (where the recursive call is the last action in function, enabling optimisations in some languages), and divide-and-conquer (splitting the problem into two or more parts, such as recursive binary search on a sorted list). The naive recursive Fibonacci function demonstrates both the concept and inefficiency: fib(n) calls fib(n-1) and fib(n-2) and repeats calculations; memoization or iterative methods are preferred for larger inputs.

When to use recursion
Use recursion when the problem naturally breaks down into similar subproblems, such as tree traversals or combinatorial generation. For simple iterative numeric tasks loops are often clearer and more efficient. Recognise trade-offs: recursion can give concise and readable code but may use more memory due to call stack and may be slower without memoization.

Testing and debugging recursive functions
Test recursion on small inputs and check base cases carefully. Insert print statements to log entry and exit from functions during debugging. Use assertions at the start of the function to validate assumptions (for example, n >= 0 for factorial). Understanding recursion thoroughly equips students to model many algorithms and prepare for more advanced CS topics.

📌 Examples
  • Factorial: def fact(n): if n==0: return 1 else: return n * fact(n-1)
  • Recursive sum: def sum_list(lst): return 0 if not lst else lst[0] + sum_list(lst[1:])
  • Show recursion tree for fact(4) to trace calls and returns.
🧮 Formulas
  1. Recursive pattern: f(n) = base_case for n in base_cases; f(n) = combine(f(n-1), ...) otherwise
  2. Factorial: fact(0)=1; fact(n)=n*fact(n-1) for n>0
📊 Visual ideas
Recursion tree for fact(4) showing calls fact(4)->fact(3)->fact(2)->fact(1)->fact(0) and returns.
Call stack sketch showing nested calls and returns.
💻17

Basic algorithms: searching and sorting

Importance of basic algorithms
Searching and sorting are fundamental algorithms used in data processing. Understanding simple methods helps build intuition about algorithmic thinking, step-by-step execution and complexity. For ICSE-level problems, students should know linear search, binary search and simple sorting techniques like selection sort and bubble sort, and be able to write and trace these algorithms on small inputs.

Linear search
Linear search checks each element in a list until the target is found or the list ends. It works on unsorted lists and is easy to implement. Time complexity is O(n) where n is the number of items. Use linear search when the list is small or unsorted and building an index is not cost-effective.

Binary search
Binary search is efficient (O(log n)) but requires a sorted list. Start with low and high indices and compare the middle element with the target. If equal, return the index; if target is smaller, search the left half by setting high = mid - 1; otherwise search the right half by setting low = mid + 1. Repeat until low > high. Implement carefully to avoid off-by-one errors in mid calculation and termination conditions.

Simple sorting methods
Selection sort repeatedly finds the minimum element from the unsorted portion and swaps it into position; bubble sort repeatedly swaps adjacent out-of-order elements; insertion sort builds a sorted prefix by inserting each element into its correct position. All three are O(n^2) in time complexity and suitable for educational purposes on small arrays. Python’s built-in sorted() and list.sort() use efficient algorithms and should be used in practice for larger data sets.

Tracing and complexity
Dry-run algorithms on small examples to observe comparisons and swaps. Explain why binary search halves the search space each step. Discuss time complexity qualitatively: how operation counts grow with input size. This reasoning prepares students for designing better solutions when needed.

📌 Examples
  • Linear search code: for i in range(len(lst)): if lst[i]==key: return i
  • Binary search on [2,4,6,8,10] to find 6: check middle index 2 and return immediately.
  • Selection sort: repeatedly place the smallest remaining element at the next position.
🧮 Formulas
  1. Binary search loop: while low <= high: mid = (low+high)//2; compare and adjust low/high
  2. Selection sort: for i in range(n): find min in lst[i:] and swap with lst[i]
📊 Visual ideas
Diagram showing binary search halving the array and narrowing down to target.
Visualization of selection sort swapping the smallest remaining element into position.
💻18

Project: a small Python program combining learned topics

Purpose of the project
The project brings together the concepts learnt in this unit: variables, input/output, control flow, functions, collections and file I/O. It teaches how to design, implement and test a small application. Projects train students to decompose a problem, choose data structures, handle user interaction and persist data between runs.

Project planning
Start by specifying clear requirements: what features the program must support, expected inputs and outputs, and file format for storage. Sketch the user interface as a simple text menu. Decide data structures: a list of dictionaries is a common choice for records (each record is a dictionary with keys like 'roll', 'name', 'marks'). Plan functions for each operation: add_record, display_records, search_record, save_to_file and load_from_file. Writing the plan first avoids confusion later.

Implementation advice
Implement and test functions one at a time. Use with open(...) to handle files and catch FileNotFoundError when loading. Validate user input and convert types safely using try-except. Keep the menu loop simple: while True: show menu; read choice; call the appropriate function; break on exit. Use return values to indicate success or errors from helper functions instead of modifying globals when possible.

Example: Student marks manager
Features: add student record (roll, name, marks), compute average and grade, display all records, search by roll, save/load CSV file. Data layout in file: one student per line as roll,name,mark1,mark2,... . When loading, parse each line with split(',') and convert marks to integers. On saving, join fields using ','.

Testing and documentation
Test the project with several cases including empty list, duplicate roll numbers and malformed file lines. Add comments and a small README describing how to run the program and file format. Document assumptions such as maximum number of marks or input validation rules. This practice demonstrates design thinking and prepares students for larger assignments.

📌 Examples
  • Design functions add_student, show_all, save_data and load_data; test by adding two students and saving to file.
  • Menu loop example: while True: print(menu); choice = input(); if choice=='1': add_student(); elif choice=='4': break
  • File format: roll,name,marks separated by commas, one student per line for easy parsing.
🧮 Formulas
  1. Average: avg = sum(marks) / len(marks)
  2. Grade logic example: if avg>=90: 'A' elif avg>=75: 'B' else: 'C'
📊 Visual ideas
Flowchart of menu-driven program showing user choice branching to different functions and back to menu.
Data flow diagram showing data read from file into memory structures and written back on save.

Key Concepts

Interpreter
A program that reads and executes Python code line by line without separate compilation.
Variable
A name that refers to a value stored in memory.
Data type
A classification that determines the kind of values a variable can hold and the operations allowed.
Immutable
An object whose value cannot be changed after creation (e.g., tuple, string).
Mutable
An object whose contents can be changed after creation (e.g., list, dictionary).
Function
A named block of code that performs a task and can be called with arguments and may return a value.
Loop
A control structure that repeats a block of code while a condition is true or over items of a sequence.
Recursion
A technique where a function calls itself to solve smaller instances of the same problem.
Module
A file containing Python definitions and statements that can be imported into other programs to reuse definitions.
Exception
An error that occurs during program execution which can be handled using try-except blocks.
List comprehension
A compact syntax to create lists from iterables using an expression and optional condition.
Dictionary
A collection of key-value pairs used to map unique keys to values.
File I/O
Operations to read from and write to files on persistent storage.
Standard library
A collection of modules included with Python that provide common functionality.
Indentation
Leading spaces used in Python to define code blocks and control structure scope.

Practice Questions

  1. Write a Python statement to display the text Hello, ICSE! / एक Python कथन लिखिए जो Hello, ICSE! प्रदर्शित करे
    Show answer

    Use the print function to display text: print('Hello, ICSE!') which will print the required message to the screen. / स्क्रीन पर संदेश दिखाने के लिए print फ़ंक्शन का उपयोग करें: print('Hello, ICSE!') जो आवश्यक संदेश प्रदर्शित करेगा।

  2. How do you convert the string '123' to an integer in Python? / आप Python में '123' स्ट्रिंग को integer में कैसे बदलेंगे?
    Show answer

    Convert with the int() function: n = int('123') which returns the integer 123. Ensure the string contains only digits to avoid ValueError. / int() फ़ंक्शन से बदलें: n = int('123') जो पूर्णांक 123 देगा। सुनिश्चित करें कि स्ट्रिंग में केवल अंक हों वरना ValueError आएगा।

  3. Write a program fragment to read two integers and print their product. / दो पूर्णांक पढ़कर उनका गुणनफल प्रदर्शित करने का प्रोग्राम अंश लिखिए।
    Show answer

    Read two integers from one line and print their product: a, b = map(int, input().split()) print(a * b) This reads two space-separated integers and prints their multiplication result. / एक लाइन से दो पूर्णांक पढ़कर उनका गुणनफल प्रिंट करें: a, b = map(int, input().split()) print(a * b) यह दो स्पेस-सेपरटेड पूर्णांक पढ़ता है और उनका गुणनफल प्रदर्शित करता है।

  4. Explain the difference between list and tuple with one example each. / एक उदाहरण के साथ list और tuple में अंतर स्पष्ट कीजिए।
    Show answer

    A list is mutable (its contents can be changed) and is created with square brackets: lst = [1, 2, 3]; lst[0] = 10 changes the first element. A tuple is immutable (cannot be changed) and uses parentheses: t = (1, 2, 3); attempting t[0] = 10 raises a TypeError. Lists are used when data may change; tuples when data should remain fixed. / List परिवर्तनशील होती है और कोष्ठक [ ] से बनाई जाती है: lst = [1,2,3]; lst[0] = 10 करने पर पहला तत्व बदल जाता है। Tuple अपरिवर्तनीय होती है और ( ) से बनाई जाती है: t = (1,2,3); t[0]=10 करने पर TypeError होगा। List का उपयोग तब करें जब डेटा बदल सकता है; Tuple का उपयोग तब करें जब डेटा स्थिर रहे।

  5. Write a function factorial(n) using a loop and show factorial(5). / एक लूप का उपयोग कर factorial(n) नामक फंक्शन लिखिए और factorial(5) दिखाइए।
    Show answer

    Define and call the function: def factorial(n): result = 1 for i in range(1, n+1): result *= i return result print(factorial(5)) # outputs 120 This computes 5! = 120 by multiplying 1*2*3*4*5. / फ़ंक्शन परिभाषित और कॉल करें: def factorial(n): result = 1 for i in range(1, n+1): result *= i return result print(factorial(5)) # आउटपुट 120 यह 5! = 120 को 1*2*3*4*5 गुना करके देता है।

  6. Describe how to open a file for appending and write the line 'Done' to it. / किसी फ़ाइल को append मोड में कैसे खोलकर उसमें 'Done' लिखते हैं, समझाइए।
    Show answer

    Use the with statement to open the file in append mode so it is closed automatically: with open('file.txt', 'a', encoding='utf-8') as f: f.write('Done\n') This opens file.txt for appending, writes 'Done' followed by a newline and closes the file. / फ़ाइल को स्वतः बंद करने के लिए with स्टेटमेंट के साथ append मोड में खोलें: with open('file.txt', 'a', encoding='utf-8') as f: f.write('Done\n') यह file.txt को append के लिए खोलेगा, 'Done' और नई पंक्ति लिखेगा और फ़ाइल बंद कर देगा।

  7. What will be the output and why: print(3/2, 3//2, 3%2) ? / इसका आउटपुट क्या होगा और क्यों: print(3/2, 3//2, 3%2) ?
    Show answer

    The output is: 1.5 1 1 Explanation: 3/2 performs true division and returns float 1.5; 3//2 performs floor (integer) division and returns 1; 3%2 returns the remainder 1. / आउटपुट होगा: 1.5 1 1 विवरण: 3/2 वास्तविक भागफल देता है (1.5); 3//2 floor या integer division देता है (1); 3%2 शेषफल देता है (1)।

  8. Write a program to read a list of integers and print the largest value. / पूर्णांकों की एक सूची पढ़कर सबसे बड़ा मान प्रदर्शित करने का प्रोग्राम लिखिए।
    Show answer

    Simple solution using built-in max: nums = list(map(int, input().split())) print(max(nums)) This reads space-separated integers and prints the largest. For an empty input handle with a check before calling max. / बिल्ट-इन max का उपयोग: nums = list(map(int, input().split())) print(max(nums)) यह स्पेस-सेपरेटेड पूर्णांकों को पढ़कर सबसे बड़ा मान प्रिंट करेगा। खाली सूची के लिए पहले जाँच करें।

  9. Explain try-except with an example that handles division by zero. / Division by zero को handle करने वाला try-except उदाहरण देकर समझाइए।
    Show answer

    Use try-except to catch ZeroDivisionError when dividing by user input: try: x = int(input('Dividend: ')) y = int(input('Divisor: ')) print(x // y) except ZeroDivisionError: print('Cannot divide by zero') except ValueError: print('Please enter valid integers') This handles the case when y is zero by catching ZeroDivisionError and also handles invalid integer input. / उपयोगकर्ता इनपुट से विभाजन करते समय ZeroDivisionError को पकड़ने के लिए try-except का उपयोग करें: try: x = int(input('Dividend: ')) y = int(input('Divisor: ')) print(x // y) except ZeroDivisionError: print('Cannot divide by zero') except ValueError: print('Please enter valid integers') यह y = 0 होने पर ZeroDivisionError को पकड़ता है और अमान्य पूर्णांक इनपुट को भी हैन्डल करता है।

  10. Write code to count occurrences of each word in a given string using a dictionary. / किसी दिए गए स्ट्रिंग में प्रत्येक शब्द की आवृत्ति गिनने के लिए dictionary का उपयोग करते हुए कोड लिखिए।
    Show answer

    Use split() and a dictionary to count words: s = input() words = s.split() counts = {} for w in words: counts[w] = counts.get(w, 0) + 1 print(counts) This prints a dictionary mapping each word to its frequency. For case-insensitive counting, convert words to lower() before counting. / split() और dictionary का उपयोग करके शब्दों की गिनती: s = input() words = s.split() counts = {} for w in words: counts[w] = counts.get(w, 0) + 1 print(counts) यह प्रत्येक शब्द को उसकी आवृत्ति के साथ दिखाने वाला dictionary प्रिंट करेगा। केस-इनसेंसिटिव के लिए w.lower() का उपयोग करें।

  11. How does a for loop differ from a while loop? Give one example of when to use each. / for लूप और while लूप में क्या अंतर है? प्रत्येक के एक उपयोग उदाहरण दीजिए।
    Show answer

    A for loop iterates over items of a known sequence or a fixed range and is ideal when the number of iterations is known in advance. Example: for i in range(5): print(i) prints numbers 0 to 4. A while loop repeats as long as a condition remains True and is ideal when the number of iterations depends on runtime conditions. Example: while user_input != 'exit': user_input = input() continues until the user types 'exit'. / for लूप किसी sequence या निश्चित range पर चलता है और तब उपयोगी है जब इटरेशन की संख्या ज्ञात हो। उदाहरण: for i in range(5): print(i) 0 से 4 तक प्रिंट करेगा। while लूप तब उपयोगी है जब इटरेशन किसी रनटाइम शर्त पर निर्भर करे। उदाहरण: while user_input != 'exit': user_input = input() तब तक चलता है जब तक user 'exit' नहीं टाइप करता।

Related Laws & Principles

Explore all

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

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