Python at ALA

Before the preconference

Preconference

What To Do Next

Self-paced introduction, part 2

Goals

  • Run python scripts from a file
  • Meet the Boolean data type
  • Use flow control (if/elif/else)
  • Write your first functions

Steps

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.

python nobel.py

at a command prompt.

  • Open nobel.py in your text editor (see the instructions onsetting up your text editor for a refresher on starting the 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:

A comment is a note that makes your code easier to understand. The computer ignores comments, but when you write code that might be particularly confusing to other programmers -- including yourself in the future -- you should add a comment to facilitate collaboration and improvements.
  • 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?

Let's get back to some interactive examples. Keep typing them out! You'll thank yourself later. :)

Booleans

That's right: booleans aren't just for librarians with mad ninja OPAC skills. Programmers use them too. Constantly.

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: True and False.

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. (Before you hit enter, what do you think the result of each of these tests will be?)

"a" != "a"
"a" != "A"

<, <=, >, and >= have the same meanings you're familiar with from school. The result of these tests is a boolean:

1 > 0
2 >= 3
-1 < 0
.5 <= 1

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

"H" in "Hello"
"h" in "Hello"
"X" in "Hello"

Or check for a lack of containment with not in:

Programmer joke here. Perl is a programming language that was hugely popular in the 1990s, and there's still a ton of perl code being written, including in libraryland. It's very different stylistically from Python, though. As many people who've programmed in more than one language have strong favorites (and unfavorites), some Pythonistas might be known to diss Perl. We here take no position on the merits of different languages. Except that Python is awesome.
"a" not in "abcde"
"Perl" not in "ALA Python Preconference"

Flow control

if statements

We can use these expressions that evaluate to booleans to make decisions and conditionally execute code. (As always, decide what you think will happen before running the 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 if 6 > 5: part, and press 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.

Enter 4 spaces, and then type print "Six is greater than five!" Press Enter to end the line, and press 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!

What is going on here? When Python encounters the if 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 if 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: if and else

You can use the else keyword to execute code when the if expression isn't True. Try this:

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

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

compound conditionals: and and or

As you know again from your mad ninja OPAC skills, you can check multiple expressions together using the and and or keywords. If two expressions are joined by an and, they both have to be True for the overall expression to be True. If two expressions are joined by an or, 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 the lecture and afternoon projects.

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 < 7 or hour > 23:
    print "Go away!"
    print "I'm sleeping!"
else:
    print "Welcome to the yarn shop!"
    print "Can I interest you in some nice merino?"

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

even more choices: elif

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

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

You don't have to have an else block, if you don't need it. That just means there isn't default code to execute when none of the if or elif 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.

In summary: the structure of if/elif/else

Here's a summary of if/elif/else:

Do you understand the difference between elif and else? When do you indent? When do you use a colon? If you're not sure, talk about it with a neighbor or staff member.

Writing functions

We talked a bit about functions when we introduced the len() and type() functions. Let's review what we know about functions:

  • They do some useful bit of work.
  • They let us re-use code without having to type it out each time.
  • They take input and possibly produce output (we say they return a value). You can assign a variable to this output.
  • You call a function by using its name followed by its arguments in parentheses.

For example:

length = len("Mississippi")

Executing this code assigns the length of the string "Mississippi" to the variable length.

We can write our own functions to encapsulate bits of useful work so we can reuse them. Here's how you do it:

Step 1: Write a function signature

A function signature tells you how the function will be called. It starts with the keyword def, which tells Python that you are defining a function. Then comes a space, the name of your function, an open parenthesis, the comma-separated input arguments for your function, a close parenthesis, and a colon. Here's what a function signature looks like for a function that takes no arguments:

def myFunction():

Here's what a function signature looks like for a function that takes one argument called string:

def myFunction(string):

And one for a function that takes two arguments:

def myFunction(myList, myInteger):

Arguments should have names that usefully describe what they are used for in the function. Functions should (unlike myFunction()) have descriptive names, too.

Step 2: do useful work inside the function

Underneath the function signature you do your useful work. Everything inside the function is indented, just like with if/else blocks, so Python knows that it is a part of the function.

You can use the variables passed into the function as arguments, just like you can use variables once you define them outside of functions.

def add(x, y):
    result = x + y

Step 3: return something

If you want to be able to assign the output of a function to a variable so you can use it later, the function has to return that output using the return keyword.

def add(x, y):
    result = x + y
    return result

or, even shorter:

def add(x, y):
    return x + y

You can return any Python object: numbers, strings, booleans ... even other functions!

Once you execute a return, you are done with the function -- you don't get to do any more work. That means if you have a function like this...

def absoluteValue(number):
    if number < 0:
        return number * -1
    return number

...if number is less than 0, you return number * -1 and never even get to the last line of the function. However, if number is greater than or equal to 0, the if expression evaluates to False, so we skip the code in the if block and return number.

We could have written the above function like this if we wanted. It's the same logic, just more typing:

def absoluteValue(number):
    if number < 0:
        return number * -1
    else:
        return number

There's usually more than one right way to write a program (that is, it runs and does the thing it's supposed to do). Sometimes one of them may be better (e.g. it runs faster or is easier to read and modify), but some differences are purely a matter of personal style. As we write more complicated programs later today, you might enjoy comparing notes with your neighbors and seeing the different ways you've attacked the same problem.

Step 4: use the function

Once you define a function you can use it as many times as you want:

def add(x, y):
    return x + y

result = add(1234, 5678)
print result
result = add(-1.5, .5)
print result

Functions don't have to return anything, if you don't want them to. They usually return something because we usually want to be able to assign variables to their output.

What is the difference between print and return?

Think for a moment about the differences between print and return:

  • print prints output to the screen so your eyes can see it.
  • return is used to hand off a value from inside a function to a variable outside the function.

For example:

def add(x, y):
    print x + y

will print x + y to the screen so your eyes can see it.

def add(x, y):
    return x + y

will hand off x + y from inside the function to outside the function. This allows you to do something like:

result = add(5, 6)
print result

Does that make sense? If not, talk about it with a neighbor or staff member.

End of part 2

Congratulations! You've learned about and practiced executing Python scripts, booleans, conditionals, and if/else blocks, and you've written your own Python functions. 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.

Next Step:

Back to Self-paced introduction, part 1