Python for Coders

This introduction to Python is designed for people who have had some experience writing code in other languages.

Part 0

Python

In case you are wondering we are using Python 3.4, Python 2.7 is very similar in terms of the code you write, but we won't worry about the differences in this session.

There are some 3rd party libraries which do no yet support Python 3 but that list is growing very small very

Shell

As you go through the material please type out the examples in your command line shell or using IDLE. You can try other things and if you have questions we will be happy to answer them.

To access the command line shell open a terminal and type python. You should be presented with a Python prompt which should look like this:

In [ ]:
Python 3.4.2 (...)
[GCC 4.2.1 (...)] on ...
Type "help", "copyright", "credits" or "license" for more information.
>>>

Part 1

The Basics

Let's start with some simple math. Python is an interpreted language which means you can execute expressions interactively at a prompt. Everything you see in a block can be evaluated at a your open Python prompt.

In [ ]:
1 + 1

Python supports integers across different bases, floating point and complex numbers. There is a builtin libraries for decimal numbers and an extensive 3rd party library for scientific numeric processing called NumPy. Here are a few Python numeric literals.

In [ ]:
-42 # Strictly this isn't a numeric literal it is a composition of the - operator and a literal
In [ ]:
3.1415
In [ ]:
42e10 # Scientific notation for floats
In [ ]:
1 / 2 #Gives us the right answer!

Most the math operators work the way you expect. There is also a power operator,

In [ ]:
2**4

and a modulo operator:

In [ ]:
5%3

Strings

Strings in Python are surround by either single quotes or double quotes.

In [ ]:
"Hello, World!"
In [ ]:
'<a href="http://google.com">Link</a>' # Single quoted strings are handy for including double quotes in a string
In [ ]:
"<a href=\"http://google.com\">Link</a>" # You can use \ to escape any quote, but that is pain

There are also special triple quoted strings which are useful when you want to perserve whitespace.

In [ ]:
"""Triple quote string allow new lines,
which is handy for template strings.
Python also uses them for source documentation.
I have seem people use them for comments but I
think that is a terrible practice. There are no
multiline comments but most editors and prepend
# to a group of selected lines."""

When we excute a single value in the interpreter, Python returns the representation of the internal value, if you want to see how tripple quoted when they are printed use the builtin print function.

In [ ]:
string = """This is a triple quoted string
set to a variable named string"""
print(string)

Variables

In Python variables are like buckets (dump trucks?). You can put anything you want in them. Just give them a name and you can use them in place of the literal value or objects.

In [ ]:
variable = 200.00
print(variable)
In [ ]:
variable = "Hello, World!"
print(variable)

The value a variable has only depends on what it was last assigned. The variable doesn't have a type, but the object it points to is strongly typed.

Errors in Python

When you write something Python doesn't understand the interpreter throws an error and tries to explain what went wrong, as best it can. Let's see some examples by running these code blocks

In [ ]:
# run or copy and paste each line into your intrepreter to see the kinds of error Python can raise
gibberish
In [ ]:
*adsflf_
In [ ]:
print('Hello'
In [ ]:
1v34
In [ ]:
2000 / 0

Python tries to tell you where it stopped understanding, but in the above examples, each program is only 1 line long.

It also tries to show you where on the line the problem happened with caret ("^").

Finally it tells you the type of thing that went wrong, (NameError, SyntaxError, ZeroDivisionError) and a bit more information like "name 'gibberish' is not defined" or "unexpected EOF while parsing". If you run into an error you don't understand please ask a tutor.

Exercises

Try to fix the two blocks of code so that they run successfully.

In [ ]:
# Block 1
print('Hello, World!)
In [ ]:
# Block 2
aswer = 3 * 8
print(answer)

Part 2

Variables, objects, and helpful interspection

Variables don't have types, that is why they are sometimes called names. Python uses duck typing. If something looks like duck or quacks like a duck, it is a duck. If Python tries to do something assuming a variable is a duck and finds out it isn't, it will generally throw an exception.

Some might say Python is weakly typed. It is true the variables aren't typed, but the objects a variable refers to are strongly typed. (Unlike C where you can take bytes and call them a string or an integer.)

Python is also very object oriented in the way most everything is an object, and though you can create your own classes, you don't have to.

String are objects which have methods, we can use dir and help to learn what they are.

In [ ]:
dir("Hello, World!") # list all methods on a string

Consider the names with the double underscores as private. There are still a lot of methods. Let's look at upper and lower which change the strings case.

In [ ]:
"Hello, World!".upper()

We can also use the builtin help function to access documentation about a function or object.

In [ ]:
help("Hello, World".upper)

dir and help are very helpful builtin functions that allow you to explore Python via the command line prompt. Change "upper" in the above example to other methods listed to see what they do.

You can type q to exist the help screen.

Strings also support some standard operations including + to concatenate and * to multiply

In [ ]:
"Hello," + " World!"
In [ ]:
"MEOW " * 5

Formatting

There are a few different ways to format strings with Python. In this session we will focus on the format method.

In [ ]:
your_name = "Albert O'Connor"
string = "Hello, {0}!"
print(string.format(your_name))

We can also used literal strings:

In [ ]:
print("Hello, {0}!".format("Albert O'Connor"))

{0} is the default positional placeholder for format, but that can be customized.

Indexed by Zero

For better or worse, (and practically it is better most of the time) everything in Python is index by 0.

Part 3

If Else

The literal values in Python for true and false are True and False.

In [ ]:
False == False
In [ ]:
True == True
In [ ]:
True == False
In [ ]:
True == False

Boolean operators include >, <, <=, >=, ==, not, and, or, in and is. String also have some helpful boolean methods.

In [ ]:
1 > 2
In [ ]:
"Cool".startswith("C")
In [ ]:
"Cool".endswith("C")
In [ ]:
"oo" in "Cool"
In [ ]:
42 == 1

In order to write an "if" statement we need code that spans multiple lines

In [ ]:
condition = True
if condition:
    print("Condition is True")
else:
    print("Condition is False")

Some things to notice. The if condition ends in a colon (":"). In Python blocks of code are indicated with a colon (":") and are grouped by white space. Notice the else also ends with a colon (":"), "else:".

About that white space, consider the following code:

In [ ]:
if condition:
    print("Condition is True")
else:
    print("Condition is False")
print("Condition is True or False, either way this is outputted")

Since the last print function isn't indented it gets run after the if block or the else block. You can play with this. Try indenting the last print function below and see what happens.

In [ ]:
condition = True
if condition:
    print("Condition is True")
else:
    print("Condition is False")
    print("Now it is indented when will this statement be excuted?")

It is handy to note that a single = in a condition like below is actually a syntax error!

In [ ]:
if 1 = 3:
    print("True!")

Whitespace

On the surface the use of whitespace in Python is kind of controversial.

The benefit is there are not endless debates how to format code, there is basically one right way, and it makes code more readable.

The downside is you can run into errors with whitespace.

A good editor configured to use spaces instead of tabs and and indent side of 4 should keep you safe.

Part 4

Tuples, Lists, Loops and Dicts

Lists are the first container type we will look at.

In [ ]:
[] # The empty list
In [ ]:
["Milk", "Eggs", "Bacon"]
In [ ]:
[1,2,3]

List literals are all about square brackets ("[ ]") and commas (","). You can create a list of literals by wrapping them in square brackets and separating them with commas. You can even mix different types of things into the same list; numbers, strings, booleans.

In [ ]:
[True, 0, "Awesome"]

We can put variables into a list and set a variable to a list.

In [ ]:
your_name = "Albert O'Connor"
awesome_people = ["Eric Idle", your_name]
print(awesome_people)

Like strings lists have methods which we can see with dir.

In [ ]:
dir([])

"append" lets you add an item to the end of a list.

In [ ]:
your_name = "Albert O'Connor"
awesome_people = ["Eric Idle", your_name]
awesome_people.append("John Cleese")
print(awesome_people)

We use square brackets ("[]") again with the variable of the list to access individual elements.

In [ ]:
awesome_people[0]

If you want the last element, use:

In [ ]:
awesome_people[-1]

Finally, if you need to know how many elements a list contains, use:

In [ ]:
len(awesome_people)

Tuples

Tuples are similar to lists, except they are immutable. You can create a new tuple out of existing tuples, but you can not append to an existing tuple. Strings are actually tuples of characters and are also immutable. You can make a new string out of an existing string, but you can't change a Python string in place. If you need a buffer there are builtin libraries that provide that.

In [ ]:
() # empty tuple
In [ ]:
(1,) # tuple with on element in it, the extra comma is needed to make it clear it isn't just brackets
In [ ]:
('Awesome', 42) # tuples can also contain mixed types
In [ ]:
1, 2, 3 # you don't actually need the brackets in some cases.
In [ ]:
pair = ('+', 'plus')
In [ ]:
sign, name = pair # tuples can be unpacked
In [ ]:
print(sign + ': ' + name)

Tuples are great for passing around data in group or returning more than one value from a function.

In [ ]:
a = 1
b = 2
a, b = b, a # You can implement swap in one line!
print(a)
print(b)

Let's see what else tuples can do:

In [ ]:
dir(())

Tuples don't have many methods mostly because they are a immuatable primitive type.

Loops

Python's main loop is foreach style that looks like this:

In [ ]:
list = [1, 2, 3]
for item in list:
    print(item) # Do any action per item in the list

item is the variable name for each item in the list. The list can be any iterable including a list or a tuple or the results of a database query.

Let's see it in action with our list

In [ ]:
your_name = "Albert O'Connor"
awesome_people = ["Eric Idle", your_name]
awesome_people.append("John Cleese")
In [ ]:
for person in awesome_people:
    print(person)

If you really want an index style for loop you can use the built in method range or the builtin in function enumerate.

In [ ]:
# Try range out by itself first.
range(0,10)
In [ ]:
for number in range(0,10):
    print("{0} squared is {1}".format(number, number*number))

We can explicitly index a list, but you generally don't need to.

In [ ]:
list = ['bacon', 'eggs', 'ham']
for i in range(3):
    print(list[i]) # you can do this but why would you want to?

If you want the index values assoicated with a list you can use the builtin enumerate

In [ ]:
list = ['bacon', 'eggs', 'ham']
for i, value in enumerate(list): # Sweet tuple unpacking
    print(str(i) + ": " + value) # Use enumerate if you want to operate based on the current index.

While

Though it isn't used too often there is a while loop. One nice property of foreach style loop is you can't create an infinite loop without trying really really hard. With a while loop it is as easy as any lanugage. This is the syntax:

In [ ]:
# Don't copy this, if some_condition were true you would get an infinite loop :)
while some_condition:
    print("Something")

Sometimes it is useful to have an infinite loop from which you escape when come condtion is satisfied.

In [ ]:
while(True):
    a=2
    if(a==2):
        break

Dictionaries

Dictionaries are another container like lists, but instead of being indexed by a number like 0 or 1 it is indexed by a key which can be almost anything. The name comes from being able to use it to represent a dictionary.

List literals use square brackets ("[]") but dictionaries use braces ("{}").

Let's see what the literal dictionary looks like.

In [ ]:
{"Python": "An awesome programming language",
 "Monty Python": "A british comedy troupe"}

In a dictionary the key comes first followed by a colon (":") then the value then a comma (",") then another key and so on. This is one situation where a colon doesn't start a block.

We can assign a dictionary to a variable and we can index it by keys to get the values (definitions) out.

In [ ]:
our_dictionary = {
   "Python": "An awesome programming language",
   "Monty Python": "A british comedy troupe"
}
our_dictionary["Python"]

We can loop over the keys in a dictionary to list all of our definitions...

In [ ]:
for key in our_dictionary:
    print('The Key is "{0}" and the value is  "{1}"'.format(key, our_dictionary[key]))

Part 5

Functions

A function looks like this:

In [ ]:
def add(a, b):
    return a + b

def is the keyword to define a function. add in the above example is the name. All functions require a parameter list surrounded by an open bracket "(" and close bracket ")" even if there are no parameters. return is also a keyword which is required return a value. If it isn't provided None is returned. Function bodies are block like if statements and for loops.

None

None is Python's null object. There is only one created when the interrepter stared. None evaluates to False.

In [ ]:
None
bool(None)

That is a lot of information about function lets try out some of it.

In [ ]:
def the_answer(): # Even when there are no parameters you still need the brackets
    return 42
the_answer # Outputs information about the function object, see everything is an object

Now let's try calling our function.

In [ ]:
def the_answer(): # Even when there are no parameters you still need the brackets
    return 42
the_answer() # The brackets are need to call the function
In [ ]:
def hello(name):
    return "Hello, {0}!".format(name)
hello("Awesome")
In [ ]:
def no_return(): # With out return None gets returned
    1 + 2
no_return()

Flexible Arguments

There are two types of arguments, positional and keyword. So far we have only seen positional arguments. Keyword agruments have default values.

In [ ]:
def add_5_to(value=0):
    return value + 5
In [ ]:
print(add_5_to())
In [ ]:
print(add_5_to(15))
In [ ]:
print(add_5_to(value=20))

Keyword arguments can be called explicitly by keyword or implicitly by position, which can be a bit confusing. In the function definition positional arguments have to come before keyword arguments. When processing argument the same rule applies. Positional arguments are pocessed until the first keyword argurment is reached.

In [ ]:
def awesome(positional, default="default", flag=True):
    return positional, default, flag
In [ ]:
awesome("positional string")
In [ ]:
awesome('pos', 'def', 'flag') # positional arguments are applied in order
In [ ]:
awesome('pos', flag='flag') # defalt keyword can be skipped, but only if flag is used explicitly
In [ ]:
awesome('pos', flag='flag', default='def') # if you are using explicit keywords order doesn't matter
In [ ]:
awesome('pos', default='def', 'flag') # This doesn't work though
In [ ]:
awesome(default='def') # This also doesn't work, the positional argument must be provided

Not all argments need to be named. It is possible to capture extra positional and keyword arguments using a special and a bit odd bit of syntax with "*" and "**".

Math

Basic mathematical functions are supplied via the math module.

In [ ]:
import math
In [ ]:
print(math.cos(0))
In [ ]:
print(math.log(27))
In [ ]:
print(math.log(27,3))

Try

In [ ]:
help(math.log)

to see why the log function can take a variable number of arguments.

Next Steps

Go through the Setup Python instructions if you haven't already to make sure python is installed, pip is installed, and you have a good editor.

If there is still time, help out some one else who is a bit further behind.

You can also do some addition reading. Here are some choice selections form the Python Tutorial, but you can also just start from the beginning.