Python logo

Why Python?

Eine kurze Einführung

Gerald Senarclens de Grancy, gerald@senarclens.eu

Outline

  1. Features
  2. Tools
  3. Basic Syntax
  4. Sample Applications
  5. Interfaces

Features

Is Python
good for me?

What about jobs?

Tools

Basic I/O

Writing text to a console

spam.py  
print("Spam and eggs")
  

Launching the program

$ python3 spam.py

Basic I/O

Asking for input

dialog.py  
#!/usr/bin/env python3
food = input("What do you want to eat? - ")
print("We don't have %s, we only have spam and eggs." % food)
  

Make the program executable and launch it as shell script

$ chmod u+x dialog.py
$ ./dialog.py

Basic I/O

read-file.py  
#!/usr/bin/env python3
with open("data/history.txt", 'r') as hist_file:
    content = hist_file.read()
print(content)
  

Flow Control

coin.py  
#!/usr/bin/env python3
from random import random
if random() >= 0.5:
    print("head")
else:
    print("tail")
  

High-level Types

sort-file.py  
#!/usr/bin/env python3
with open("data/history.txt", 'r') as hist_file:
    lines = hist_file.readlines()
lines.sort()
print(lines)
  

Loops

for.py  
#!/usr/bin/env python3
with open("data/history.txt") as hist_file:
    lines = hist_file.readlines()
lines.sort()
for line in lines:
    print(line.strip())
  

Loops

while.py  
#!/usr/bin/env python3
from random import random
win_count = 0
while (random() >= 0.5):  # head
    win_count += 1
print("head won %d times" % win_count)
  

Functions

sum.py  
#!/usr/bin/env python3


def sum(*numbers):
    """Return the sum of the arguments."""
    total = 0
    for num in numbers:
        total += num
    return total

print(sum(3, 5, 7.9))
  

Objects and Classes

random_student.py  
#!/usr/bin/env python3
from random import choice


class StudentPicker(object):
    def __init__(self, students):
        with open(students, 'r') as student_file:
            students = student_file.readlines()
        students = filter(None, students)
        students = [s.strip().split('\t') for s in students]
        self._students = ["%s %s, %s" % (s[0], s[1], s[2]) for s in students]
        self._initial_students = list(self._students)

    def pick_student(self):
        """
        Return a student and remove that student from the list.
        """
        try:
            student = choice(self._students)
            self._students.remove(student)
            return student
        except IndexError:
            return "no more students available; use 'reset' or 'quit'"

    def reset(self):
        self._students = list(self._initial_students)
  

Advantages
over a spreadsheet?

What can
Python do for me?

Sample Applications

matrix.py  
#!/usr/bin/env python3
import numpy as np
A = np.array((0, 1, 0, 2, 1, 3, 1, 0, 1)).reshape((3, 3))
B = np.ones(9).reshape((3, 3))
print(np.dot(A, B))
  

Sample Applications

pdf.py  
#!/usr/bin/env python3
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.mlab as mlab

mu, sigma = 0.0, 1.0

fig = plt.figure()
ax = fig.add_subplot(111)
x = np.arange(-4, 4.1, 0.1)
y = mlab.normpdf(x, mu, sigma)
l = ax.plot(x, y, 'r-', linewidth=1)

ax.set_title(r'probability density function: $\mu=%f,\ \sigma=%f$'.format(
    mu, sigma))
ax.set_xlim(-4, 4)
ax.set_ylim(0, 0.5)
# plt.show()
plt.savefig("data/density.svg")  # also supports pdf, png, ...
  

data/density.svg

Interfaces

shell.py  
#!/usr/bin/env python3
import cmd
import sys
from random_student import StudentPicker


class StudentPickerShell(cmd.Cmd):
    def __init__(self, students):
        cmd.Cmd.__init__(self)                # initialize the base class
        self.prompt = "ST> "
        self._picker = StudentPicker(students)

    def do_quit(self, arg):
        sys.exit()

    def do_pick(self, arg):
        """Print a random student.

        The same student won't be selected again unless `reset` is called.
        """
        print(self._picker.pick_student())

    def do_reset(self):
        self._picker.reset()

shell = StudentPickerShell("data/pioneers.tsv")
shell.cmdloop()
  

Interfaces

qt.py  
#!/usr/bin/env python3
import sys
from PyQt4 import QtGui, QtCore
from random_student import StudentPicker


class StudentPickerWindow(QtGui.QWidget):
    def __init__(self, students, parent=None):
        self._picker = StudentPicker(students)
        QtGui.QWidget.__init__(self, parent)
        self.setWindowTitle('Student Picker')

        pick = QtGui.QPushButton("Pick")
        reset = QtGui.QPushButton("Reset")
        textfield = QtGui.QLineEdit()
        self._textfield = textfield

        grid = QtGui.QGridLayout()
        grid.setSpacing(10)
        grid.addWidget(textfield, 1, 0)
        grid.addWidget(pick, 1, 1)
        grid.addWidget(reset, 1, 2)

        self.connect(pick, QtCore.SIGNAL('clicked()'), self.do_pick)
        self.connect(reset, QtCore.SIGNAL('clicked()'), self.do_reset)
        self.setLayout(grid)
        self.resize(500, 50)

    def do_pick(self):
        self._textfield.setText(self._picker.pick_student())

    def do_reset(self):
        self._picker.reset()
        self._textfield.setText("")

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    window = StudentPickerWindow("data/pioneers.tsv")
    window.show()
    sys.exit(app.exec_())
  

Interfaces

This demo is not available on public hosts.

Why Python?

Python 3 Video Tutorials
and Slides

Questions
and feedback...

Further Reading

Guido van Rossum, Barry Warsaw PEP 8 -- Style Guide for Python Code http://www.python.org/dev/peps/pep-0008/
Mark Pilgrim Dive Into Python 3 (2nd edition) Apress (October 23, 2009)
Python Software Foundation Python Documentation http://docs.python.org/