Lab 1: Programming Essentials, Variables, and Conditionals

0. Environment setup

Everyone should have a computer with Anaconda/Spyder installed on it. Open Spyder now. The screen you see should be divided into 3 parts:

  • The left side holds a text editor. Most of your programming will be done here.
  • The top right corder holds some analysis tools that will be useful later on.
  • The bottom right holds the Console. Python is an interpreted language, meaning we can write code at the same time we're running code. This is primarily useful for trying out new instructions or testing very simple code.

Note that although we'll be working within Spyder, python does not require it. If you have a Mac, you can open a python console by typing "python" into a terminal window.

0.1 Setup Tasks

You should see line numbers along the left side of your text editor. If not, go to Tools -> Preferences -> Editor -> Show Line Numbers. Check the box.

Using the tab key in the editor should create two space characters. If it does something else (4 spaces or a tab character, most likely), go to Tools -> Preferences -> Editor -> Advanced Settings -> Set Indentation Characters and change the value shown to 2 space characters.

1.0-1.5,1.8-1.9 Programming Essentials

1.0 Philosophy of Programming

Don't be afraid to experiment. The process of programming is perhaps best described as building something wrong in a variety of ways until you finally run out of ways to be wrong. Our goal in this class is to be wrong in as many different ways as we can manage, so that when you see something strange this fall you'll be able to say "I've seen that before!"

Ongoing Task:

  • If you aren't sure whether something is right, run it! See what it does.
  • If you still aren't sure, ask your neighbor to take a look. We're in this together.

1.1 Philosophy of Python

Like most programming languages, python code consists of a series of statements, one per line.

Python focuses on elegance and simplicity. It uses "white space" to organize code, where most languages would use braces or parentheses. Indentation matters. Here is an example of a very simple python program:

def oneToTen():
  print "Start"
  for i in range(10):
    print i+1,
    print "OK!"
oneToTen()

Here is a different python program:

def oneToTen():
  print "Start"
  for i in range(10):
    print i+1,
print "OK!"
oneToTen()

The only change I made was to un-indent the 5th line. Try each program by copying it into your editor, saving, and then running the program (either by using the green arrow button at the top of the screen or by pressing F5).

While indentation is very important, spaces elsewhere in your code are often ignored. i+1 and i + 1 are both acceptable, for example.

1.2 Trying out the Console

Let's move over to the Console and try out some expressions and statements. If you give an expression to the Console without telling it to do anything with it, the Console will print the value of the expression back to you.

Tasks:

  • Identify two types of numbers and a way python handles them differently. (Hint: Try some math expressions.)
  • Python has boolean (True/False) values. Identify the keywords for these values. How does a logical expression interact with a mathematical one?
  • Python has strings for values that are words or sentences. You will need to wrap each string with either single (') or double (") quotation marks. Otherwise python will think the first word you enter is actually a statement and will try to do what it says. Can you mix strings with math or logic expressions?

1.3 A First Python Program

If you have an interpreter (as we do), you can try out python code live, but most programming will be done by creating a file or files to hold pre-written code, which is then compiled and run. Python hides the compile step. When you run one of your files it is actually first compiled. We won't worry about that.

When we run a program, the statement on the first line is executed, followed by the statement on the next line, continuing until we run out of lines. Some statements change the order in which other statements are executed.

Tasks:

  • Try placing some of the expressions from your console experimentation in a program and running it. Notice that nothing is displayed yet.
  • Use the print statement to display your expressions. It looks like print "Hello World"
  • You can print multiple expressions on the same line by inserting commas: print "Hello", "World". Find a way to have two print statements on different lines of your program display on the same line of your console.

1.4 Getting User Input

Now that we have our basic output statement, it will be useful to have a basic input statement as well.

raw_input()

Notice the parentheses at the end. Those mean that raw_input is a function. Most of what we will write for this course will be functions. You may already be familiar with the notions of procedures or subroutines--a function is the same thing. For us, raw_input() is a black box that takes user input from the keyboard and returns it to the program. The parentheses hold any inputs to the function. In this case, raw_input can take either 0 or 1 inputs. The optional input is a prompt to show the user while waiting.

Tasks:

  • Try out raw_input(), with and without prompts, in your console.
  • Write a program that echoes user input several times.
  • What type does raw_input() return?

To answer the last question, you can use a second function, type(). It takes one input, (which can be anything), and returns the type of that thing. You may also be able to figure out raw_input() from context or by using the Object Inspector in the top right panel of the UI.

1.5 Commenting Your Code

Any text after the '#' symbol in a python program is a comment. Code placed after a '#' is not executed. Comments should be used to document what your programs do, for easier reading and debugging. Each program should include a comment at the very top explaining the purpose of the program. Comments to explain particular lines of code can be place either immediately above the line or to its right.

Ongoing Tasks:

  • Add comments to your code!
  • When you write a program, try writing comments describing exactly what the program does before you write the program.

1.6-1.7 Variables

1.6 Variables

In order to make a function like raw_input() really useful, we need a way to store information. Just like other programming languages, python uses variables. A variable in python is mutable, meaning you can change its value after it is created. Python also allows you to change variable types. In fact, you are never required to state the type of a variable in python. When you run code that needs a variable to be of a particular type, python will attempt to convert it into that type at run-time. Warning: Python is notoriously bad at this conversion. It's actually better at it than any other language I have used, but you will still want to handle any needed conversion yourself.

Syntax:
x = 17
myLunch="An Apple"
myLunch = "A Sandwich"
myLunch=False

The variable's name goes on the left, followed by the assignment operator '=', followed by whatever you want to store in the variable.

Task:

  • Create a very simple calculator program that asks the user for two numbers and prints out their sum, difference, product, and quotient.

To complete the task above, you may find the int() function useful. It takes one input (a string) and returns the corresponding integer. So x = int('7') creates a variable called x holding an integer value of 7.

Task:

  • Modify your calculator so that it also reports the length of the hypotenuse of a right triangle with the two given integers as legs.

In order to calculate the length of the hypotenuse, you will need the pythagorean theorem c^2 = a^2 + b^2. Python does not allow you to place an expression on the left side of an assignment statement, so we will need to take the square root of the right-hand side. The square root is not a built-in operator like '+' or '*', but there is a math module that includes a function for calculating the square root.

import math

print "The quare root of 9 is", math.sqrt(9)

1.7 Naming Conventions for Variables

Every language has standard ways to name variables. In python, the rules are very loose. A variable name cannot start with a number, but any alphabetic character is fine, as is the underscore '_'. A variable name should be descriptive (reading the variable name should give me a good idea of what it's for) while also being concise. Remember that you can always use comments to help explain what you are doing. I tend to use variableNamesLikeThis when I want to use multi-word names. The actual python standard is variable_names_like_this. Either is fine, provided you are consistent. Avoid starting variable names with underscores; there are some environment variables that are defined before your code begins running. (What value does __name__ hold? Note: There are two underscores on either side.)

Ongoing Task:

  • Pick descriptive names for your variables!

1.8 A Very Brief Introduction to Lists

L = [1,2,3,4]

The statement above creates a variable L whose value is a list of the numbers 1-4. In python, you can make lists out of anything (including other lists). Different elements in a list may have different types, even different sizes. To make a list, wrap some other things in square brackets, separating each element of the list with a comma. There are a variety of tricks for making lists more easily. Here's one: zeros = [0]*3 creates [0, 0, 0].

Frequently, you will want to access a particular element in a list. You can do this by placing square brackets and the index of your desired element after the list. So L[1] should have the value 2. All lists in python are zero-indexed, so mylist[0] accesses the first element in mylist.

1.9 Breaking Python

You have probably already seen some error messages. Whenever something goes wrong, python will spit out an error report saying roughly what went wrong and where. Take a few minutes and see how many different types of errors you can generate.

Task:

  • Create a new file called breakingPylisthon.py. When you find a new error type, add a comment to the file with the code you used to generate the error and a brief description of what the error means. For example:
    # ZeroDivisionError: Tried to divide by zero.
    # 5/0
Other error types you may find include
  • NameError
  • TypeError
  • SyntaxError
  • IndexError

1.10-1.11 Conditionals

1.10 Comparison

Up to this point, you have used math operators (*, +, etc), logical operators (and, or, not), and the assignment operator (=). Here are some useful comparison operators: ==, >, <, >=, !=, in. This is by no means a complete list. '!=' is python's not-equal operator. The 'in' operator takes some object as its first operand, and a list as its second operand. It tests whether the first operand is "in" the given list.

>>> 5 in [1,2,3,4]
False
>>> 3 in [1,2,3,4]
True

Task:

  • What is python's comparison rule for strings?
  • What about for lists?
  • What happens if we test the equality of objects with different types, such as 5, 5.0, and "5"?

1.11 Conditionals

At the start of today's lab, I mentioned that indentation matters. This is where we start to use it. An if statement in python has two parts, a condition and a body. Structurally, it looks like this:

if CONDITION:
  BODY

Notice that the body section is indented. Any indented code immediately following an if statement will be run if and only if the condition evaluates to True. There is no end-if marker in python. You simply do not indent the following code that comes after the if body.

x = int(raw_input("Enter a single-digit number: ")
if x >= 10:
  print x, "is too big"
y = int(raw_input("Enter another number: ")

The two other conditional statements are elif and else. elif, short for "else if", is structured exactly like if. Its body executes if the if statement before it (plus any elif statements in between) all had their conditions evaluate to false, and its own condition evaluates to true. else does not have a condition. It simply executes its body if none of the preceding if or elif statements executed theirs.

Task:

  • Construct a program which asks the user to think of a person in the room. The program should then ask questions to narrow down the possible people the user could be thinking of. When the program has narrowed down the possibilities to a single person, it should print out You are thinking of and the person's name. When your game is ready, have the person seated next to you play it.