Skip to content
ME-506 · Python/Quick Revision Short Notes

Python (ME-506) - Unit 1 Short Notes

1. Introduction to Python & Setup

What is Python?

  • High-level, interpreted, general-purpose programming language.

  • Key Features: Readable syntax (uses indentation), dynamic typing, extensive standard library, cross-platform.

  • Philosophy: "The Zen of Python" (import this) emphasizes simplicity, readability, and explicitness.

  • Applications: Web development (Django, Flask), Data Science (Pandas, NumPy), Automation, Scripting, Engineering simulations.

Setting up the Environment

  • Installation: Download from python.org. Choose latest stable Python 3.x (avoid 2.x).

  • IDEs/Editors:

    • IDLE: Bundled with Python (simple).

    • VS Code / PyCharm: Feature-rich (recommended for serious development).

    • Jupyter Notebook: Browser-based, ideal for data exploration.

  • Running Python:

    1. Interactive Shell (REPL): python or python3 in terminal. Good for quick tests.

    2. Script Mode: Save code in .py file, run python script.py.

    3. IDE: Use built-in run/debug buttons.

[!TIP] Exam Focus: Know the difference between Python 2 and 3 (e.g., print is a function in 3.x). Be familiar with at least one IDE's basic workflow.


2. Basic Syntax & First Steps

The print() Function

  • Outputs objects to the standard output (console).

  • Formatted Output (Modern - Recommended):

    
    name = "Alice"
    
    age = 25
    
    print(f"Name: {name}, Age: {age}")  # f-string (Python 3.6+)
    
    
  • Legacy Methods: .format() and % operator (know they exist, prefer f-strings).

Comments & Documentation

  • Single-line: # This is a comment

  • Multi-line: ''' This is a multi-line string/comment ''' or """ ... """.

  • Best Practice: Use comments to explain why, not what (code should be self-explanatory).

Variables & Assignment

  • Dynamic Typing: Type is inferred from value. x = 10 (int), x = "hello" (str) is allowed.

  • Naming Rules (PEP 8):

    • Use lowercase with underscores (snake_case).

    • Start with letter/underscore, not a number.

    • Avoid Python keywords (if, for, class, etc.).

  • Assignment: = operator. Multiple assignment: x, y = 10, 20.


3. Python Data Types & Objects

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

Type Example Mutability Description
int 42, -5 Immutable Integer numbers.
float 3.14, -0.001 Immutable Floating-point (decimal) numbers.
complex 2+3j Immutable Complex numbers.
bool True, False Immutable Boolean values.
str "Hello", 'World' Immutable Sequence of Unicode characters.
list [1, 2, 3] Mutable Ordered, changeable sequence.
tuple (1, 2, 3) Immutable Ordered, unchangeable sequence.
set {1, 2, 3} Mutable Unordered, unique elements.
dict {'a': 1, 'b': 2} Mutable Key-Value pairs (keys immutable).
None None Immutable Represents absence of value.

Strings (str) - Key Operations

  • Concatenation: "Hello" + " " + "World" → "Hello World"

  • Repetition: "Hi!" * 3 → "Hi!Hi!Hi!"

  • Indexing: s[0] (first char), s[-1] (last char).

  • Slicing: s[start:stop:step] → s[1:5] (from index 1 to 4).

  • Common Methods:

    • .lower(), .upper()

    • .strip() (remove whitespace)

    • .split(sep) → list

    • .join(iterable) → string

    • .find(sub) / .index(sub)

    • .replace(old, new)

  • Escape Sequences: \n (newline), \t (tab), \\ (backslash).

Type Conversion

  • Explicit: int("10"), float(5), str(100), bool(0) → False.

  • Implicit (Coercion): 5 + 2.0 → 7.0 (int promoted to float).


4. Operators & Expressions

Category Operators Example
Arithmetic +, -, *, /, //, %, ** 5 // 2 → 2
Comparison ==, !=, >, <, >=, <= 3 == 3.0 → True
Logical and, or, not True and False → False
Assignment =, +=, -=, *=, /=, //=, %= x += 1
Membership in, not in 'a' in 'cat' → True
Identity is, is not (checks if same object) x is y

Operator Precedence (Highest to Lowest):

  1. () (parentheses)

  2. ** (exponentiation)

  3. +x, -x, ~x (unary)

  4. *, /, //, %

  5. +, -

  6. <<, >> (bitwise shifts)

  7. & (bitwise AND)

  8. ^ (bitwise XOR)

  9. | (bitwise OR)

  10. Comparisons (<, >, ==, etc.)

  11. not

  12. and

  13. or

\boxed{\text{Use parentheses to override precedence and improve clarity.}}


5. Input from User

  • input(prompt): Reads a line from standard input (always returns a string).

    
    name = input("Enter your name: ")  # User types "Alice" → name = "Alice"
    
    
  • Type Conversion is Mandatory for numeric input:

    
    age = int(input("Enter age: "))  # Must enter a valid integer
    
    
  • Handling Invalid Input: Use try-except (see Unit 1.14) to catch ValueError from int()/float().


6. Control Flow: Conditional Statements

Syntax:


if condition1:

    # code block

elif condition2:

    # code block

else:

    # code block (optional)

  • Conditions evaluate to True or False.

  • Only one block executes.

  • Indentation defines the block (typically 4 spaces).

Ternary Conditional Operator (Inline If-Else):


result = "Pass" if score >= 50 else "Fail"

# Equivalent to:

if score >= 50:

    result = "Pass"

else:

    result = "Fail"

[!TIP] Common Pitfall: Using = (assignment) instead of == (comparison) in conditions. Python will raise a SyntaxError in recent versions for if x = 5:.


7. Control Flow: Loops

while Loop

  • Executes as long as condition is True.

  • Pattern:

    
    counter = 0
    
    while counter < 5:
    
        print(counter)
    
        counter += 1  # Crucial: update condition variable!
    
    
  • Infinite Loop: while True: (requires break to exit).

  • break: Exits the nearest enclosing loop immediately.

  • continue: Skips rest of current iteration, jumps to next loop condition check.

for Loop

  • Iterates over a sequence (list, tuple, string, range).

  • Syntax: for item in sequence:

    
    for i in range(5):  # 0, 1, 2, 3, 4
    
        print(i)
    
    
  • range(start, stop, step): Generates numbers. stop is exclusive.

    • range(3) → 0,1,2

    • range(1, 4) → 1,2,3

    • range(0, 10, 2) → 0,2,4,6,8

  • else clause: Executes after loop finishes normally (not via break).

    
    for n in range(2, 10):
    
        for i in range(2, n):
    
            if n % i == 0:
    
                break
    
        else:
    
            print(f"{n} is prime")
    
    

8. Data Structures I: Lists

  • Ordered, mutable, allows duplicate elements.

  • Creation: my_list = [1, 2, 3], list(iterable), [x**2 for x in range(5)] (list comprehension).

  • Access:

    • Indexing: list[0], list[-1] (last).

    • Slicing: list[1:4] (returns new list).

  • Common Methods:

    • append(x): Add to end.

    • extend(iterable): Add multiple items.

    • insert(i, x): Insert at index.

    • remove(x): Remove first occurrence (ValueError if not found).

    • pop([i]): Remove & return item at index i (default last).

    • index(x): Return first index of x.

    • count(x): Count occurrences.

    • sort(): In-place sort (mutates).

    • reverse(): In-place reverse.

    • clear(): Remove all items.

  • List Comprehension: [expression for item in iterable if condition]

    
    squares = [x**2 for x in range(10) if x % 2 == 0]  # [0, 4, 16, 36, 64]
    
    

9. Data Structures II: Tuples & Sets

Tuples (tuple)

  • Ordered, immutable, allows duplicates.

  • Creation: t = (1, 2, 3), t = 1, 2, 3 (packing), tuple(iterable).

  • Single-element tuple: t = (5,) (comma is mandatory).

  • Packing/Unpacking:

    
    a, b, c = (1, 2, 3)  # Unpacking
    
    t = a, b, c          # Packing
    
    
  • Use Case: Fixed data, dictionary keys (since immutable), function returns multiple values (as tuple).

Sets (set)

  • Unordered, mutable, no duplicates.

  • Creation: s = {1, 2, 3}, set(iterable). {} creates dict, not set!

  • Properties: Elements must be hashable (immutable types: int, str, tuple).

  • Common Methods:

    • add(x): Add single element.

    • remove(x): Remove x (KeyError if missing).

    • discard(x): Remove x if present (no error).

    • pop(): Remove & return arbitrary element (KeyError if empty).

    • clear(): Remove all.

  • Mathematical Operations:

    • Union: s1 | s2 or s1.union(s2)

    • Intersection: s1 & s2 or s1.intersection(s2)

    • Difference: s1 - s2 (in s1 not s2)

    • Symmetric Difference: s1 ^ s2 (in either but not both)

[!TIP] Key Difference: Lists are ordered/mutable; Tuples are ordered/immutable; Sets are unordered/mutable/no duplicates. Choose based on need for order, mutability, and uniqueness.


10. Data Structures III: Dictionaries

  • Key-Value pairs. Keys must be immutable & unique. Values can be any object.

  • Creation: d = {'a': 1, 'b': 2}, dict(iterable), dict(key=value), {k:v for k,v in iterable}.

  • Access:

    • d[key]: Returns value (KeyError if key missing).

    • d.get(key, default=None): Safer, returns default if key missing.

  • Modification:

    • d[key] = value: Add or update.

    • del d[key]: Remove key (KeyError if missing).

    • d.pop(key): Remove & return value.

    • d.popitem(): Remove & return last inserted (LIFO, Python 3.7+).

  • Common Methods:

    • d.keys(): View of keys.

    • d.values(): View of values.

    • d.items(): View of (key, value) tuples.

    • d.clear(): Remove all.

  • Iteration:

    
    for key in d:           # Iterates keys
    
    for key in d.keys():    # Explicit keys
    
    for value in d.values():
    
    for key, value in d.items():
    
    

11. Functions

Defining & Calling:


def greet(name, message="Hello"):  # `message` has default value

    """Returns a greeting string."""  # Docstring

    return f"{message}, {name}!"

result = greet("Alice")  # Uses default message

result = greet("Bob", message="Hi")  # Keyword argument

Parameters & Arguments:

  • Positional: Arguments matched by position.

  • Keyword: func(arg=value). Order doesn't matter.

  • Default Values: def func(a, b=10):

  • Variable-Length:

    • *args: Tuple of positional arguments.

    • ``**kwargs`: Dict of keyword arguments.

    
    def func(*args, **kwargs):
    
        print(args)   # tuple
    
        print(kwargs) # dict
    
    

Return Statement:

  • return value: Exits function, returns value.

  • return: Exits, returns None.

  • return x, y: Actually returns a tuple (x, y).

Variable Scope:

  • Local: Inside function. Created on function call, destroyed on return.

  • Global: At module level. Accessible everywhere in module.

  • global keyword: Modify global variable inside function (use sparingly).

    
    x = 10
    
    def func():
    
        global x
    
        x = 20  # Modifies global x
    
    

Lambda Functions:

  • Anonymous, single-expression functions.

  • Syntax: lambda arguments: expression

  • Use Case: Short functions for map(), filter(), sorted(key=...).

    
    square = lambda x: x**2
    
    points = [(1,2), (3,1), (5,0)]
    
    points_sorted = sorted(points, key=lambda p: p[1])  # Sort by y-coordinate
    
    

12. Modules & Packages (Introduction)

  • Module: A .py file containing Python definitions (functions, classes, variables).

  • Importing:

    
    import math               # Use math.sqrt()
    
    from math import sqrt     # Use sqrt() directly
    
    from math import *        # Imports all (discouraged - namespace pollution)
    
    import math as m          # Alias: m.sqrt()
    
    
  • Standard Library Examples: math (math functions), random (random numbers), datetime (date/time).

  • Creating a Module: Save functions in mymodule.py, then import mymodule.

  • Package: Directory containing multiple modules and a special __init__.py file (can be empty). Allows hierarchical structuring (import mypackage.mymodule).


13. File Handling (Basic I/O)

File Paths:

  • Absolute: Full path from root (C:\data\file.txt or /home/user/file.txt).

  • Relative: Path relative to current working directory (data/file.txt).

Opening Files:


file = open("filename.txt", "r")  # Modes: 'r' (read), 'w' (write, truncate), 'a' (append), 'r+' (read/write)

  • Always close files: file.close().

  • Best Practice: Use with statement (Context Manager) – auto-closes:

    
    with open("data.txt", "r") as f:
    
        content = f.read()  # File automatically closed after block
    
    

Reading:

  • f.read(size=-1): Read entire file or size bytes.

  • f.readline(): Read one line (including \n).

  • f.readlines(): Read all lines into list.

  • Iterating (Best for large files):

    
    with open("file.txt") as f:
    
        for line in f:  # Reads line by line, memory efficient
    
            print(line.strip())
    
    

Writing:

  • f.write(string): Write string (no newline added automatically).

  • f.writelines(list_of_strings): Write each string in list (no separators added).

CSV Files (Basic):


import csv

with open("data.csv", "r") as f:

    reader = csv.reader(f)

    for row in reader:  # row is a list of strings

        print(row)


14. Error & Exception Handling

Syntax Errors: Code structure mistakes (caught by interpreter before execution). Exceptions: Runtime errors (e.g., ZeroDivisionError, TypeError).

try-except-else-finally Structure:


try:

    # Code that might raise an exception

    result = 10 / 0

except ZeroDivisionError as e:

    # Handle specific exception

    print(f"Error: {e}")

except (TypeError, ValueError):

    # Handle multiple exceptions

    print("Type or Value error occurred")

except Exception as e:

    # Catch-all (use cautiously)

    print(f"Unexpected error: {e}")

else:

    # Executes if NO exception in try block

    print("Operation successful")

finally:

    # Executes ALWAYS (cleanup: close files, release resources)

    print("Cleanup complete")

Common Built-in Exceptions:

  • ValueError: Invalid value for operation (e.g., int("abc")).

  • TypeError: Operation on wrong type (e.g., "a" + 1).

  • IndexError: Sequence index out of range.

  • KeyError: Dictionary key not found.

  • FileNotFoundError: File doesn't exist.

  • ZeroDivisionError: Division/modulo by zero.

Raising Exceptions:


def set_age(age):

    if age < 0:

        raise ValueError("Age cannot be negative")

    # ...

[!TIP] Exam Focus: Be able to write a complete try-except block. Know the purpose of else (no exception) and finally (always runs). Understand the hierarchy of exceptions.

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