How to Think Like a Computer Scientist: Learning with Python study notes

Foreword, Preface, and Book Origins

  • Objective of the Book: To teach the reader to think like a computer scientist, combining math, engineering, and natural science. It focuses on the primary skill of problem-solving: formulating problems, thinking creatively about solutions, and expressing solutions accurately.

  • Origin and Collaboration:   - Authors: Allen Downey (college professor), Jeffrey Elkner (high school teacher), and Chris Meyers (professional programmer).   - The book is a product of the free software movement, released under the GNU Free Documentation License (GFDL).   - Originally written in Java by Allen Downey; translated to Python by Jeffrey Elkner.

  • David Beazley’s Foreword:   - Python was developed by Guido van Rossum over ten years ago, derived from the teaching language ABC.   - It successfully blends practical tools (large libraries, graphics, web-programming) with conceptual foundations (procedural abstraction, object-oriented programming, data structures).   - Beazley notes that Python reduces student frustration compared to "masochistic alternatives" like C++ and Java, allowing focus on the actual subject rather than low-level syntax errors or general protection faults.

  • Jeffrey Elkner’s Case Study: Yorktown High School (Arlington, Virginia) switched from Pascal to C++ in 1997. Elkner found C++ difficult to teach and transitioned to Python.   - A student named Matt Ahrens learned Python in two months and wrote pyTicket, a web application for technology problem reporting.   - Comparison of "Hello, World!": The C++ version required 13 paragraphs of explanation for syntax like #include, void main(), and curly braces. The Python version requires only two paragraphs, focusing on the "big idea" of a programming statement.

Chapter 1: The Way of the Program

  • Definition of a Program: A sequence of instructions specifying how to perform a computation. Basic universal instructions include:   - input: Getting data from the keyboard, files, or devices.   - output: Displaying data on the screen or sending it to a file.   - math: Performing operations like addition and multiplication.   - conditional execution: Checking conditions and executing appropriate statements.   - repetition: Performing actions repeatedly with variations.

  • Python as a High-Level Language:   - High-level languages (Python, C, C++, Java, Perl) are easier to write, shorter, and more portable across different computers.   - Low-level languages (machine or assembly language) are the only ones computers execute directly.   - Processing Methods:     - Interpreter: Processes the program a little at a time, alternately reading lines and performing computations.     - Compiler: Translates source code completely into object code (or an executable) before running.

  • Modes of Interaction:   - Command-line mode: Typing programs directly; the interpreter prints results immediately after >>> prompt.   - Script mode: Storing a program in a file (ending in .py) and telling the interpreter to execute it.

  • Debugging Types:   - Syntax errors: Violations of the language's structure and rules; Python will not run if even one exists.   - Runtime errors (Exceptions): Errors that appear only when the program is running.   - Semantic errors: The program runs successfully but does not do the intended task (it follows instructions we gave, not what we wanted).

  • Formal vs. Natural Languages:   - Natural languages: Evolved naturally (English, Spanish). Ambiguous, redundant, and metaphorical.   - Formal languages: Designed for specific applications (math notation, chemical formulas, programming). Unambiguous, concise, and literal.   - Parsing: Examining a program and analyzing its syntactic structure.   - Tokens: Basic elements (words, numbers, symbols) of a language.

Chapter 2: Variables, Expressions, and Statements

  • Values and Types:   - Value: A fundamental thing like a letter or a number.   - Types:     - int: Integers (e.g., 1717, 22).     - float: Numbers with decimal points (floating-point).     - str: Strings of letters enclosed in quotes (e.g., "Hello, World!").

  • Variables: A name that refers to a value. The assignment statement (using =) creates new variables.

  • Variable Names and Keywords: Names must begin with a letter, are case-sensitive (Bruce vs bruce), and cannot be one of the 29 Python keywords (e.g., and, def, if, while, lambda).

  • Expressions and Operators:   - Expression: Combination of values, variables, and operators that represent a result.   - Operators: Special symbols (++, -, *, //, ** for exponentiation).   - Integer Division: In Python (version 2), dividing two integers rounds down to the next lower integer (e.g., 59 / 60 yields 00).

  • Order of Operations (PEMDAS):   - 1. Parentheses: 2 * (3-1) is 44.   - 2. Exponentiation: 2**1+1 is 33.   - 3. Multiplication and Division (Left to Right).   - 4. Addition and Subtraction (Left to Right).

  • String Operations:   - + (Concatenation): Joins strings end-to-end.   - * (Repetition): Repeats a string (e.g., "Fun" * 3 is "FunFunFun").

  • Comments: Notes for programmers starting with the # symbol; everything to the end of the line is ignored by the interpreter.

Chapter 3: Functions

  • Function Call: Consists of the function name followed by arguments in parentheses (e.g., type("32")). It returns a result called a return value.

  • Type Conversion and Coercion:   - int(): Converts to integer (truncates floating-point values).   - float(): Converts to floating-point.   - str(): Converts values to strings.   - Type Coercion: Automatic conversion where mixed-type operations (like 59 / 60.0) force the result to be a float.

  • Math Module: Provides mathematical functions. Must use dot notation after importing (e.g., math.log10(), math.sin()). Angles are in radians.

  • New Functions:   - Defined using def NAME(LIST OF PARAMETERS):.   - Indented statements following the header form the body.

  • Flow of Execution: Jumps from the point of call to the function definition and returns to where it left off. Functions must be defined before use.

  • Scope:   - Parameters and Local Variables exist only inside their function.   - Stack Diagrams: Visual representation of frames (boxes) showing where variables reside and which function is executing. The topmost function is __main__.

  • Composition: Using an expression as an argument or using the result of one function as an argument for another.

Chapter 4: Conditionals and Recursion

  • Modulus Operator: Denoted as %, yields the remainder of a division (e.g., 7 % 3 is 11).

  • Boolean Expressions: Evaluate to True or False. Comparison operators include ==, !=, >, <, >=, <=.

  • Logical Operators: and, or, and not combine boolean expressions.

  • Conditional Execution:   - If: Executes a block if the condition is true.   - Alternative Execution (if-else): Two branches; exactly one executes.   - Chained Conditionals (elif): Allows more than two branches.   - Nested Conditionals: Conditionals inside other conditionals.

  • Recursion: A function that calls itself.   - Base Case: The conditional branch that does not make a recursive call, preventing infinite recursion.   - Infinite recursion eventually causes a "Maximum recursion depth exceeded" runtime error.

  • Keyboard Input:   - raw_input(): Gets a string from the user. Use conversion functions to change types.   - input(): Evaluates what the user types (risky if they enter non-numeric value).

Chapter 5: Fruitful Functions

  • Fruitful Functions: Functions that return a value other than None.

  • Incremental Development: Method of writing code by adding small, tested chunks to avoid long debugging.   - Example: Writing a distance function distance=(x2x1)2+(y2y1)2distance = √{(x_2 - x_1)^2 + (y_2 - y_1)^2} step-by-step using temporary variables like dx and dy.

  • Scaffolding: Code used for development (like print statements) that is not part of the final program.

  • Boolean Functions: Return True or False. Often used in conditional logic.

  • Leap of Faith: Mental shortcut where one assumes a recursive call works correctly to simplify solving the larger problem.

  • Factorial Example:   - 0!=10! = 1   - n!=n(n1)!n! = n(n-1)!

  • Fibonacci Example:   - fib(0)=1fib(0) = 1   - fib(1)=1fib(1) = 1   - fib(n)=fib(n1)+fib(n2)fib(n) = fib(n-1) + fib(n-2)

  • Guardians: Using isinstance to check types and handling negative values to ensure recursion terminates.

Chapter 6: Iteration

  • Multiple Assignment: Assigning different values to the same variable at different times (legal, but potentially confusing).

  • While Loop: Repeatedly executes a block while a condition is true. This process is called iteration.   - Example: The Collatz-like sequence where n becomes n/2 if even or n*3+1 if odd.

  • Tab Escape Sequence (\t): Used to align output in columns for tables (e.g., powers of two or logarithms).

  • Encapsulation and Generalization:   - Encapsulation: Gathering code into a function.   - Generalization: Making functions more versatile by adding parameters (e.g., changing a multiplication table from 2×62 × 6 to an arbitrary size n×highn × high).

  • Local Variables: Variables like loop counters (i) inside a function are unique to that function, even if another function uses a variable with the same name.

Chapter 7: Strings

  • Strings as Compound Types: Strings are sequences of characters.

  • Bracket Operator ([]): Selects a character via an index. Indexing starts at 00.

  • Length: len("banana") is 66. Accessible indices are 00 to len - 1.

  • Traversal: Iterating through a string using a while or for loop.

  • Immutability: Strings cannot be changed once created (TypeError). Modifying a string requires creating a new one (e.g., using slices).

  • Slices: s[n:m] returns a segment from the nn-eth character to the mm-eth character, including the first but excluding the last.

  • String Methods: The string module provides functions like find(), constants like string.lowercase, string.digits, and string.whitespace.

Chapter 8: Lists

  • Definition: A list is an ordered set of values called elements. Unlike strings, they are mutable.

  • List Creation: Square brackets [10, 20, 30]. Elements can be different types, and lists can be nested.

  • Range: range(1, 10, 2) returns a list of integers starting at 11, up to (but not including) 1010, with a step of 22.

  • Mutation and Deletion:   - Slices can update or remove multiple elements: list[1:3] = [].   - del statement removes single elements or slices.

  • Aliasing and Cloning:   - Aliasing: Two variables referring to the same object in memory. Changes to one affect the other.   - Cloning: Creating a copy of a list using a full slice: b = a[:].

  • List Parameters: Passing a list to a function passes a reference; modifications inside the function affect the original list.

  • String/List Conversion: string.split(song) breaks a string into a list of words; string.join(list) concatenates them.