Python 2 hour intro

This material is intended for a 1.5 - 2 hour interactive lecture.

Lecture handout

Math


Math in Python looks a lot like math you type into a calculator. A Python prompt makes a great calculator if you need to crunch some numbers and don't have a good calculator handy.

Addition
2 + 2 1.5 + 2.25

Subtraction
4 - 2 100 - .5 0 - 2

Multiplication
2 * 3

Division
4 / 2 1 / 2

Hey now! That last result is probably not what you expected. What's going on here is that integer divison produces an integer. You need a number that knows about the decimal point to get a decimal out of division:

1.0 / 2

This means you have to be careful when manipulating fractions. If you were doing some baking and needed to add 3/4 of a cup of flour and 1/4 of a cup of flour, we know in our heads that 3/4 + 1/4 = 1 cup. But try that at the Python prompt:

3/4 + 1/4

What do you need to do to get the right answer? Use data types that understand decimals for each of the divisions:

3.0/4 + 1.0/4 3.0/4.0 + 1.0/4.0

The two previous expressions produce the same result. You only need to make one of the numbers in each fraction have a decimal. When the Python interpreter goes to do the division, it notices that one of the numbers in the fraction cares about decimals and says "that means I have to make the other number care about decimals too".

Command history
Stop here and try hitting the Up arrow on your keyboard a few times. The Python interpreter saves a history of what you've entered, so you can arrow up to old commands and hit Return to re-run them!

Variables


A lot of work gets done in Python using variables. Variables are a lot like the variables in math class, except that in Python variables can be of any data type, not just numbers.

type(4) x = 4 x type(x) 2 * x

Giving a name to something, so that you can refer to it by that name, is called assignment. Above, we assigned the name 'x' to 4, and after that we can use  wherever we want to use the number 4.

Variables can't have spaces or other special characters, and they need to start with a letter. Here are some valid variable names:

Projects develop naming conventions: maybe multi-word variable names use underscores (like ), or "camel case" (like  ). The most important thing is to be consistent within a project, because it makes the code more readable.

Output


Notice how if you type a 4 and hit enter, the Python interpreter spits a 4 back out:

4

But if you assign 4 to a variable, nothing is printed:

x = 4

You can think of it as that something needs to get the output. Without an assignment, the winner is the screen. With assignment, the output goes to the variable.

You can reassign variables if you want:

x = 4 x x = 5 x

Sometimes reassigning a variable is an accident and causes bugs in programs.

x = 3 y = 4 x * y x * x 2 * x - 1 * y

Order of operations works pretty much like how you learned in school. If you're unsure of an ordering, you can add parentheses like on a calculator:

(2 * x) - (1 * y)

Note that the spacing doesn't matter:

x = 4

and

x=4

are both valid Python and mean the same thing.

(2 * x) - (1 * y)

and

(2*x)-(1*y)

are also both valid and mean the same thing. You should strive to be consistent with whatever spacing you like or a job requires, since it makes reading the code easier.

You aren't cheating and skipping typing these exercises out, are you? Good! :)

Strings


So far we've seen two data types: integers and floats. Another useful data type is a string, which is just what Python calls a bunch of characters (like numbers, letters, whitespace, and punctuation) put together. Strings are indicated by being surrounded by quotes:

"Hello" "Python, I'm your #1 fan!"

Like with the math data types above, we can use the  function to check the type of strings:

type("Hello") type(1) type("1")

String Concatenation
You can smoosh strings together (called "concatenation") using the '+' sign:

"Hello" + "World"

name = "Jessica" print "Hello " + name

Printing
You can print strings using :

h = "Hello" w = "World" print h + w

my_string = "Alpha " + "Beta " + "Gamma " + "Delta" print my_string

How about printing different data types together?

print "Hello" + 1

Hey now! The output from the previous example was really different and interesting; let's break down exactly what happened:

Python is giving us a traceback. A traceback is details on what was happening when Python encountered an Exception or Error -- something it doesn't know how to handle.

There are many kinds of Python errors, with descriptive names to help us humans understand what went wrong. In this case we are getting a : we tried to do some operation on a data type that isn't supported for that data type.

Python gives us a helpful error message as part of the TypeError:

We saw above the we can concatenate strings:

print "Hello" + "World"

works just fine.

However,

print "Hello" + 1

produces a. We are telling Python to concatenate a string and an integer, and that's not something Python understands how to do.

We can convert an integer into a string ourselves, using the  function:

print "Hello" + str(1)

Like the  function from before, the   function takes 1 argument. In the above example it took the integer 1. takes a Python object as input and produces a string version of that input as output.

Quotes
We've been using double quotes around our strings, but you can use either double or single quotes:

print 'Hello' print "Hello"

Like with spacing above, use whichever quotes make the most sense for you, but be consistent.

You do have to be careful about using quotes inside of strings:

print 'I'm a happy camper'

This gives us another traceback, for a new kind of error, a. When Python looks at that expression, it sees the string 'I' and then

which it doesn't understand -- it's not 'valid' Python. Those letters aren't variables (we haven't assigned them to anything), and that trailing quote isn't balanced. So it raises a.

We can use double quotes to avoid this problem:

print "I'm a happy camper"

or we can escape the quote with a backslash:

print 'I\'m a happy camper' print 'Ada Lovelace is often called the world\'s first programmer.' print "Computer scientist Grace Hopper popularized the term \"debugging\"."

One fun thing about strings in Python is that you can multiply them:

print "A" * 40 print "ABC" * 12

Part 1 Practice


Read the following expressions, but don't execute them. Guess what the output will be. After you've made a guess, copy and paste the expressions at a Python prompt and check your guess.

1. total = 3 - 1/2 + .5 print total

2. a = "quick" b = "brown" c = "fox jumps over the lazy dog" print "The " + a * 3 + " " +  b * 3 + " " + c

End of Part 1
Congratulations! You've learned about and practiced math, strings, variables, data types, exceptions, tracebacks, and executing Python from the Python prompt.

Take a break, stretch, meet some neighbors, and ask the staff if you have any questions about this material.

Python scripts


Until now we've been executing commands at the Python prompt. This is great for math, short bits of code, and testing. For longer ideas, it's easier to store the code in a file.

 Download the file http://mit.edu/jesstess/www/BostonPythonWorkshop6/nobel.py by right-clicking on it and saying to save it as a ".py" file to your Desktop. The ".py" extension hints that this is a Python script. Run the script by double-clicking on it. What happens?

introduces two new concepts: comments and multiline strings.

Open  in a text editor. Read through the file in your text editor carefully and check your understanding of both the comments and the code. 

Study the script until you can answer these questions:  How do you comment code in Python? How do you print just a newline? How do you print a multi-line string so that whitespace is preserved?</li> </ol>

Let's get back to some interactive examples.

Booleans


So far, the code we've written has been unconditional: no choice is getting made, and the code is always run. Python has another data type called a boolean that is helpful for writing code that makes decisions. There are two booleans:  and.

True

type(True)

False

type(False)

You can test if Python objects are equal or unequal. The result is a boolean:

0 == 0

0 == 1

Use  to test for equality. Recall that  is used for assignment.

This is an important idea and can be a source of bugs until you get used to it: = is assignment, == is comparison.

Use  to test for inequality:

"a" != "a"

"a" != "A"

,,  , and   have the same meaning as in math class. The result of these tests is a boolean:

1 > 0

2 >= 3

-1 < 0

.5 <= 1

You can check for containment with the  keyword, which also results in a boolean:

"H" in "Hello"

"X" in "Hello"

Or check for a lack of containment with :

"a" not in "abcde"

"Perl" not in "Boston Python Workshop"

if statements
We can use these expressions that evaluate to booleans to make decisions and conditionally execute code:

if 6 > 5: print "Six is greater than five!"

That was our first multi-line piece of code, and the way to enter it at a Python prompt is a little different. First, type the  part, and hit enter. The next line will have  as a prompt, instead of the usual. This is Python telling us that we are in the middle of a code block, and so long as we indent our code it should be a part of this code block.

Type 4 spaces, and then type. Hit enter to end the line, and hit enter again to tell Python you are done with this code block. All together, it will look like this:

>>> if 6 > 5: ...     print "Six is greater than five!" ... Six is greater than five!

So what is going on here? When Python encounters the  keyword, it evaluates the expression following the keyword and before the colon. If that expression is True, Python executes the code in the indented code block under the  line. If that expression is False, Python skips over the code block.

In this case, because 6 really is greater than 5, Python executes the code block under the if statement, and we see "Six is greater than five!" printed to the screen. Guess what will happen with these other expressions, then type them out and see if your guess was correct:

if 0 > 2: print "Zero is greater than two!"

if "banana" in "bananarama": print "I miss the 80s."

more choices: and
You can use the  keyword to execute code only when the   expression isn't True:

sister_age = 15 brother_age = 12 if sister_age > brother_age: print "sister is older" else: print "brother is older"

Like with, the code block under the   statement must be indented so Python knows that it is a part of the   block.

compound conditionals: and
You can check multiple expressions together using the  and   keywords. If two expressions are joined by an, they both have to be True for the overall expression to be True. If two expressions are joined by an, as long as at least one is True, the overall expression is True.

Try typing these out and see what you get:

1 > 0 and 1 < 2

1 < 2 and "x" in "abc"

"a" in "hello" or "e" in "hello"

1 <= 0 or "a" not in "abc"

Guess what will happen when you enter these next two examples, and then type them out and see if you are correct. If you have trouble with the indenting, call over a staff member and practice together. It is important to be comfortable with indenting for tomorrow.

temperature = 32 if temperature > 60 and temperature < 75: print "It's nice and cozy in here!" else: print "Too extreme for me."

hour = 11 if hour 23: print "Go away!" print "I'm sleeping!" else: print "Welcome to the cheese shop!" print "Can I interest you in some choice gouda?"

You can have as many lines of code as you want in  and   blocks; just make sure to indent them so Python knows they are a part of the block.

even more choices:
If you have more than two cases, you can use the  keyword to check more cases. You can have as many  cases as you want; Python will go down the code checking each   until it finds a True condition or reaches the default   block.

sister_age = 15 brother_age = 12 if sister_age > brother_age: print "sister is older" elif sister_age == brother_age: print "sister and brother are the same age" else: print "brother is older"

You don't have to have an  block, if you don't need it. That just means there isn't default code to execute when none of the  or   conditions are True:

color = "orange" if color == "green" or color == "red": print "Christmas color!" elif color == "black" or color == "orange": print "Halloween color!" elif color == "pink": print "Valentine's Day color!"

If color had been "purple", that code wouldn't have printed anything.

Remember that '=' is for assignment and '==' is for comparison.

Lists

 * Use lists to store data where order matters.
 * Lists are indexed starting with 0.

List initialization
>>> my_list = [] >>> my_list [] >>> your_list = ["a", "b", "c", 1, 2, 3] >>> your_list ['a', 'b', 'c', 1, 2, 3]

Access and adding elements to a list
>>> len(my_list) 0 >>> my_list[0] Traceback (most recent call last): File " ", line 1, in IndexError: list index out of range >>> my_list.append("Alice") >>> my_list ['Alice'] >>> len(my_list) 1 >>> my_list[0] 'Alice' >>> my_list.insert(0, "Amy") >>> my_list ['Amy', 'Alice']

>>> my_list = ['Amy', 'Alice'] >>> 'Amy' in my_list True >>> 'Bob' in my_list False

Changing elements in a list
>>> your_list = [] >>> your_list.append("apples") >>> your_list[0] 'apples' >>> your_list[0] = "bananas" >>> your_list ['bananas']

Slicing lists
>>> her_list = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'] >>> her_list[0] 'a' >>> her_list[0:3] ['a', 'b', 'c'] >>> her_list[:3] ['a', 'b', 'c'] >>> her_list[-1] 'h' >>> her_list[5:] ['f', 'g', 'h'] >>> her_list[:] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']

Strings are a lot like lists
>>> my_string = "Hello World" >>> my_string[0] 'H' >>> my_string[:5] 'Hello' >>> my_string[6:] 'World' >>> my_string = my_string[:6] + "Jessica" >>> my_string 'Hello Jessica'


 * One big way in which strings are different from lists is that lists are mutable (you can change them), and strings are immutable (you can't change them). To "change" a string you have to make a copy:

>>> h = "Hello" >>> h[0] = "J" Traceback (most recent call last): File " ", line 1, in TypeError: 'str' object does not support item assignment >>> h = "J" + h[1:] >>> h 'Jello'

Loops
Use a  loop to do something to every element in a list.

>>> names = ["Jessica", "Adam", "Liz"] >>> for name in names: ...    print name ... Jessica Adam Liz

>>> names = ["Jessica", "Adam", "Liz"] >>> for name in names: ...    print "Hello " + name ... Hello Jessica Hello Adam Hello Liz

End of Part 2
Congratulations! You've learned about and practiced writing and executing Python scripts, making choices with booleans and conditionals, and using lists and iteration. This is a huge, huge accomplishment!



Take a break, stretch, meet some neighbors, and ask the staff if you have any questions about this material.