2012 March 25,

CS 111: Introduction to Python, Part A

Carleton College, Spring 2012

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

Introduction

This tutorial gives you a succinct introduction to the Python programming language. By the end of the tutorial, you will have an idea of how Python works, but you will not have mastered the language. That's okay; we will revisit and reuse these concepts throughout our course.

It is essential that you read this document at a computer, trying every Python command for yourself!

What's Python?

Python is a computer programming language — a language that a human uses, to give instructions to a computer. When you first start using Python, it's typically through a textual interface like this:

However, Python programs are not limited to producing text. Here's some 3D graphics I made with Python:

And here's some better 3D graphics, that a professional using Autodesk Maya might make with Python:

Python is used in the Ciranova circuit layout program, for designing electronics:

Environmental scientists, geologists, civil engineers, city planners, and others use geographic information systems to collect and analyze data related to the Earth. One of the most popular GIS packages, ArcGIS, uses Python heavily:

Python is one of the most popular languages for constructing sophisticated web applications. For example, Google and YouTube use it heavily. For another example, a couple of years ago I wrote a little web application in Python, to help my calculus students practice differentiation; you can try it here.

Here is a recent story, about a fellow who used Python, a video camera, a robot, and a water gun to automatically defend his backyard against squirrels.

Python is available for many different platforms (Windows, Mac OS X, Linux, etc.), including some mobile phones:

Here are some other examples of companies and products that use Python. Anyway, it should be clear that there is a lot that Python can do. In fact, it can do anything that a computer can do at all.

Running the Python Interpreter Interactively

The Python programming language can be used in two different ways. It can be used interactively, like some sort of super-powered calculator. Alternatively, it can be used to run pre-written batches of commands, called programs. In this short section, we learn the first way of using Python.

Along the bottom of your screen is a row of icons, called the Dock. Each icon represents a program, folder, or document, that you can open by clicking. Locate and click the Terminal icon, to launch that program. (If it's not there, then ask for help.) You should see a window much like the following, although the color and text may be different.

Put simply, a terminal is a program that lets you run other programs — especially programs with textual interfaces. Right now the terminal is running the program bash. The > is a prompt indicating that bash is waiting for your command; your setup may use $ for a prompt instead of >, but that is just a cosmetic difference.

Type python2 and press the Return key. You have just told bash to run the Python interpreter, which takes over the terminal. The bash program is still running; it's just temporarily hidden by the Python interpreter.

The prompt >>> indicates that the Python interpreter is waiting for your command. You can press Control-D to exit the Python interpreter; then you find yourself back in bash. You can quit the Terminal program entirely by pressing Command-Q, if you like.

Arithmetic

In this section we use the Python interpreter as a glorified hand calculator. We also learn how to store values in variables.

Launch the Python interpreter using the directions of the preceding section. Then enter each of the following commands (pressing Return after each one), to see what they do.

3.0 + 6.5

2.2 - 17.2

14.3 * 2.0

14.3 / 2.0

3.0 ** 4.0

Question A: What's wrong with 14.3 * 2.0?

Question B: What does the ** operator do?

When you do long computations on a hand calculator, it is helpful to store intermediate results in memory. On primitive calculators you put a value into memory using the M+ key, you retrieve a value using the MR key, and so on. On more recent calculators, there are multiple memory slots, called A, B, C, etc., where you can store results.

Python can also store values in memory, using the = operator. Try these commands, in order:

x = 5.7

x

3.0 + x

y = x ** 2.0

y

z = x - y

z

z = x + y

z

z = z + 3.0

z

The x, y, and z in the preceding example are called variables. A variable is a named location in the computer's memory. Once you've assigned a value to a variable using =, you can use the value any time you want by simply invoking the variable's name. You can also assign a new value to a variable at any time.

Question C: Does = have the same meaning in Python as it does in a math class? Does the term variable have the same meaning in Python as it does in a math class?

Question D: What happens when you try to use a variable's value before you've stored a value in that variable?

Question E: What happens when you compute sin(0)?

Variable names are not limited to single letters. Try these commands:

timmy_smith = 3 ** 2

timmy_smith = timmy_smith + 7.0

celsius = 20

fahrenheit = 1.8 * celsius + 32

You can name your variables however you like — almost. A variable name must consist of upper-case letters, lower-case letters, digits, and underscores. Also, a variable name should begin with a letter.

Integers vs. Floating-Point Numbers

Until now, all of our numbers have had decimal points. But, as you'd expect, Python can also do arithmetic with whole numbers that don't have decimal points. Try some of these commands for comparison with the ones you used earlier.

7 + 3

7 - 3

7 * 3

7 / 3

7 ** 3

For the most part, these are pretty self-explanatory, but the division example should have given you pause. To understand what's going on, compare the results of these four commands:

7 / 3

7.0 / 3

7 / 3.0

7.0 / 3.0

In Python (and most other programming languages) there are two types of numbers: integers (whole numbers without decimal points) and floating-point numbers (which have decimal points). For example, the integer 7 and the floating-point number 7.0 are not exactly the same thing in Python. You can see this by comparing the results of 7 / 3 and 7.0 / 3. You can also see it by asking Python what the types the two numbers are:

type(7)

type(7.0)

Question F: When you do an arithmetic operation (+, -, *, /, **) on two numbers of different types, what is the type of the result? (Experiment, until you discover the simple rule.)

Question G: What exactly does the division operator / do on integers? What exactly does the modulus operator % do on integers? (Experiment. Hint: These two operators are closely related.)

Question H: Why does Python have two different kinds of numbers? (You shouldn't know the answer, but try to speculate.)

Warning: Python 3, which the Miller and Ranum text uses, has slightly different conventions for division; it uses / for floating-point division and // for integer division. Python 2, which we use, just uses / for both kinds of divison.

Strings

Thus far in the tutorial we have used two types of data — integers and floating-point numbers — that were both fundamentally numeric. But computers don't just manipulate numbers, do they? They also manipulate pictures, and sounds, and text, and so on. Let's learn a bit about text now.

A character is a letter, digit, punctuation mark, or any other symbol that is used in text. Spaces, tabs, carriage returns, and other forms of "empty space" in text also count as characters; they are called white space characters. A string, which is a sequence of (zero or more) characters. You usually enter a string in Python by enclosing it in single quotation marks or double quotation marks:

myName = 'Lucy'

myName

type(myName)

yourName = "Leroy Godzilla, Esq."

yourName

You can ask a string for its length like this:

len(myName)

len("Carleton")

Question I: What happens if you "add" two strings together, using the + operator?

The [] operator is used to extract particular characters from strings, as in the following example.

name = "Captain Haddock"

name[1]

name[4]

name[3]

Question J: How do you extract the first character from a string? What happens if you ask for a character after the last character? Suppose you have a string stored in a variable hisName. How can you use len() and [] together to extract the last character from hisName?

The [] operator can be used to extract not just single characters but also entire substrings, as follows.

name = "Shalikashvili"

name[3:7]

name[0:4]

Question K: When you ask for name[3:7], exactly which characters are you getting out of name? What about when you ask for name[0:4]? Be careful.

Golden Rule of Programming

Thus far we have learned about three data types: integers, floating-point numbers, and strings. A typical computer program uses these and many other data types, that we will learn about later. In fact, it is common for a programmer to invent new data types, as she is writing a program, just for that program. By the end of this term, you'll be inventing your own data types.

In Python, any variable can hold data of any type. If you want to store the integer 17 in the variable x, you may do so. If you want to store the string "Maria" in the variable x, you may do so. The flip side of this freedom is that you can sometimes confuse yourself: "Did I store an int or a string in that variable?" For a subtle example, consider this code:

y = 17

type(y)

type("y")

In this example, y is a variable that holds an integer, so y is of type int. On the other hand, "y" is a string, so "y" is of type str. You must keep things straight, between the variables that hold data, and the values that those variables hold. I propose the following

Golden Rule of Programming: In any piece of computer code that you write, you must know the type of every variable.

You see, variable are crucial elements of your program. They are tools, that you use in accomplishing your intended task. Not knowing whether a variable is an int or a string is like not knowing the difference between a hammer and a screwdriver. You can't possibly use a tool correctly, if you don't know what it does. The good news is that you can always ask the Python interpreter what the type of a variable is, using the type() command.