Boston Python workshop 2/Friday tutorial

Type each of the following expressions at the Python prompt (no copying and pasting! You'll learn the concepts better if you type them out yourself). After you type an expression, hit Return. This causes the Python interpreter to evaluate the expression.

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

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:

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.

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:

type(1) type(1.0)

So now we've seen two data types: integers and floats.

I used the term 'function' without explaining what it is -- we'll talk about functions a lot more on Saturday, and write our own, but for now know two things:


 * To use a function, write the name of the function followed by an open parenthesis, possibly some data (we call that data the 'arguments' to the function), and then a close parenthesis.

So in this case 'type' is the name of the function, and it takes one argument; in the example we first give  an argument of 1 and then give it an argument of 1.0.


 * Functions are a lot like functions in math class. You provide input to a function, and it possibly produces output. The 'type' function takes data as an input, and produce what type of data the data is (e.g. an integer or a float) as output.

Command history
Stop here and try hitting the Up arrow on your keyboard. 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 'syntax'.

(2 * x) - (1 * y)

and

(2*x)-(1*y)

are also valid syntax. You should strive to be consistent with whatever syntax you like or a job requires, since it makes reading the code easier.

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:

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

String Concatenation
print "Hello" + "World" print "Hello", "World"

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

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

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

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

Printing different data types together

print "Hello", 1 print "Hello" + 1

The output from the previous example is really different and interesting; let's break down exactly what is happening:

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 'TypeError': 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 TypeError. We are telling Python to concatenate a string and an integer, and that's not something Python understands how to do.

In the similar expression

print "Hello", 1

Python is actually turning the integer 1 into a string before printing, and that's why the concatenation works: Python does know how to concatenate two strings.

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 example the integer 1. takes in 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 '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 h = "Happy" b = "Birthday" print (h + b) * 10

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.

Open your text editor and create a new file called test.py. The .py extension helps us and other programs recognize that this file will contain Python code.

Copy the following lines into your file:



Save the file.

Execute the contents of the file by typing at a terminal prompt:

python nobel.py.

this file introduces two new concepts: comments and multiline strings. Read through the file careful and check your understanding of both the comments and the code.

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 = 1.5 - 1/2 + ((-2.0/2) - (1.0/2)) print total type(total)

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

3. print 2.0 * 123, "2.0" * 123 print 2.0 * 123 + str(2.0) * 123

4. a = "| (_|  --  --   --   -- | --  --  --   --   ||\n" b = "|_\_|_/___|__|__|__|___|__|___|__|___________________________||\n" c = "|________________________________|__|___|___|____|_____||\n" d = "___|)________________________________________________________\n" e = "|_/(|,\____/_|___/_|____/_|______|___________________________||\n" f = "|___/____________________________|___________________________||\n" g = "|  |     |   |    |    |  |                           ||\n" h = "|__\___|.________________________|___\_|___\_|___\_|___|_____||\n" i = "|__/|_______/|____/|_____/|______|___________________________||\n" j = "|_____/__________________________|____\|____\|____\|_________||\n" k = "|____/___________________________|___________________________||\n" l = "|__/___\_._______________________|__|__|__|__|__|__|___|_____||\n"

print d + f + i + e + b + g + a + c + l + h + j + k