Python at ALA

Before the preconference

Preconference

What To Do Next

Self-paced introduction, part 1

Goals

  • Get to know the Python shell
  • Meet some useful Python data types
  • Practice using variables
  • Learn why tracebacks are useful

Steps

Welcome to the preconference!

This two-part tutorial covers several core programming concepts that we'll build upon during an interactive lecture starting at 10. There's a break in the middle, and exercises at the middle and end to help review the material. If you finish early, there's more advanced things to work on; if you aren't done at 10, we'll have time to catch up later. Please go at your own pace, and feel free to ask your instructors or classmates if you have any questions.

This is an interactive tutorial! As you go through this tutorial, any time you see something that looks like this:

a = "Hello"

you should type the expression at a Python prompt, hitting Return after every line and noting the output.

No copying and pasting! You'll learn the concepts better if you type them out yourself.

Strings

A string 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, world"

Try it now! Open your Python shell and type your own name in (don't forget the quotes):

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

Hm, we could have done that better...

"Alice " + "Walker"

There. FYI, we've been using double quotes around our strings, but you can use either double or single quotes:

"Alice"
'Alice'

Use whichever quotes make the most sense for you, but be consistent.

What if we try this?

'Alice's restaurant'

Hey now! The output from the previous example was really different and interesting; can you see where the problem was? Let's break down exactly what happened:

>>> 'Alice's restaurant'
File "", line 1
'Alice's restaurant'
         ^
SyntaxError: invalid syntax

This is giving us some useful feedback, a SyntaxError. When Python looks at that expression, it sees the string 'Alice' and then

s restaurant'

which it doesn't understand -- it's not 'valid' Python. Those letters don't mean anything to Python (outside of a string), and that trailing quote isn't balanced. So it raises a SyntaxError.

We can use double quotes to avoid this problem:

"Alice's restaurant"

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

What if you type in your name without the quotes?

Alice

This looks kind of like the last error we got, but instead of a SyntaxError, it's a NameError. Python thinks Alice is the name of a variable, but it's confused because we haven't defined any variables named Alice yet.

A lot of work gets done in Python using variables. You can stick all kinds of pieces of information inside of them, and store that information for later use.

name = "Alice"
print name

Giving a name to your piece of information, so that you can refer to it by that name, is called assignment. Above, we assigned the name name to the information "Alice", and after that we can use name wherever we want to use the string "Alice".

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

my_name
magic_word
numberOfCats

Projects develop naming conventions: maybe multi-word variable names use underscores (like magic_word), or "camel case" (like numberOfCats). 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 string and hit enter, the Python interpreter spits your string back out:

"Alice"

But if you assign your name (as a string) to a variable, nothing is printed:

name = "Alice"

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:

name = "Alice"
name
name = "Bob"
name

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

Note that the spacing doesn't matter:

name = "Alice"

and

name="Alice"

are both valid Python and mean the same thing. You should strive to be consistent with whatever spacing you like (or is required by a job or standard for an open source project), since it makes reading the code easier.

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

The return of strings

As you probably guessed earlier, you can print strings using print:

h = "Hello"
w = "World"
print h + w
my_string = "Alpha " + "Beta " + "Gamma " + "Delta"
print my_string
We haven't defined the term function yet, but we promise we will.

There's another useful function that works on strings called len(). len() returns the length of a string:

len("Alice")
len("")
len(my_string)
Note that we can do len(my_string) because you assigned a value to the variable my_string earlier. If you used a variable name you hadn't assigned a value to yet, like len(foo), what would happen?

What if we try this?

name + len(name)

Whoa, hey! That's new. Let's break it down.

>>> name + len(name)
Traceback (most recent call last):
File "", line 1, in 
TypeError: cannot concatenate 'str' and 'int' objects

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. Reading tracebacks can help us find where and why bugs happen.

Python gives us a helpful error message: "cannot concatenate 'str' and 'int' objects". But what does it mean by 'str' and 'int'? And what's this about a TypeError?

Types

A data type is the kind of thing Python thinks something is. So far we've seen two data types: strings and integers (the 'int' in that last traceback). Strings, as we've seen, are bunches of alphanumeric characters run together. Integers are just like in math class -- numbers like 1, 2, 0, or -1 that don't contain fractions.

If you have experience with other programming languages, you may find that Python is much more casual about type declarations than you're used to. The TAs will be happy to chat about that if you're curious.
Python cares what type a thing is because it affects what you can do with that thing. It makes sense to ask what the length of a string is, but it doesn't make sense to ask what the length of an integer is:

len(name)
len("1")
len(1)

That is, strings have a len() function, but integers don't.

We haven't really defined the term function yet. We'll talk about functions more in a bit, and write our own, but for now know these things:

  • Functions encapsulate some useful bit of work. We save that useful bit of work inside the function so we don't have to type it over and over again every time we want to use it. So, for example, some nice person decided that being able to determine the length of a string was useful, so he or she put the Python code that figures out an string's length into the function type, and now we all get to use it, instead of having to write it ourselves.
  • You provide input to a function and it produces output. The length function takes a string as an input, and returns an integer telling you how long the string is as output.
  • To use a function, write the name of the function followed by an open parenthesis, what the function takes as input (we call that input the arguments to the function), and then a close parenthesis.

One function you may find useful, now that you know about data types, is type(). It takes an object as an argument, and returns that object's type.

type(name)
type("1")
type(1)

Arithmetic

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.

You can add...

2 + 2
1.5 + 2.25

...subtract...

4 - 2
100 - 0.5
0 - 2

...multiply...

2 * 3

...and divide.

4 / 2
1 / 2
By the way, this isn't true any more in Python 3.0 — division is smart enough to switch to floats automatically. While Python 3.0 is available, most people are still using a 2.x version, so that's what we're doing. If you find yourself working on a Python 3.x project, though, you'll want to read up on the changes between versions.

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 type of number is called a float.

This means you have to be careful when manipulating fractions. If you were making some pie and needed to add 3/4 of a cup of flour and 1/4 of a cup of flour, you know in your 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".

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.

Back to Before the preconference