Python scripts

Until now we've been executing commands in the IPython Notebook. But usually, when you get code from other people, it doesn't come in IPython Notebooks, comes in Python files. These are just plain-text files of Python commands.

There's a file in the same directory as these notebooks called nobel.py. The ".py" extension hints that this is a Python script.

Open a command prompt, and use the navigation commands (dir and cd on Windows; ls, pwd, and cd on OS X and Linux) to navigate to your directory of workshop exercises. See "Practice navigating the computer from a command prompt" in your Setup notebook (Windows, Mac, Linux) for a refresher on those commands (or just ask for help!)

Once you are in the workshop directory, execute the contents of nobel.py by typing

python nobel.py

at a command prompt.

nobel.py introduces two new concepts: comments and multiline strings.

Open nobel.py in your text editor (see preparing 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:

  • 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 tomorrow. :)

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

True
In []:
 
False
In []:
 

Flow Control

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!"
In []:
 

That was our first multi-line piece of code, and those four spaces at the beginning of the second line are important; don't leave them out!

When you're typing at the regular, command-line Python prompt, instead of this IPython Notebook, the way you enter Python containing this kind of "block" is a little different. Go to the command prompt window and try this:

  • First, type the if 6 > 5: 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 print "Six is greater than five!".
  • 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 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."
In []:
 

more choices: if and else

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

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

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

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
In []:
 
1 < 2 and "x" in "abc"
In []:
 
"a" in "hello" or "e" in "hello"
In []:
 

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

In []:
 

Before you execute these next two examples, try to guess what they will print, then execute them and see if you are correct Make sure you understand why some of the lines are indented; feel free to ask a staff member to help explain. It is important to be comfortable with indenting for tomorrow.

In []:
temperature = 32
if temperature > 60 and temperature < 75:
    print "It's nice and cozy in here!"
else:
    print "Too extreme for me."
In []:
hour = 11
if hour < 7 or 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 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.

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"
In []:
 

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!"
In []:
 
In []:
 

Now go back to the cell above, change the first line to read

color = 'purple'

and execute it - notice how it doesn't print anything. Remember that '=' is for assignment (make this equal that!) and '==' is for comparison (does this equal that?).

[edit]Writing Functions

type(True)
In []:
 
False
In []:
 

type(False)

In []:
 

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

0 == 0
In []:
 
0 == 1
In []:
 

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"

In []:
 
"a" != "A"
In []:
 

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

In []:
 
2 >= 3
In []:
 
-1 < 0
In []:
 
.5 <= 1
In []:
 

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

"H" in "Hello"
In []:
 
"X" in "Hello"
In []:
 

Or check for a lack of containment with not in:

"a" not in "abcde"
In []:
 
"Perl" not in "Boston Python Workshop"

Flow Control

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!"
In []:
 

That was our first multi-line piece of code, and we need to pay attention to the indentation on the second line. Make sure to hit space four times before typing the second line; Python needs them to understand what we want it to do.

Try typing this same code at a regular command prompt (outside this notebook), too; you'll see that it works differently:

  • First, type the if 6 > 5: 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 print "Six is greater than five!".

  • Hit enter to end the line, and hit enter again to tell Python you are done with this code block.

All together, in the command-prompt window, 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 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."
In []:
 

more choices: if and else

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

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

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

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
In []:
 
1 < 2 and "x" in "abc"
In []:
 
"a" in "hello" or "e" in "hello"
In []:
 
1 <= 0 or "a" not in "abc"
In []:
 

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."
In []:
 
hour = 11
if hour < 7 or 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?"
In []:
 

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.

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"
In []:
 

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!"
In []:
 

Now go back to the cell above and change the first line to read

color = 'purple'

Execute the cell again. Notice that, this time, nothing is printed.

Remember that '=' is for assignment (make this equal that) and '==' is for comparison (does this equal that?).

Writing Functions

We talked a bit about functions when we introduced the type() function. 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 parenthesis.

For example:

length = len("Mississippi")
In []:
 

Executing this code assigns the length of the string "Mississippi" to the variable length. See what it did:

length
In []:
 

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 parameters 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):

Parameters should have names that usefully describe what they are used for in the function.

We've used the words "parameters" and "arguments" seemingly interchangeably to reference the input to functions. The distinction isn't really important right now, but if you're curious: in function signatures the input is called parameters, and when you are calling the function the input is called arguments.

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 parameters, 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 a variable to the output of a function, 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

Step 4: use the function

Once you define a function you can use it as many times as you want. Go ahead and type this function definition in and execute it.

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

Now you can use it as many times as you want, passing in whatever arguments you want.

result = add(1234, 5678)
print result
In []:
 
result = add(-1.5, .5)
print result
In []:
 

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.

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.

In []:
 
Back to top