Get in Touch with Python

This page is a slideshow!

  • Press ‘F10’ to start and stop
  • Press ‘space’ for current slide
  • Press ‘left’ and ‘right’ to go back and forth

Get in Touch with Python

Martin Bless

T3DD15 - TYPO3 Developer Days 2015 in Nuremberg

July 16-19, 2015

Logo mbless.de

Agenda

Python
I’m talking about Python. So I bring some diversity and take you abroad.
What is it?
Python is a high level general programming language. Stable, common, powerful, available for all platforms.
Ansible, Saltstack, Sphinx, ...
You only know Python from the context of big and complex applications? Then you are missing something.
A great beginner’s language
It is often used in teaching, for children, by casual programmers. Don’t miss it. You can easily start. And it can take you anywhere.
As an experienced programmer
you will benefit definitely as well. Python should be part of your toolbox.
I love programming in Python
And that’s mainly for two reasons: Fun and productivity!

For whom?

This talk is for those who want to start with Python or those hoping to see a new trick.
We are going to
  • learn a bit about the basics
  • see interactive feature of Python
  • do a small meaningful example
IPython Notebook
It’s interactive and runs in the browser. I’ll try to give an impression of this phantastic tool.
And then?

It’s enough, I would say!

But we have options.

  • PyCharm?
  • Sphinx documentation tools for TYPO3?
Thank You!

Participants! Sponsors !! Helping hands !!! Organizers

of this marvellous and amazing event!

Fun and Productivity

Welcome!

  • Hello friends, I love programming in Python.
  • Why would somebody talk about Python? What’s so amazing about Python?
  • For me the answer can be given in two words: fun and productivity.
  • By fun I mean: Work is still work, but I tend to LIKE it.
  • By productivity I mean: I’m ten times faster. I can do jobs that I otherwise couldn’t.
  • I’m very much astonished that Python is mentioned so rarely in our community.
  • I’m afraid you’re missing something. So that’s the reason why I’m proposing the topic here.

Overall Goal

What am I saying?

I’m not saying “Do everything in Python”

My message is:

“You’ll gain a lot if you are ready for the first steps with Python and if you don’t avoid it.”

Programmers

“In the good old days”
you were a Php programmer. Or a Pascal programmer. Or a Java programmer.
Nowadays

a programmer is more thought of as an allrounder. It’s expected that you understand at least several of these:

Bash, C, Cobol, Coffeescript, Css, Haml, Haskell, Html, Java, Javascript, Pascal, Perl, Php, Python, Typescript, Typoscript, Xml, and so on.

Popularity: A Ranking of Programming Languages

Just the other day I saw this ranking of programming languages (June 2015):

What’s most popular?

A Ranking of Programming Languages

Really another language? Oh must I?”

Doubts, hesitation, resistence ...

  • Why another language?
  • Don’t we have enough?
  • Haven’t we got enough problems already?
  • Install another tool? Why should I take the risk of screwing up my machine?

Is it worth the effort?

Yes!

Some Pro Arguments

Yes, it’s definitely worth the effort:

  • It’s not a matter of all or nothing
  • Python is easy to start with
  • You can start at any of many levels

And, NO

  • Installing Python will NOT screw up your machine

More Evangelism: What’s so great about Python?

Some personal notes

  • Documentation is great
  • Python is easy to learn and start with. Recommended for children!
  • Python code is very well readable. Something you write in pseudo code may very well be a valid Python program
  • Python code is very good to maintain
  • Python is very stable and backwards compatible
  • The core of the Python language by itself is very small. So the Python Language Reference shouldn’t be much of a problem. It describes syntax and language elements
  • The bigger task is to know the many and very good Library Functions of the The Python Standard Library. Keep that under your pillow!
  • Python is very interactive
  • There a many (easy) ways of debugging
  • Python has a nice and friendly community
  • Python is a preferred language for many scientists

More Evangelism

Two important things for me

Orthogonal and Regular
Python tries to do it “clean”, regular and “orthogonal”. For example, indexing and slicing have the same syntax for strings, lists and and list-like objects.
Libraries
Often I look into Python library function to understand complex issues. For example: What is a valid email format? Look into the Python “email” module for a lot of answers to that question.

Curious?

Hopefully you’re a bit curious by now

Find out if Python is installed already.

Get yourself a commandline and type: python --version

Hopefully you’ll see something like this:

RESOLVEME://files/001.png

If You Need To Install

Where to get Python from

Go to https://www.python.org/

Go to Downloads

RESOLVEME://files/003.png
Oops, wait:
What version should I choose?

Installation: Which version should I choose?

Python is in a transition phase

Which Python version should I choose?

Read: https://wiki.python.org/moin/Python2orPython3

Installation

Linux

Go to https://www.python.org/

Go to Downloads

Python is most probably installed. If not, use the packet manager of your system:

sudo apt-get install python

Installation

Mac

Go to https://www.python.org/

Go to Downloads

Pick an installer for Mac

I can’t say much about installing on a Mac.

Installation

Windows

Go to https://www.python.org/

Go to Downloads

Pick an installer for Windows:

Pick an installer for Windows
  • Run the installer. Will install to C:\Python27 by default. Simply go with it. Or install to D:\Python27.

Tip

  • Make sure, the paths C:\Python27\Scripts and - maybe - C:\Python27\Tools\Scripts are in the path
  • Add .py to the PATHEXT system variable if you want to be able to start script program.py by just typing program.

First Contact

Let’s try something

Python opens in dialog mode:

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> 1 + 1
2

>>> 'abc' + 'bcd'
'abcbcd'

>>> 3 * 5
15

>>> 'abc,' * 5
'abc,abc,abc,abc,abc,'

>>> ['a list'] * 3
['a list', 'a list', 'a list']

>>> exit()

First Contact: Interesting Aspects

Arbitrary long integers

>>> 2 ** 2
4
>>> 2 ** 22
4194304
>>> 2 ** 222
6739986666787659948666753771754907668409286105635143120275902562304L
>>> 2 ** 2222
7738385577878121270921913291177363957675805352044369150726746755451166643339
0225621118213792695021175190244951667322675647283977978393877115802136888227
6356848070794209358070102043443325352136545050000110534739684220468927252571
8545228637585111967234385629106091901532146690670721017896215421721054251511
3476510755470378003616234600251330288404641161878732714654916869730107991804
7772519772786759323456323386160178483395107203321577048282851869205647641463
3106982424173128829195665264713264067983600100179414810240875191907508744662
4702169205467746275821767903148850994094812935433097063308327801207416503803
3940046145844629478331113175706858291419937603163400966242304L

First Contact

How To Write Strings?

>>> 'string'
'string'

>>> "string"
'string'

>>> '''
... multiline string
... '''
'\nmultiline string\n'

>>> """multiline string"""
'multiline string'

>>> r'a raw string: C:\Python27'
'a raw string: C:\\Python27'

>>> u'unicode constants'
u'unicode constants'

First Contact

The Long Story about Strings and Literals

See the documentation:

Literals and String Literals in the Documentation

First Contact

Remember to do a tutorial

https://docs.python.org/2/tutorial/

Glorious Python - friendly and easy to learn

First Contact

Some Basics

Statements

  • we don’t have curly braces for blocks: no { }
  • we don’t have dollar signs for variables: no $
  • we don’t have semicolons at the end of statements: no ;

Indentation instead!

Best practise: four blanks:

if 1 and 'say hello':
    msg = "Hello World!"
    print(msg)

Some Basics

Consistent Index and Slice Notation for Sequences

Lists will look very much like Json.

Tuples are like lists, but immutable.

Consistent:

>>> '0123456789'[2:5]   # string
'234'

>>> (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)[2:5]  # tuple
(2, 3, 4)

>>> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9][2:5]  # list
[2, 3, 4]

First Contact

Small Set of Builtin Functions

There is a rather small set of builtin functions plus the builtin types with objects methods

A rather small set of builtin functions

First Contact

Import Library Functions

Most of the functionality is in library function and needs to be imported. These modules have different namespaces by default:

>>> import math

>>> math
<module 'math' (built-in)>

>>> math.sqrt
<built-in function sqrt>

>>> math.sqrt(36)
6.0

>>> from math import sqrt

>>> sqrt
<built-in function sqrt>
>>> sqrt(36)
6.0

>>> exit()

Basics

Functional Parameters

def myfunc(a, b, args*, kwargs**):
    pass

myfunc(a, b)
myfunc(a, b, c, .., x)
myfunc(a, b, host='localhost', db='test')
myfunc(a, b, c, ..., x, host='localhost', db='test', ..., name=value)

Basics

What is falsy?

This is well defined in chapter Truth Value Testing.

False is:

None, False, Zero number, an empty sequence, an empty mapping and instances of classes, that return 0 by bool() oder len().

This means: You most often just need to write if thing: then ...:

result = myfunc()
if result:
   "do something"

Basics

Btw

I often write:

if 1 and 'explanation':
   'do something'

Because I can turn off a whole codeblock easily:

if 0 and 'explanation':
   'do something'

Easy, well readable, because highlighting remains, the compiler optimises this away.

Most notable change in Python 3: “print”

One of the most notable changes is that print is function in Python 3 while it’s a statement with special syntax in Python 2.

Import “the future” to use the futureproof print function in Python 2 already:

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> print

>>> from __future__ import print_function
>>> print
<built-in function print>
>>> print("Hello world!")
Hello world!

About the nature of Python again

  • highly dynamic
  • dynamical typing
  • but NO automatic type conversion and “no magics”

You cannot use uninitialised variables:

>>> a
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'a' is not defined

Type conversion never happens implicitely:

>>> zero_string = '0'
>>> zero_string == 0
False

The Zen of Python

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren’t special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one– and preferably only one –obvious way to do it.
Although that way may not be obvious at first unless you’re Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it’s a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea – let’s do more of those!

Try Something Yourself

Go to Python.org and launch an interactive shell:

RESOLVEME://files/020.png

Try Something Yourself

Better: Try IPython from PythonAnywhere

RESOLVEME://files/021.png

What Can You Do With Python?

There’s a wide range of possible applications:

  • type some commands interactively
  • create shell commands
  • create complex shell suites
  • Objekt-Code einbinden
  • Create Gui-Application (sublime?)
  • integrate Python as scripting engines into other applications. Some games do this.
  • ...

Production Boosters / Examples

Beautiful Soup

Complete commandline program to list all links of a webpage:

#! /usr/bin/env python
# -*- coding: utf-8 -*-
import bs4, urllib2, sys

if len(sys.argv) != 2:
    print "usage: dumplinks.py <url>"
    exit(1)
url = sys.argv[1]
data = urllib2.urlopen(url).read()
soup = bs4.BeautifulSoup(data)
hits = soup.find_all('a')
for hit in hits:
    if hit.attrs.has_key('href'):
        print hit.attrs['href']

Writing Python Code

Source Code Encoding

#! /usr/bin/env python
# coding: ascii   <- assumed if nothing else specified
#! /usr/bin/env python
# coding: utf-8

Details

Writing Python Code

Generators are cool!

$ python
Python 2.7.6 (default, Jun 22 2015, 17:58:13)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> def gimme():
...     for item in ['Let me', 'show you', 'something']:
...         yield item
...     for item in [1, 2, 3]:
...         yield item
...
>>> for item in gimme():
...    print item
...
Let me
show you
something
1
2
3

IPython Interactive Computing

http://ipython.org

The IPython homepage

Editors, Tools, IDEs

If You Are on Windows: PythonWin!

PythonWin is a cool IDE on Windows!

Visit Python for Windows Extensions - pywin32

Editors, Tools, IDEs

Pycharm from Jetbrains!

IPython Interactive Computing

In a Terminal

http://ipython.org

IPython in a terminal window

Pycharm

Start a Terminal

Start a terminal window in Pycharm

Pycharm

Start Python in a Terminal Window in Pycharm

Start Python in a terminal window in Pycharm

Pycharm

Start a Python Console

Start a Python console in Pycharm

Pycharm

The Python Console in Pycharm

The Python console in Pycharm

Just to mention

Language Comparisons

Tags

Archives

Languages

Recent Posts

This Page