Why learn more languages?

  • It's fun (if you pick a fun language)
  • It will make you a better programmer (if it's not similar to something you already know)
  • Different languages are good at different things, knowing a few lets you pick the right one for the right job
  • As you get older, you will be less and less willing to learn a new language
  • It prevents you from getting stuck to a language
  • How many languages you know correlates with salary
I'll begin with a shockingly controversial statement: programming languages vary in power.
Paul Graham
in Beating the Averages

Why Python?

  • It's the language I know the best because I loved it since day one (if I do this well enough, I hope you will too)
  • Easy to learn
  • Fast to write
  • Great for prototyping
  • Many common tools are in the standard library
  • Rich (but not overwhelming) set of syntax features
  • Great documentation (nothing like the Java documentation)
  • It makes programming fun (compared to Java)
  • Large community with a package for almost everything
    Some of my favorites:
    • Web frameworks such as Django and Flask
    • requests.py, "HTTP for humans" (replacement for Pythons built-in urllib2))
    • NumPy for numerical computing (think Matlab)
    • matplotlib (matlab style plotting)
    • pygame, simple library for developing 2D graphics applications

Why not Python?

  • You somehow don't like whitespace indentation
  • It's not fast to run
  • You can't write mobile apps with it
    • Actually you can, but I wouldn't recommend it for serious projects
  • It's not statically typed
  • The Global Interpreter Lock

Where is it used?

  • Google
  • CERN
  • NASA
  • YouTube
  • Dropbox
  • Reddit
  • Duolingo
  • Hipmunk
  • BitTorrent (first implementation)
  • And many more...

How did it come to be?

Creator: Guido van Rossum

  • Created ABC , a programming language designed for learning
  • Created Python, designed to be a scripting language with syntax inspired by ABC
  • Worked at Google
  • Now works at Dropbox
More on Wikipedia
Lets write it in Java, it is as good a programming a language as any.
Well actually it isn't, but...
Prof. Thore Husfeldt
Lecture in "Algorithms, datastructures and complexity" (EDAF05)

Hello World!

print("Hello world!")
Hello world!

Just for comparison, here is the equivalent Java:

public class Program {
    public static void main(String[] args) {
        System.out.println("Hello World!");


word = "Narwhal"                   # They are awesome
part_of_word = word[0:2]           # This is called slicing, can be shortened `word[:2]`
print(part_of_word*10 + " Batman!")
NaNaNaNaNaNaNaNaNaNa Batman!


How do they work?

our_list = ["rainbow"]
our_list.append("rainbow")        # What does it mean?
if len(our_list) != 2:
    raise Exception("list was of unexpected length")
if our_list[0] == our_list[1] == "rainbow":
    print("Double rainbow all across the slide!")
Double rainbow all across the slide!


What happens if you turn a string into a list?

our_string = "The cake is a lie"
our_list = list(our_string)
['T', 'h', 'e', ' ', 'c', 'a', 'k', 'e', ' ', 'i', 's', ' ', 'a', ' ', 'l', 'i', 'e']

What this does is essentially looping though the string, one character at a time, and then putting each element in the list. Rarely very useful.

What is useful is splitting the string whenever a certain character appears

our_string = "The cake is a lie"
our_list = our_string.split(" ")
['The', 'cake', 'is', 'a', 'lie']



primes = [17, 3, 5, 13, 7, 11]
primes = [17, 3, 5, 13, 7, 11]
[3, 5, 7, 11, 13, 17]

An example on how to implement a comparator can be found here.


Also known as hashmaps

our_dictionary = {"some key": "some value"}
print(our_dictionary["some key"])             # You can fetch using the bracket syntax

our_dictionary["some key"] = "another value"  # It's easy to create (in this case write over) an entry
print(our_dictionary.pop("some key"))         # Removes and returns the value with the given key
assert len(our_dictionary) == 0               # Our dictionary is now empty

our_dictionary[1] = "one"                     # We can even have keys of different types in the same dict
our_dictionary["one"] = 1
print(our_dictionary)                         # A dict like this might be useful for... something.

s = 1
for i in range(101):
    s = our_dictionary[s]
some value
another value
{1: 'one', 'one': 1}


Declaration and usage

def multiply_by_2(n):
    """This is a so called docstring"""
    return n*2

Running it

our_list = []
for i in range(10):

A shorter way to write it is:

print([multiply_by_2(i) for i in range(10)])   # This is called a list comprehension
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]


A fibonacci example

def fibonacci(n):
    """Returns the n'th Fibonacci number using iteration"""
    i = 1
    j = 0
    for _ in range(n):
        tmp = i
        i += j
        j = tmp
    return i
def fibonacci(n):
    """Returns the n'th Fibonacci number using recursion"""
    if n < 2:
        return 1
        return fibonacci(n-1) + fibonacci(n-2)


First-class citizens

def add_one(i):
    return i+1

def f(g, argument):
    """Runs and returns g(argument)"""
    return g(argument)

i = 0
while i < 10;
  i = f(add_one, 1)
print("Done! Ran " + str(i) + " times!")



def logging_decorator(f):
    def g():
        print("Will now execute function")
        print("Function executed")
    return g

def f():
    print("Running function")
f = logging_decorator(f)   # Passes a function into another function which
                           # returns a new function which is assigned to f

The last part can be written with the fancy decorator syntax as:

def f():
    print("Running function")

They are exactly equivalent


class Animal:
    def __init__(self, name):
        self.name = name

    def walk_to(self, animal):
        print(self.name + " walks to " + animal.name)

class Dog(Animal):
    def __init__(self, name, loud=False):
        Animal.__init__(self, name)   # Run the Animal constructor on self before continuing
        self.loud = loud

    def bark(self):
        if self.loud:

toto = Dog("Toto")   # Toto is a fictional dog in L. Frank Baum's Oz series of children's books

fluffy = Dog("Fluffy", loud=True)    # A giant three-headed dog from Harry Potter

Batteries included

Need something? Python probably has it

import webbrowser

If you run this, the exact same thing will happen as if you click this.

The Python standard library includes excellent (and easy to use) modules for:

  • Date and time
  • Functional programming
  • Data compression and archiving
  • Concurrent execution
  • Turtle graphics (yes, really)

...and much more.

...not enough? A lot more is available from the Python Package Index.

xkcd Python comic

Try this at home

import antigravity

Things I've skipped

  • Basic datatypes such as tuples and sets
  • Decorators
  • Modules and packages
  • List, set and dict-comprehensions
  • Generators
  • Lambdas
  • Properties (Pythonic getters & setters)
  • Metaclasses
  • Unit testing (the 'unittest' package)

These are less important than the other things I've gone through, but they can be very useful so if you want to do even more with less Python you should check them out.

Want more?