Skip to content
EX-406 · Python/Quick Revision Short Notes

Python (EX-406) - Unit 1 Short Notes

UNIT 1: Python Fundamentals - Short Notes

1. Introduction & Environment Setup

  • What is Python? A high-level, interpreted, general-purpose programming language. Core philosophies emphasize code readability and simplicity (via significant whitespace).

  • Environment Setup:

    • Download installer from python.org.

    • Interpreter/REPL (Read-Eval-Print Loop): Interactive command-line shell for immediate code execution.

    • IDEs/Editors: IDLE (bundled), VS Code, PyCharm, Jupyter Notebooks (for data science).

  • Running Code:

    • Interactive Mode: Type commands directly into REPL.

    • Script Mode: Write code in a .py file and execute via terminal: python script.py.

[!TIP] Exam Focus: Know the difference between interpreted (Python) vs. compiled (C++) languages. Understand what REPL stands for.


2. Basic Syntax & First Programs

  • print() Function: Outputs to console.

    • Prefer f-strings (Python 3.6+) for formatting: print(f"Value: {x}").

    • Avoid comma-separated printing for complex formatting (adds spaces automatically).

  • Comments:

    • Single-line: # comment

    • Multi-line (docstring): """ multi-line comment """ (also used for function/class documentation).

  • Variables & Assignment:

    • Dynamic Typing: Type is inferred at runtime; no int x; declaration.

    • Naming (PEP 8): snake_case for variables/functions, CamelCase for classes.

    • Assignment: x = 10, x += 5 (compound assignment).

  • input() Function: Reads console input as a string. Always convert for numeric use:

    
    age = int(input("Enter age: "))  # Converts string to integer
    
    

[!CAUTION] Common Pitfall: Forgetting to convert input() result causes TypeError in arithmetic operations.


3. Python Data Types & Objects

Python is object-oriented; everything is an object with a type.

Category Type Key Characteristics Common Methods/Operations
Numeric int Integers (unbounded precision) +, -, *, /, //, %, **
float Floating-point (double precision) Same as int; is_integer()
Boolean bool True or False (subclass of int: True==1) and, or, not
Sequence str Immutable sequence of Unicode chars. upper(), lower(), strip(), split(sep), join(iterable), format()
list Mutable, ordered collection. append(), insert(i,x), remove(x), pop([i]), sort(), reverse()
tuple Immutable, ordered collection. Similar to list but no mutation methods. Use for fixed data.
Mapping dict Mutable key-value pairs. Keys must be immutable (str, int, tuple). keys(), values(), items(), get(key, default), update()
Set set Mutable, unordered, unique elements. add(), remove(), union(), intersection(), difference()
  • Type Checking & Conversion:

    • Check type: type(obj), isinstance(obj, class)

    • Convert: int("5"), str(10), list((1,2)), tuple([1,2])

[!TIP] Exam Focus: Mutability is a key differentiator (list/dict/set mutable vs str/tuple immutable). Know dictionary key constraints.


4. Operators & Expressions

  • Arithmetic: +, -, *, / (float div), // (floor div), % (modulo), ** (power).

  • Comparison: ==, !=, >, <, >=, <= (return bool).

  • Logical: and, or, not (short-circuit evaluation).

  • Assignment: =, +=, -=, *=, /=, //=, %=, **=.

  • Membership: in, not in (checks if value exists in sequence).

  • Identity: is, is not (checks if two references point to same object in memory, not equal value).

    
    a = [1,2]; b = [1,2]; a == b  # True (same values)
    
    a is b  # False (different objects in memory)
    
    
  • Operator Precedence: (Highest to Lowest)

    
    1. ** (exponentiation)
    
    2. +x, -x, ~x (unary)
    
    3. *, /, //, %
    
    4. +, -
    
    5. <<, >> (bit shifts)
    
    6. & (bitwise AND)
    
    7. ^ (bitwise XOR)
    
    8. | (bitwise OR)
    
    9. Comparisons, membership, identity (==, !=, >, <, in, is, etc.)
    
    10. not
    
    11. and
    
    12. or
    
    

    Use parentheses () to override and improve readability.

[!CAUTION] Common Pitfall: Confusing == (equality) with is (identity). Use is only for None, True, False checks or singleton objects.


5. Control Flow

  • Conditional Statements (if/elif/else):

    
    if condition1:
    
        # code block
    
    elif condition2:
    
        # code block
    
    else:
    
        # code block
    
    
    • Indentation defines blocks (typically 4 spaces).

    • pass is a null operation placeholder.

  • Loops:

    • for Loop: Iterates over sequences (strings, lists, tuples, dicts, range()).

      
      for item in sequence:
      
          print(item)
      
      for i in range(5):      # 0 to 4
      
      for i in range(1,6):    # 1 to 5
      
      for i in range(0,10,2): # 0,2,4,6,8
      
      
    • while Loop: Repeats as long as condition is True. Must ensure termination to avoid infinite loops.

      
      while condition:
      
          # code
      
      
    • Loop Control:

      • break: Exit the nearest enclosing loop immediately.

      • continue: Skip rest of current iteration, move to next.

      • else clause on loops: Executes only if loop terminated normally (no break).

      
      for i in range(5):
      
          if i == 3:
      
              break
      
      else:
      
          print("Completed")  # NOT printed if break hit
      
      

[!TIP] Exam Focus: Loop else clause behavior is frequently tested. Know when it executes.


6. Functions

  • Definition & Call:

    
    def function_name(param1, param2=default):
    
        """Docstring explaining function."""
    
        # code
    
        return result  # Optional; returns None if omitted
    
    
  • Parameters & Arguments:

    • Positional: Arguments matched by position.

    • Keyword: func(param=value); order doesn't matter after first keyword arg.

    • Default Values: Defined in function header; allow omitting argument.

  • Return Statement:

    • Returns a single object.

    • To return multiple values, return a tuple: return x, y, z (actually return (x,y,z)).

  • Variable Scope:

    • Local: Defined inside function; not accessible outside.

    • Global: Defined at module top-level; accessible everywhere (but read-only inside function unless declared global).

    • global keyword: global x inside function allows modification of global x. Use sparingly; prefer returning values.

  • Docstrings: Triple-quoted string right after def; accessible via function_name.__doc__.

[!CAUTION] Common Pitfall: Mutable default arguments (e.g., def f(x=[])) are created once at definition, leading to shared state across calls. Use None and initialize inside.


7. Modules & Namespaces

  • Module: A .py file containing Python definitions (functions, classes, variables). Allows code organization and reuse.

  • Importing:

    
    import module_name                # Use: module_name.func()
    
    from module_name import func_name # Use: func()
    
    from module_name import *         # Avoid! Imports all names, pollutes namespace.
    
    
  • Namespace: A mapping from names to objects (like a dictionary). Each module has its own global namespace.

    • Prevents naming collisions.

    • Access module's namespace via dir(module).

  • Standard Library: Rich set of built-in modules (e.g., math, random, datetime, os). Import and use directly.


8. Basic Error Handling (Introduction)

  • Syntax Errors: Detected by parser during compilation (e.g., missing colon). Code won't run.

  • Exceptions (Runtime Errors): Detected during execution (e.g., ZeroDivisionError, ValueError, TypeError, IndexError, KeyError, FileNotFoundError).

  • try...except Block:

    
    try:
    
        # Code that might raise exception
    
        result = 10 / 0
    
    except ZeroDivisionError as e:
    
        # Handle specific exception
    
        print("Cannot divide by zero:", e)
    
    except (TypeError, ValueError):
    
        # Handle multiple exceptions
    
        print("Type or value error")
    
    except Exception as e:
    
        # Catch-all (use cautiously)
    
        print("Unexpected error:", e)
    
    
  • else Clause: Executes if try block completes without raising an exception.

  • finally Clause: Always executes (whether exception occurred or not), typically for cleanup (e.g., closing files).

[!TIP] Exam Focus: Order of except clauses matters—specific exceptions first, general (Exception) last. finally runs even if return in try/except.


\boxed{\text{Core Exam Topics: Data Types (Mutability), Control Flow (Loop else), Functions (Scope, Returns), Operators (Precedence, Identity vs Equality)}}

Go to where you left off?

Quick Add to Notes

Save questions, your own notes and screenshots into notes filed by unit. It takes a free account.

Create free account

Have an account? Log in