Community Data Science Workshops (Fall 2015)/Day 0 tutorial

Welcome to the Friday tutorial!

This tutorial covers several core programming concepts that we'll build upon during an interactive lecture tomorrow morning. It will take 1-2 hours to complete. There's a break in the middle, and exercises at the middle and end to help review the material.

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

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.

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.

Division
First, lets try some basic fractions:

Sure enough, Python says that the answer is 0.5 which is the same as 1/2.

Let's try the same thing:

Hey now! That last result is a little strange. When you divide a number in Python, even if the answer doesn't need a decimal place (like  which equals 2), you get an answer with a decimal point!

What's going on here is that in Python, division produces an what's called a  which essentially means a number with a decimal point.

When the Python interpreter goes to do the division, it knows that (unlike multiplication for example) division can lead to numbers that aren't whole numbers (like ) so it makes sure that the result will always include a decimal place just in case it's needed.

This shouldn't be important for this workshop but it might be worth knowing that older versions of Python (before version 3) would always round down and return integers instead of giving numbers with decimal places.

Types


There's a helpful function (more on what a function is in a second) called  that tells you what kind of thing -- what data type -- Python thinks something is. We can check for ourselves that Python considers '1' and '1.0' to be different data types: So now we've seen two data types: integers and floats.

By the way, what is a "function"? Here are the important ideas about functions:


 * A function encapsulates a useful bit of work and gives that work a name.
 * You provide input to a function and it produces output. For example, the  function takes data as an input, and produces what type of data the data is (e.g. an integer or a float) as output.
 * To use a function, write the name of the function, followed by an open parenthesis, then what the function needs as input (we call that input the arguments to the function), and then a close parenthesis.
 * Programmers have a lot of slang around functions. They'll say that functions "take" arguments, or that they "give" or "pass" arguments to a function. "call" and "invoke" are both synonyms for using a function.

In the example above, "type" was the name of the function. takes one argument; we first gave  an argument of 1 and then gave it an argument of 1.0.

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. 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: But if you assign 4 to a variable, nothing is printed: 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: Sometimes reassigning a variable is an accident and causes bugs in programs. 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: Note that the spacing doesn't matter: and are both valid Python and mean the same thing. and 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: Like with the math data types above, we can use the  function to check the type of strings:

String Concatenation
You can smoosh strings together (called "concatenation") using the '+' sign: How about concatenating different data types? Hey now! The output from the previous example was really different and interesting; let's break down exactly what happened:

>>> "Hello" + 1 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.

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:

"Hello" + "World"

works just fine.

However,

"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:

"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.

String length
There's another useful function that works on strings called. returns the length of a string as an integer:

Quotes
We've been using double quotes around our strings, but you can use either double or single quotes: 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:

'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:

"I'm a happy camper"

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

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.

2.

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.



Part 2: Printing
So far we've been learning at the interactive Python interpreter. When you are working at the interpreter, any work that you do gets printed to the screen. For example: will display "HelloWorld".

Another place that we will be writing Python code is in a file. When we run Python code from a file instead of interactively, we don't get work printed to the screen for free. We have to tell Python to print the information to the screen. The way we do this is with the print function. Here's how it works:

The string manipulate is exactly the same as before. The only difference is that you need to use print to print results to the screen:

becomes

We'll see more examples of the print function in the next section.

Python scripts


Until now we've been using the interactive Python interpreter. This is great for learning and experimenting, but you can't easily save or edit your work. For bigger projects, we'll write our Python code in a file. Let's get some practice with this!

 Download the file http://mako.cc/teaching/2015/cdsw-spring/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. Open a terminal prompt, and use the navigation commands ( and   on Windows, ,  , and   on OS X and Linux) to navigate to your Desktop directory. See navigating from a terminal for a refresher on those commands. Once you are in your Desktop directory, execute the contents of  by typing

python nobel.py

at the terminal prompt.

introduces two new concepts: comments and multiline strings.

Open  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?</li> How do you print a multi-line string so that whitespace is preserved?</li> </ol>

Making choices
We can use these expressions that evaluate to booleans to make decisions and conditionally execute code.



if statements
The simplest way to make a choice in Python is with the  keyword. Here's an example (don't try to type this one, just look at it for now):

That is our first multi-line piece of code, and the way to type it at a Python prompt is a little different. Let's break down how to do this (type this out step by step):

 First, type the

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.</li>

Press the spacebar 4 times to indent.</li> Type

</li> Press Enter to end the line. The prompt will still be a </li> Press Enter one more time to tell Python you are done with this code block. The code block will now execute.</li> </ol>

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  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
  lets you execute some code only if a condition is. What if you want to execute different code if a condition is ?

Use the   keyword, together with, to execute different code when the   condition isn't. Try this:

Like with, the code block under the   condition 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   for the overall expression to be. If two expressions are joined by an, as long as at least one is  , the overall expression is.

Try typing these out and see what you get:

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.

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 need to execute code conditional based on 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   condition or reaches the default   block.

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  :

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 diagram of :



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

Booleans
Please return to the interactive Python interpreter for the rest of the tutorial. And remember: type out the examples. You'll thank yourself tomorrow. :)



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. You can test if Python objects are equal or unequal. The result is a boolean: 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: ,,  , and   have the same meaning as in math class. The result of these tests is a boolean: You can check for containment with the  keyword, which also results in a boolean: Or check for a lack of containment with :

End of Part 2
Congratulations! You've learned about and practiced executing Python scripts, booleans, conditionals, and making choices with if, elif, and else. 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.