1. Elements of Programming
Our goal in this chapter is to convince you that composing a computer program is easier than writing a piece of text such as a paragraph or an essay. Writing prose is difficult: we spend many years in school to learn how to do it. By contrast, just a few building blocks suffice to take us into a world where we can harness the computer to help us solve all sorts of fascinating problems that would be otherwise unapproachable. In this chapter, we take you through these building blocks, get you started on programming in Python, and study a variety of interesting programs.
- 1.1 Your First Program instructs you on how to compose and execute a Python program on your system.
- 1.2 Built-in Types of Data describes Python's built-in data types for manipulating strings, integers, real numbers, and booleans.
- 1.3 Conditionals and Loops introduces Python structures for control flow, including
if
,while
, andfor
statements. - 1.4 Arrays considers a data structure known as the array for organizing large quantities of data.
- 1.5 Input and Output extends the set of input and output abstractions (from command-line input and standard output) to include standard input, standard drawing, and standard audio.
- 1.6 Case Study: Random Web Surfer presents a case study that models the behavior of a web surfer using a Markov chain.
Python Programs in this Chapter
Below is a list of Python programs and data files used in this chapter.
REF PROGRAM DESCRIPTION DATA 1.1.1 helloworld.py Hello, World – 1.1.2 useargument.py using a command-line argument – 1.2.1 ruler.py string concatenation example – 1.2.2 intops.py integer operators – 1.2.3 floatops.py float operators – 1.2.4 quadratic.py quadratic formula – 1.2.5 leapyear.py leap year – 1.3.1 flip.py flipping a fair coin – 1.3.2 tenhellos.py your first loop – 1.3.3 powersoftwo.py computing powers of two – 1.3.4 divisorpattern.py your first nested loops – 1.3.5 harmonic.py harmonic numbers – 1.3.6 sqrt.py Newton's method – 1.3.7 binary.py converting to binary – 1.3.8 gambler.py gambler's ruin simulation – 1.3.9 factors.py factoring integers – 1.4.1 sample.py sampling without replacement – 1.4.2 couponcollector.py coupon collector simulation – 1.4.3 primesieve.py sieve of Eratosthenes – 1.4.4 selfavoid.py self-avoiding random walks – 1.5.1 randomseq.py generating a random sequence – 1.5.2 twentyquestions.py interactive user input – 1.5.3 average.py averaging a stream of numbers – 1.5.4 rangefilter.py a simple filter – 1.5.5 plotfilter.py standard input to draw filter usa.txt 1.5.6 bouncingball.py bouncing ball – 1.5.7 playthattune.py digital signal processing elise.txt ascale.txt stairwaytoheaven.txt entertainer.txt firstcut.txt freebird.txt looney.txt 1.6.1 transition.py computing the transition matrix small.txt medium.txt 1.6.2 randomsurfer.py simulating a random surfer – 1.6.3 markov.py mixing a Markov chain –