Programming in Python

Rob Speer

Contents

Day 1: Introduction to Programming

Programming versus math

In math, you can define a square root like this:

  • \sqrt{x} = a real number r such that r2 = x

In programming, you can define a square root like this:

To find the square root of x:
  • Start by making an arbitrary guess, like 1. Call this guess G.
  • Find 1 / G.
  • If G \approx 1/G (that is, G - \frac1G < \epsilon) then you're done, and \sqrt{x} \approx G.
  • Otherwise, take \frac{G - 1/G}{2} as the new guess and repeat.

Math is for declarative knowledge (about "what you know"); programming is for procedural knowledge (about "how you do it").

Python

Python is a programming language: one particular way to tell the computer what to do.

Python is considered an interpreted language because the computer is reading the instructions in Python and following them ("interpreting" them) as it goes.

Other languages are compiled, meaning that the instructions need to be translated into machine code (the low-level zeros and ones that your processor wants to hear) before the program runs.

Some interpreted languages you may know of: Perl, JavaScript, BASIC.

Some compiled languages you may know of: C, C++, Java.

A simple program

print "Hello, world!"

You're instructing the computer to put the text "Hello, world!" on the screen.

  • This is called "printing" because the idea dates back to the days when computers actually output everything through a printer.
  • In these more enlightened times, the text will be "printed" in your Python window.

Blocks

Programs are made of functions, which let you define some instructions once and use them in different situations.

The program needs to know which statements are part of the function. In Python, you do this by indenting all the lines in the function.

Topics

  • Hello World
  • Arithmetic
  • Variables and types
  • Strings
  • Functions
    • silly function-ized "hello world"
  • if
    • Absolute value example
  • While loops
    • smallest fibonacci number greater than 100
    • largest fibonacci number less than 100
    • 99 Bottles of Beer
  • For loops
    • Deutsch Deutsch Deutsch Deutsch
    • factorial example
    • Relay problem
  • Recursion
    • Euclidean algorithm
    • Factorial again
  • Input
    • Monty Python example
  • Random numbers
    • dice roller
    • game of Rock Scissors
  • game of three-pile Nim