Learn » Introduction » Python for Coders.md

Python for Coders

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

Part 0


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


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:

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.

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.

-42 # Strictly this isn't a numeric literal it is a composition of the - operator and a literal


42e10 # Scientific notation for floats

1 / 2 #Gives us the right answer!

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


and a modulo operator:



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

"Hello, World!"

'<a href="http://google.com">Link</a>' # Single quoted strings are handy for including double quotes in a string

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

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

string = """This is a triple quoted string
set to a variable named string"""


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.

variable = 200.00

variable = "Hello, World!"

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

# run or copy and paste each line into your intrepreter to see the kinds of error Python can raise




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.


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

# Block 1
print('Hello, World!)

# Block 2
aswer = 3 * 8

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.

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.

"Hello, World!".upper()

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

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

"Hello," + " World!"

"MEOW " * 5


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

your_name = "Albert O'Connor"
string = "Hello, {0}!"

We can also used literal strings:

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.

False == False

True == True

True == False

True == False

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

1 > 2



"oo" in "Cool"

42 == 1

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

condition = True
if condition:
    print("Condition is True")
    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:

if condition:
    print("Condition is True")
    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.

condition = True
if condition:
    print("Condition is True")
    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!

if 1 = 3:


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.

[] # The empty list

["Milk", "Eggs", "Bacon"]


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.

[True, 0, "Awesome"]

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

your_name = "Albert O'Connor"
awesome_people = ["Eric Idle", your_name]

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


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

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

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


If you want the last element, use:


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



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.

() # empty tuple

(1,) # tuple with on element in it, the extra comma is needed to make it clear it isn't just brackets

('Awesome', 42) # tuples can also contain mixed types

1, 2, 3 # you don't actually need the brackets in some cases.

pair = ('+', 'plus')

sign, name = pair # tuples can be unpacked

print(sign + ': ' + name)

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

a = 1
b = 2
a, b = b, a # You can implement swap in one line!

Let's see what else tuples can do:


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


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

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

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

for person in awesome_people:

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

# Try range out by itself first.

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.

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

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.


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:

# Don't copy this, if some_condition were true you would get an infinite loop :)
while some_condition:

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



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.

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

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

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

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

Part 5


A function looks like this:

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 is Python's null object. There is only one created when the interrepter stared. None evaluates to False.


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

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.

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

def hello(name):
    return "Hello, {0}!".format(name)

def no_return(): # With out return None gets returned
    1 + 2

Flexible Arguments

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

def add_5_to(value=0):
    return value + 5




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.

def awesome(positional, default="default", flag=True):
    return positional, default, flag

awesome("positional string")

awesome('pos', 'def', 'flag') # positional arguments are applied in order

awesome('pos', flag='flag') # defalt keyword can be skipped, but only if flag is used explicitly

awesome('pos', flag='flag', default='def') # if you are using explicit keywords order doesn't matter

awesome('pos', default='def', 'flag') # This doesn't work though

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


Basic mathematical functions are supplied via the math module.

import math






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.