Grade 12 Exam  >  Grade 12 Notes  >  Computer Science  >  Chapter Notes: Python Revision

Chapter Notes: Python Revision

Python Basics

Revision Notes

  • Creator and name: Python was developed by Guido van Rossum in the late 1980s at the Centrum Wiskunde & Informatica (CWI) in the Netherlands. The name Python was inspired by the BBC comedy series Monty Python's Flying Circus.
  • Interactive Mode: In interactive mode the Python interpreter reads and executes commands one at a time; it is useful for testing small code fragments and learning.
  • Script Mode: In script mode a program is written in a text file (commonly with extension .py) and the interpreter executes the whole file.
  • Indentation: Blocks of code are denoted by indentation. Proper indentation is required and determines block structure.
  • Comments: A hash sign (#) begins a single-line comment. Triple-quoted strings ('''...''' or """...""") are commonly used for multi-line comments or documentation strings (docstrings).
  • Variables: A variable is created when a value is assigned to it. There is no separate declaration statement; the variable's value can change during program execution.
  • Dynamic typing: In Python the object referenced by a variable has a type; the variable itself is not bound to a single type and may refer to objects of different types at different times.
  • Static typing (contrast): In statically typed languages a type is associated with a variable at declaration and cannot be changed; this contrasts with Python's dynamic typing.
  • Multiple assignment:Python supports assigning the same value to several variables or unpacking multiple values in one statement.

    a = b = c = 1 a, b, c = 1, 2, "john"

  • Token: The smallest meaningful unit in the source code (such as keyword, identifier, literal, operator) is called a token.
  • Identifiers: An identifier names variables, functions, classes, modules, etc. It must start with a letter (A-Z or a-z) or an underscore (_) and may contain letters, digits and underscores. Python is case-sensitive (Value and value are different).
  • Identifier naming conventions:Use these conventions for clarity:
    • Class names: start with an uppercase letter (e.g., MyClass).
    • Other identifiers: start with a lowercase letter (e.g., my_variable).
    • A single leading underscore (_name) indicates the identifier is intended for internal use (conventionally private).
    • Two leading underscores (__name) invoke name mangling for strongly private identifiers.
    • Identifiers that both start and end with two underscores (e.g., __init__) are special language-defined names.
  • Reserved words (keywords): Keywords are language-reserved names that cannot be used as identifiers.
Revision Notes
  • Literals / Values: Literals (constants) are fixed values appearing directly in the code. Python supports numeric literals, string literals, boolean literals, the special literal None, and collection literals (list, tuple, set, dict).
  • Data types: A data type defines a set of values and the operations permitted on them. Python provides several built-in data types that are simple to use and powerful.
Revision Notes
  • Numbers: Numeric types include integers and floating-point numbers (and complex numbers in full Python).
  • Sequence types: An ordered collection of items indexed from 0. Main sequence types are strings, tuples and lists.
  • Strings: Sequences of characters declared with single or double quotes. Example: "hello" or 'hello'.
  • Lists: Ordered, mutable collections written with square brackets. Example: [1, "a", 3.5].
  • Tuples: Ordered, immutable collections written with parentheses or comma-separated values. Example: (1, 2, 3) or 1, 2, 3.
  • Sets: Unordered collections that do not allow duplicate elements. Example: {1, 2, 3}.
  • Dictionaries: Unordered collections of key:value pairs where keys are unique and typically immutable. Example: { "name": "Asha", "age": 17 }.
  • Operators: Special symbols that perform computations. Expressions are formed from operators, operands, literals and variables.
Revision Notes

Conditional Statements

Revision Notes

  • A conditional statement executes code selectively depending on the result of a condition (a boolean expression).
  • Plain if executes a block when a condition is true.
Revision Notes
Revision Notes
  • if-else executes one block when a condition is true and another when it is false.
Revision Notes
Revision Notes
  • if-elif-else chains allow checking multiple conditions in sequence; the first true branch runs and the rest are skipped.
  • Nested if: An if (or elif or else) block may itself contain further if statements; these are nested conditionals.
  • Storing conditions: Complex or repeated boolean expressions can be assigned to descriptive variable names and used in conditionals to improve readability.

Iteration Constructs

Revision Notes

  • Iteration (repetition) statements allow instructions to be executed repeatedly.
  • Python provides common loop forms:
    • Counting loops: repeat a fixed number of times (typically for loops).
    • Conditional loops: repeat while a condition holds (the while loop).
    • Nested loops: loops inside other loops.
  • Common loop constructs: for loop, while loop, loop control statements (break, continue), and nested loops.
Revision Notes

Python While Loop

A while loop executes its body as long as the condition is true. The condition is evaluated before each iteration.

a = 3 while (a > 0): print(a) a -= 1 # Output: # 3 # 2 # 1

  • Infinite loop: If the loop condition never becomes false (for example due to a missing counter update), the loop runs forever. To stop execution in an interactive session press Ctrl+C. Infinite loops can be intentionally useful in some programmes (for example, servers waiting for input).
  • else clause on while: A while loop may include an else block. The else block executes when the loop terminates normally (condition becomes false). It does not execute if the loop is exited by breakor an exception is raised.

    a = 3 while (a > 0): print(a) a -= 1 else: print("Reached 0") # Output: # 3 # 2 # 1 # Reached 0

  • If a break occurs inside the loop the elseclause is skipped.

    a = 3 while (a > 0): print(a) a -= 1 if a == 1: break else: print("Reached 0") # Output: # 3 # 2

  • Single-statement while:If the loop body has only one statement it may be written on the same line (use semicolons to separate statements when needed).

    a = 3 while a > 0: print(a); a -= 1 # Output: # 3 # 2 # 1

Python For Loop

The for loop iterates over items of a sequence (like elements of a list, characters of a string, or values produced by range()). The syntax differs from C/Java style indexed loops; Python uses the in keyword.

for a in range(3): print(a) # Output: # 0 # 1 # 2

To print 1 to 3 you can adjust the expression inside the loop:

for a in range(3): print(a + 1) # Output: # 1 # 2 # 3

  • The range() function:Produces a sequence of integers.

    list(range(10)) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] list(range(2, 7)) # [2, 3, 4, 5, 6] list(range(2, 12, 2)) # [2, 4, 6, 8, 10] list(range(12, 2, -2)) # [12, 10, 8, 6, 4]

  • Jump statements: break and continuecontrol loop flow.
    • break: Terminates the current loop and transfers control to the statement following the loop.
    • continue: Skips the remainder of the loop body for the current iteration and proceeds with the next iteration.
  • Nested loops: A loop may contain another loop. The inner loop must complete all its iterations for each iteration of the outer loop.

Example: nested loops to print a pattern

for i in range(1, 6): for j in range(1, i): print("*", end=" ") print() # Output: # # * # * * # * * * # * * * *

Python For Loop
Python For Loop

Idea of Debugging

Revision Notes

  • Bug / Error: Anything in the code that prevents a program from running correctly is commonly called a bug or error.
  • Errors are commonly classified as:
    • Syntax errors: Violations of the language rules; these are detected when the interpreter parses the code.
    • Semantic errors: Statements that are syntactically correct but meaningless or invalid in the program context (e.g., using an undefined variable in a way that passes parsing but fails logically).
    • Runtime errors: Errors that occur during program execution (for example division by zero, file not found).
    • Logical errors: The program runs but produces incorrect results because of faulty algorithm or programmer misunderstanding.
  • Debugging: The process of finding and fixing logical and runtime errors.
  • Common debugging approaches:
    • TDD (Test Driven Development): Write tests first and then code to satisfy those tests.
    • Print statements: Insert temporary prints to inspect variable values and program flow.
    • Using a debugger: Use tools such as the Python debugger (pdb) or IDE debuggers to step through code, set breakpoints and examine state.

Lists, Tuples and Dictionary

Revision Notes

  • List: An ordered, mutable collection that can hold items of different types. Lists use square brackets. Example: [1, 2, "apple"].
  • Important list operations and functions:
    • Indexing and slicing: Access elements by index and ranges with [start:stop] (stop excluded).
    • len(L): Returns the number of items in list L.
    • Membership: Operators in and not in test presence.
    • Concatenation: Use + to join lists.
    • Common methods: append(), insert(), extend(), sort(), remove(), reverse(), pop().
  • Tuples: Ordered, immutable sequences. Use parentheses or commas. Example: (1, "a", 3.5).
  • Tuple operations:
    • Indexing and slicing are supported.
    • len(), max(), min() are useful; tuples are immutable so there is no append or remove.
  • Dictionaries: Mutable, unordered collections of unique keys mapped to values. Example: { "roll": 21, "name": "Ravi" }.
  • Dictionary operations and methods:
    • len(), clear(), items(), keys(), values(), update().
    • Membership operators in and not in test for keys, not values.

Sorting Algorithm

Revision Notes

  • Sorting: Arranging elements in a specified order, typically ascending or descending.
  • Two simple sorting techniques:
    • Bubble Sort: Repeatedly compares adjacent items and swaps them if they are in the wrong order. After each pass the largest (or smallest) element moves to its final position.
    • Insertion Sort: Builds a sorted subarray one element at a time by inserting each new item into its correct position among the previously sorted elements.

Strings in Python

Revision Notes

  • Storage and indexing: Strings are sequences of characters stored contiguously and indexed from 0. They support forward and reverse indexing.
  • Immutability: Strings are immutable; you cannot change characters in place.
  • Common string operations:
    • Concatenation: + to join strings.
    • Replication: * to repeat strings.
    • Membership: in and not in to test substrings.
    • Comparison: Operators ==, !=, <, >, <=, >= compare lexicographically.
  • Built-in functions:
    • ord(ch) - returns the Unicode (ASCII for ASCII-range) code point of character ch.
    • chr(n) - returns the character corresponding to integer code point n.
  • Slicing: A slice selects a substring using string[n:m], which returns characters from index n up to but not including m. Omitting n or m uses the start or end of the string respectively.
The document Chapter Notes: Python Revision is a part of the Grade 12 Course Computer Science for Grade 12.
All you need of Grade 12 at this link: Grade 12

FAQs on Chapter Notes: Python Revision

1. How do I remember all the Python data types and when to use each one for CBSE exams?
Ans. Python's main data types are integers, floats, strings, lists, tuples, dictionaries, and sets. Use integers for whole numbers, floats for decimals, strings for text, lists for ordered changeable collections, tuples for immutable sequences, dictionaries for key-value pairs, and sets for unique values. Choose based on whether you need mutability, ordering, or key-based access-this directly affects your code efficiency in exam problems.
2. What's the difference between mutable and immutable objects in Python, and why does it matter?
Ans. Mutable objects (lists, dictionaries, sets) can be modified after creation; immutable objects (strings, tuples, numbers) cannot. This distinction matters because modifying a mutable object affects all references to it, while immutable objects create new objects when changed. Understanding this prevents unexpected bugs in Grade 12 coding assignments and helps optimise memory usage in solutions.
3. How do I fix common syntax errors when writing Python functions and loops?
Ans. Common mistakes include missing colons after function definitions or loop statements, incorrect indentation (Python requires consistent spacing), and forgetting to define variables before using them. Always check that colons follow control structures, indent code blocks uniformly, and declare variables first. Refer to mind maps or flashcards to visualise Python syntax rules quickly during revision sessions.
4. What's the easiest way to understand list comprehensions and dictionary comprehensions for my Python revision?
Ans. List comprehensions create lists using syntax like `[x*2 for x in range(5)]`, condensing loops into one line. Dictionary comprehensions work similarly: `{x: x**2 for x in range(5)}`. Both replace traditional loops, making code concise and faster. Practice converting standard loops into comprehensions-this technique frequently appears in Grade 12 assessments and improves code readability substantially.
5. How should I approach object-oriented programming concepts like classes and inheritance when revising Python?
Ans. Start with class basics: classes are blueprints for objects with attributes (variables) and methods (functions). Inheritance allows new classes to inherit properties from existing ones using `class Child(Parent)`. Focus on real-world examples-a Dog class inheriting from Animal-to solidify understanding. Practise creating objects, calling methods, and overriding parent methods; these concepts form the foundation of advanced Python programming tested in Grade 12.
Explore Courses for Grade 12 exam
Get EduRev Notes directly in your Google search
Related Searches
Free, mock tests for examination, shortcuts and tricks, Chapter Notes: Python Revision, ppt, past year papers, Important questions, Extra Questions, MCQs, Objective type Questions, pdf , Exam, practice quizzes, Chapter Notes: Python Revision, Chapter Notes: Python Revision, Semester Notes, Viva Questions, Previous Year Questions with Solutions, video lectures, Summary, study material, Sample Paper;