🐍

Complete Python Setup and Fundamentals

Dec 15, 2025

Overview

  • Lecture: Complete Python Mastery (beginners → advanced topics overview).
  • Instructor: Experienced software engineer; course uses Python 3.
  • Goals: Install Python and VS Code, learn fundamentals (types, control flow, functions), use IDE features (linting, formatting), and build good coding habits.

Installation And Setup

  • Download Python from python.org (use latest Python 3).
  • Windows: check "Add Python to PATH" during install.
  • Verify: terminal -> python --version or python3 --version (mac/linux).
  • VS Code recommended as editor; install Python extension by Microsoft.
  • Use integrated terminal (Ctrl+`) to run scripts: python app.py (Windows) or python3 app.py (mac/linux).

VS Code Features And Extensions

  • Python extension adds: linting, debugging, autocompletion, formatting, unit testing, snippets.
  • Linting (e.g., pylint) shows syntax/semantic issues live; Problems panel lists them.
  • Formatting: autopep8 formats code to follow PEP 8; enable "Format On Save".
  • Key shortcuts: Command Palette (Shift+Cmd/Ctrl+P), Problems (Shift+Cmd/Ctrl+M).
  • Add custom keyboard shortcut to run file (e.g., Ctrl+R).

Python Language vs Implementations

  • Python (language) = specification; implementations execute code.
  • CPython: default implementation (written in C).
  • Other implementations: Jython (Java), IronPython (C#), PyPy.
  • CPython compiles to bytecode then runs on Python VM; Jython compiles to Java bytecode to run on JVM.

Basic Interactive Use

  • Python interpreter / REPL allows quick experiments.
  • Expressions produce values (e.g., 2+2 → 4).
  • Booleans: True and False (case-sensitive).
  • Syntax errors indicate incorrect grammar (missing tokens, parentheses).

Key Terms And Definitions

  • Expression: code that produces a value.
  • Syntax Error: error due to incorrect grammar.
  • Linter: tool that checks code for potential errors.
  • Interpreter: program that executes Python code.
  • Module: file with Python code; import to reuse.
  • Method: function associated with an object (access via dot notation).
  • Iterable: object that can be looped over (range, string, list, tuple).
  • REPL: Read-Eval-Print Loop (interactive shell).

Primitive Types And Variables

  • Primitive types: integers (int), floating-point (float), booleans (bool), strings (str).
  • Complex numeric type: complex (a + bj).
  • Variables are labels that reference memory; use descriptive, lowercase names, underscores between words.
  • Assignment spacing and naming conventions per PEP 8 (autopep8 enforces format).

Strings

  • Define with single, double, or triple quotes (triple for multi-line).
  • Length: len(s).
  • Indexing: s[0] is first character (zero-based). Negative index: s[-1] is last char.
  • Slicing: s[start:end] returns substring; end is excluded. Omitting start/end defaults to beginning/end.
  • Escape sequences: " ' \ \n
  • Concatenation: "a" + " " + "b".
  • Formatted strings (f-strings): f"{first} {last}" — evaluate expressions inside {} at runtime.
  • Common string methods: .upper(), .lower(), .title(), .strip(), .lstrip(), .rstrip(), .find(sub), .replace(a, b).
  • Membership: "sub" in s yields Boolean. Use not in to check non-existence.

Numbers And Math Utilities

  • Arithmetic operators: +, -, *, / (floating division), // (integer division), %, ** (exponent).
  • Augmented assignment: x += 3, x *= 2, etc.
  • Built-in number functions: round(), abs().
  • For advanced math, import math module: math.ceil(), math.floor(), math.sqrt(), etc.

Input And Type Conversion

  • input(prompt) returns a string.
  • Convert types: int(), float(), bool(), str().
  • Use type(obj) to inspect type.
  • Truthy/falsy: Falsey values include 0, 0.0, "", None, False; bool(value) converts accordingly.

Comparison And Logical Operators

  • Comparison operators: >, >=, <, <=, ==, !=
  • Comparisons work for strings (lexicographic) and numbers; Python is case-sensitive.
  • Logical operators: and, or, not — used to compose conditions.
  • Short-circuit evaluation: and stops at first False, or stops at first True.
  • Chained comparisons: 18 <= age < 65 is valid and readable.

Conditional Statements

  • if condition: block must end with colon and use consistent indentation (PEP 8 recommends 4 spaces).
  • elif and else for additional branches.
  • Best practice: prefer assigning to a variable and using a conditional expression (ternary) for concise code:
    • message = "eligible" if age >= 18 else "not eligible"

Loops

  • for loops: iterate over iterable objects (range, string, list, tuple).
    • range(stop) → 0 .. stop-1
    • range(start, stop) → start .. stop-1
    • range(start, stop, step)
  • while loops: repeat while a condition is true.
  • Use break to exit a loop early.
  • for-else: else block runs only if loop completes without encountering break.
  • Nested loops: outer loop iterates; for each outer iteration, inner loop runs fully.
  • Avoid infinite loops unless intentionally controlled; include exit condition/break.

Collections And Iteration

  • Iterable examples: range object, strings, list, tuple.
  • Tuple: ordered immutable collection (created with parentheses).
  • List: ordered mutable collection (square brackets). (Detailed structures covered later.)

Exercises And Examples

  • Example: print star * 10 to repeat string.
  • For-loop attempts example: for i in range(3): print(f"Attempt {i+1}") and break if successful.
  • Example using for-range with step to produce sequence.
  • Exercise: display even numbers between 1 and 10, then print count:
    • Loop range(1, 10), check if n % 2 == 0, print and increment count.

Functions

  • Define with def name(parameters): followed by indented block.
  • Call with function_name(arguments).
  • Parameters vs arguments: parameter = placeholder; argument = actual value.
  • Functions that perform a task (side effects) vs functions that return values.
  • Return values with return statement (default return is None).
  • Example patterns:
    • Task function: def greet(name): print(...)
    • Value function: def get_greeting(name): return f"Hi {name}"
  • Optional/default parameters: def increment(number, by=1)
    • Default parameters must follow required parameters.
  • Variable-length arguments: def multiply(*numbers): receives arguments packed into a tuple; iterate to compute product.
  • Keyword arguments: call functions using parameter names for readability (e.g., increment(2, by=1) or increment(2, by=5)).

Good Practices And Style

  • Follow PEP 8: consistent indentation, spacing around operators, descriptive names.
  • Use linters and formatters (pylint, autopep8) to catch errors and enforce style.
  • Keep functions focused: return values for reuse; avoid printing directly unless function is specifically for I/O.
  • Avoid redundant comparisons for Booleans (e.g., use if high_income: rather than if high_income == True).

Action Items / Next Steps

  • Install Python 3 and VS Code; add Python extension and autopep8.
  • Practice basic REPL expressions and script execution.
  • Complete exercises: string slicing, loops, conditional logic, and the even-number counting exercise.
  • Next section: deeper fundamentals and writing reusable functions in larger programs.`