2012 March 27,

CS 111: Introduction to Python, Part B

Carleton College, Spring 2012

Prof. Joshua R. Davis, , Goodsell 106B, x4473

Writing and Running Python Programs

In this section we learn how to write a Python program in a text editor and run that program in the Python interpreter. The instructions are specific to TextWrangler running on Mac OS X, but other text editors behave similarly. We also learn the most important commands for navigating among folders in bash.

Launch the TextWrangler program by clicking its icon in your Dock. (If it's not there, then ask for help.) You should be greeted with a big, white window.

A text editor is kind of like a word processor (such as Microsoft Word), in that it is a program where you type a bunch of text. However, a text editor lacks many features, such as spell checking, mail merging, and what-you-see-is-what-you-get editing. Instead it offers powerful "structural" features, such as sophisticated search-and-replace queries, and the ability to understand computer code and display it in a helpful manner. Loosely speaking, you use a word processor if the document you're typing is going to be read by a human; you use a text editor if the document you're typing is going to be read by a computer. So we edit Python programs in a text editor.

A computer program is nothing more or less than a sequence of commands. Type the following commands into the TextWrangler window. In case it's not clear, the code is trying to convert a time period measured in seconds into a time period measured in years.

secondsPerYear = 60 * 60 * 24 * 365.25
secondsElapsed = 27000.341
yearsElapsed = secondsElapsed / secondsPerYear

Now press Command-S and save the file to your Desktop, giving it a name such as "secondstoyears.py". The ".py" suffix is conventional for Python programs, although not strictly necessary.

Keeping the TextWrangler window open, also open the Terminal program. Do not launch the Python interpreter in the terminal window; just stay in bash. In bash, first enter the command pwd (followed by Return). pwd means "print working directory"; it tells you where you are in the computer's file system:

Now use the ls ("list") command to list all of the files and folders here:

Assuming that you saved your secondstoyears.py program to your desktop, now do cd Desktop ("change directory" to Desktop) followed by ls:

You should see your secondstoyears.py program there. To run the program, enter python2 secondstoyears.py:

Your program ran, but you didn't ever get to see the answer. This is because you never told the program to produce any output. To fix this, go back to TextWrangler, add the line print yearsElapsed to the end of the program, and save the file. Then return to bash and press the up-arrow key. This takes you back to the last command, which was python2 secondstoyears.py. Press Return to issue this command again; it should now show you the answer:

When you run Python commands in the Python interpreter, the interpreter shows you the result of every command automatically. On the other hand, when you type Python commands into a file and run the file, Python does not show you the result of every command; instead, it outputs only what you tell it to, using the print command.

Warning: Python 3, which the Miller and Ranum text uses, has slightly different conventions for the print command; it requires parentheses, as in print(yearsElapsed). In Python 2, which we use, it is better to omit the parentheses.

So there are two ways to interact with Python. The first way is to type individual commands into the Python interpreter. This is useful for when you want to do little experiments, to figure out how a particular Python command works. The second way is to type a sequence of commands into a text file, and then to execute that program as a whole using the Python interpreter. This is useful when you are writing complicated programs consisting of many commands.

By the way, here is a cheat sheet of handy commands for the terminal.

Question A: In that program, what is the type of the variable yearsElapsed? How would you figure this out, from earlier questions I've asked? How would you test your answer, using the Python interpreter?

Question B: Suppose that, instead of saving the program file to your Desktop, you instead saved it in a folder "cs111" inside your Documents folder? How would you execute that program?

Conditionals (if)

In this section, we start writing Python code that is able to alter its behavior based on the information at hand. This is a huge first step toward writing interesting programs.

For example, suppose that I want to compute the absolute value of a number. For a positive number (such as 3), the absolute value is the same as the number (3). For a negative number (such as -5.8), the absolute value is the negative of that number (--5.8 = 5.8). We can implement this idea in Python as follows.

number = -5.8
if number >= 0:
    absval = number
else:
    absval = -number
print absval

Type that code into TextWrangler, save the file, and execute the program. Then, change -5.8 to other values — both positive and negative, both integers and floating-point numbers — to observe how the behavior of the program changes.

Often, a program's logic is too complicated to capture with a single if statement. For example, suppose that an insurance company sets its auto insurance rates based on the driver's age. Drivers under 18 or over 100 are risky; drivers 18-25 are less risky; drivers 25-100 are the least risky of all. We can implement this idea by nesting if statements. Run the following code, trying various ages.

age = 31
if age < 18:
    rate = 450
else:
    if age > 100:
        rate = 500
    else:
        if age < 25:
            rate = 400
        else:
            rate = 300
print rate

Question C: Suppose that the program is run with age 17. Exactly which of the three if statements gets executed? What if the age is 19? What if it's 50? What if it's 150?

In fact, such nested combinations of else and if are so common, that there is a shortcut, elif, for dealing with them. The following code is equivalent, but much easier to type.

age = 31
if age < 18:
    rate = 450
elif age > 100:
    rate = 500
elif age < 25:
    rate = 400
else:
    rate = 300
print rate

Now that we are starting to write programs with a lot of indentations, you need to know something: Python is very sensitive to indentations. All of the code, within a single indented block, must be indented in exactly the same way, or Python complains. The most subtle and irritating example is described here.

Question D: What's wrong with the following code? How do you fix it?

age = 31
if age < 18:
    rate = 450
else:
    if age > 100:
        rate = 500
    else:
        if age < 25:
            rate = 400
         else:
            rate = 300
print rate

In if statements, you test equality using ==. For example, here's how you test whether an integer is even or odd:

mystery = 13
if mystery % 2 == 0:
    print "even"
else:
    print "odd"

Be sure to keep the = and == operators distinct in your mind; they do very different things.

Booleans

The preceding section described how if statements change their behavior based on whether a certain condition is true or false. In this brief section, we focus on the condition itself.

A Boolean value is a value that is either True or False. Enter the following commands into the interactive Python interpreter, to explore Booleans. (The != operator means "does not equal".)

3.2 < 5

type(3.2 < 5)

type(False)

"Obama" == "President"

"Obama"[1:4] == "b" + "am"

3.0 != 8 / 2

4.0 != 8 / 2

You can combine Booleans using the operators and, or, and not. For example, the following code tests whether a given person is allowed to vote:

name = "Big Bird"
age = 42
isFelon = True
if age >= 18 and not isFelon:
    print name, "may vote."
else:
    print name, "may not vote."

Question E: Rewrite that code, so that it uses neither and nor not, but instead uses or, and accomplishes exactly the same task.

Iteration (while)

Computers are dumb, but they sometimes appear smart, because they are able to do simple calculations over and over again, at high speed, without ever tiring. The "over and over again" part is called looping or iteration. In this section we learn our first looping technique.

Let's just dive in. First, look at this code, and try to guess what it does. Then run it.

i = 1
while i < 5:
    print "Repetition is repetitive."
    i = i + 1

You should think of a while as a repeated if. If the while statement (i < 5) is true, then the indented block gets executed. If the condition is still true, the indented block gets executed again. This repeats until the condition is no longer true. The variable i is called a loop counter. On the first pass through the loop, i has value 1. At the end of the first pass, its value is changed to 2. On the second pass through the loop, its value is 2. At the end of the second pass, its value is changed to 3. And so on.

Loop counters don't have to count up by 1 on each pass through the loop; they can count down by 1, or down by 5, or whatever you want. And usually they are used somewhere within the body of the loop. Here's a more sophisticated example:

sum = 0
n = 100
while n >= 0:
    sum = sum + n
    n = n - 2
print sum

Question F: Describe, in plain English, what that loop accomplishes.

Question G: Write a loop to compute the sum 12 + 22 + 32 + ... + 1002.

You can nest while statements within while statements, and within if statements, and vice-versa, to your heart's content. This code prints out the auto insurance rates for all ages 16-34. Examine carefully, how the nesting works.

age = 16
while age <= 34:
    if age < 18:
        rate = 450
    elif age > 100:
        rate = 500
    elif age < 25:
        rate = 400
    else:
        rate = 300
    print age, ":", rate
    age = age + 1

Also, did you see my fancy print statement? You can print multiple items on a single line, if you separate them with commas. You can even make multiple print statements print on the same line, by using trailing commas. Try this next dumb example. (By the way, if you're pasting this code into the interactive Python interpreter, you'll miss the effect. You have to paste it into a file, save the file, and execute the file.)

print "Are",
print "you",
print "Brad Pitt?"
print "No;",
print "please stop asking."

Question H: Write a program that prints out a 10-by-10 multiplication table. Your program should use two while loops, one inside the other. Hint: The two loops must have different loop counters.

My Friend Paul

In this section, we learn no new concepts. We just put the earlier concepts to heavier use. The premise may seem silly, but there is a reason for it, which we will discuss in class. So please be patient.

I have a friend named Paul with a strange quirk. When you tell him a positive integer, he will respond in one of two ways. If the integer is even, then he will divide it in two and tell you the answer. If the integer is odd, then he will multiply it by three, then add one, and then tell you the answer. For example, he responds to "14" with "7", and he responds to "15" with "46". Paul is very good at mental arithmetic; he responds to "1729" with "5188" immediately.

Question I: Write a program that uses an if statement to print Paul's response for any given number.

I play a game with Paul. I give him a positive integer. As soon as he responds, I repeat what he said back to him, like a parrot. As soon as he responds to that, I repeat what he said. For example:

Me: 5

Paul: 16

Me: 16

Paul: 8

Me: 8

Paul: 4

Me: 4

Paul: 2

Me: 2

Paul: 1

Me: 1

Paul: 4

Me: 4

Paul: 2

Me: 2

Paul: 1

Me: 1

Paul: 4

...

As you can probably see, as soon as we hit 4, we enter a never-ending loop of 4, 2, 1, 4, 2, 1, 4, 2, 1, .... This is tedious, even by our low standards. So, by agreement, we stop our game as soon as I say "1".

Question J: Using a while loop and an if statement, write a program that starts with any given number, such as 5, and prints out our entire game based on that number. (Your program should work for any starting number you enter — not just 5.) I'll get you started:

number = 5
print "Me:", number
while number > 1:

Be sure to test your code on some small numbers, to make sure it works. Also run your code on the numbers 26 and 27. Although there's not much difference between these two numbers, the game based on 27 takes about 10 times as long as the game based on 26.

Question K: Modify your code from the previous question, to accomplish this new task: Write a program that starts with any given number, and prints out how many things I say, in the game based on that number. For example, if the starting number is 5, then your program should print 6 (because I say "5", "16", "8", "4", "2", "1").

For the sake of brevity, let's call the number you just computed the "game length". For example, the game length of 5 is 6, because I say 6 things in the game that starts at 5. The game length of 16 is 5.

Question L: Write a program that prints out the game length of every integer from 1 to 100.

Question M: Does every one of these games between Paul and me end? Or are there some starting numbers — maybe very large ones — that lead to never-ending games?

Iteration (for)

Loops are extremely common in computer programs. Furthermore, many of these loops use a loop counter, that counts up or down, changing by a fixed amount on each step, like clockwork. In fact, clockwork loop counters are so common that there is a shortcut for them, called for. Try these:

for i in range(10):
    print i

for k in range(4, 8):
    print k

for joe3 in range(3, 12, 2):
    print joe3

for i in range(10, 0, -1):
    print i

As you can probably surmise, for i in range(a, b, c): makes a loop, with loop counter i, that starts at a, and changes by c on each pass through the loop, until just before it reaches the value b.

Question N: for i in range(a, b): is simply a shorthand for for i in range(a, b, c):, with a particular value of c assumed. Explain.

Question O: Similarly, for i in range(n): is a shorthand for some longer for statement, with particular values assumed. Explain.

Question P: Redo Question G, using a for loop instead of a while loop.

Here's a teaser question: What is the type of range(3, 12, 2)? The answer leads us to the next section of this introductory tutorial.