SlideShare a Scribd company logo
 




Utan stödhjul och 
   motorsåg
Vad är Python?




● Ett dynamiskt typat språk
● Designat för enkelhet och tydlighet
It is the only language co-designed for the
  most advanced and the complete novice.

             [David Goodger]
Plattformar



● Python = CPython
● Jython (JVM)

● IronPython (.NET, Mono)

● PyPy (Python in Python)
Användningsområden

admin, byggen och driftsättning

webbapps, webbtjänster/+klienter

verktygsklister & GUIn (vanligt på linux)

dataskyffling/-konvertering/-analys
Scripta verktyg


Grafik (Gimp, Inkscape, Blender, ...), 
LibreOffice, ...

Spel (Battlefield 2+, Civ IV, EVE-Online, ...)

DVCS: Mercurial, Bazaar...
Användare
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
Python utan-stodhjul-motorsag
.. Sun, Microsoft, Canonical, O'Reilly, Lucasfilm, 
Nasa, Sourceforge, ...
Årets språk enligt Tiobe


      Bästa tillväxten

           2007
           2010
Moget


Utveckling & drift: doctest, nosetests, distribute,
pip, virtualenv, ...

Paket för allt: data, sysadmin, webb, grafik,
matematik, parallellism...
Design
Vad är viktigt?



Läsbarhet!

Namngivning!
Programming The 
Way Guido Indented It
def to_roman(num):

    assert num > 0 and num < 4000

    result = []

    for d, r in NUMERALS:

        while num >= d:
            result.append(r)
            num -= d

    return ''.join(result)
"In soviet russia, braces scope you"


from __future__ import braces


...
SyntaxError: not a chance
Effektivt


tokens = ['a', 'b', 'c', 'B', 'dd', 'C', 'DD']

similar = {}

for token in tokens:
    key = token.lower()
    similar.setdefault(key, []).append(token)
Lättanvänt


for key, tokens in similar.items():

    if len(tokens) > 1:
        print("Similar (like %s):" % key)

        for token in tokens:
            print(token)
Generella behållare



● list() == []
● dict() == {}

● tuple() == ()

● set()
Python är interaktivt



$ python
Python 2.7.1 [...]
Type "help", "copyright", "credits" or "license" for
more information.
>>>
>>>   def add(a, b=1):
...       return a + b
...
>>>   add(1)
2
>>>   add(1, 2)
3
>>>   add(2, b=3)
5
>>>   add(b=3, a=2)
5
Mekanik
"""
Usage:

      >>> usr = Path('/usr')
      >>> bin = usr.segment('local').segment('bin')
      >>> str(bin)
      '/usr/local/bin'
"""

class Path:
    def __init__(self, base):
        self.base = base

      def segment(self, name):
          return Path(self.base + '/' + name)

      def __str__(self):
          return self.base
__protokoll__




Betyder används under ytan
Tydliga sammanhang



Börjar bukta när en dålig idé växer

●   state är explicit (self)
"""
Usage:

      >>> usr = Path('/usr')
      >>> bin = usr.segment('local').segment('bin')
      >>> str(bin)
      '/usr/local/bin'
"""

class Path(str):
    def segment(self, name):
        return Path(self + '/' + name)
Allt är objekt



● primitiver
● collections

● funktioner, klasser

● moduler, paket
Ingen motorsåg..
"""Usage:
                      Closures
      >>> mkpasswd = salter("@secret#salt")
      >>> mkpasswd("qwerty")
      '4ef6056fb6f424f2e848705fd5e40602'
"""

from hashlib import md5

def salter(salt):

      def salted_encrypt(value):
          return md5(salt + value).hexdigest()

      return salted_encrypt


 
Funktionell @dekoration


from django.views.decorators.cache import cache_page

@cache_page(15 * 60)
def slashdot_index(request):
    result = resource_intensive_operation(request)
    return view_for(result)
Reduce boilerplate..


try:
    f = open('file1.txt')
    for line in f:
        print(line)

finally:
    f.close()
.. with contexts



with open('file1.txt') as f:

    for line in f:
        print(line)
Generators


def public_files(dirname):
    for fname in os.listdir(dirname):
        if not fname.startswith('.'):
            yield fname

for fname in public_files('.'):
    open(fname)
Projicera data
Maskinellt procedurell


publicfiles = []

for fname in os.listdir('.'):

    if not fname.startswith('.'):
        publicfiles.append(open(fname))
Tillståndslös spaghetti



publicfiles = map(lambda fname: open(fname),
                  filter(lambda fname:
                            not fname.startswith('.'),
                         os.listdir('.')))
List comprehensions



publicfiles = [open(fname)
               for fname in os.listdir('.')
               if not fname.startswith('.')]
Generator comprehensions



publicfiles = (open(fname)
               for fname in os.listdir('.')
               if not fname.startswith('.'))
process(open(fname) for fname in os.listdir('.')
        if not fname.startswith('.'))
Myter
"My way or the highway"
Sanningar
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.
Python is humanism
Python ger dig




● Enkel men kraftfull kod
● Fokus på lösningen
Tack!
Image Tributes (CC)
Python, Google, YouTube, Spotify logos & Amazon Python Day Poster photo courtesy of 
respective organization.

Night train

"And so thy path shall be a track of light"

"Documents Reveal Django Pony, Caught In Tail Of Lies." / _why

"inch by inch"

"Wasserglas"

"I am Jack, hear me lumber!"

"Bend me, Shape me, any way you want me."

More Related Content

PDF
The Browser Environment - A Systems Programmer's Perspective
PDF
Poker, packets, pipes and Python
PDF
"PostgreSQL and Python" Lightning Talk @EuroPython2014
ODP
Programming Under Linux In Python
PDF
Pry at the Ruby Drink-up of Sophia, February 2012
KEY
Clojure入門
PDF
Happy Go Programming
PDF
Palestra sobre Collections com Python
The Browser Environment - A Systems Programmer's Perspective
Poker, packets, pipes and Python
"PostgreSQL and Python" Lightning Talk @EuroPython2014
Programming Under Linux In Python
Pry at the Ruby Drink-up of Sophia, February 2012
Clojure入門
Happy Go Programming
Palestra sobre Collections com Python

What's hot (20)

PDF
Frege is a Haskell for the JVM
PDF
Descobrindo a linguagem Perl
PDF
Chrome拡張開発者のためのFirefox拡張開発
PDF
Intro to Python
PDF
Implementing virtual machines in go & c 2018 redux
ODP
NUMOSS 4th Week - Commandline Tutorial
PDF
Programming Lisp Clojure - 2장 : 클로저 둘러보기
PDF
(Fun clojure)
PDF
Communities - Perl edition (RioJS)
PDF
Alta performance com Python
PPTX
Python basic
PDF
PubNative Tracker
KEY
An introduction to Ruby
PDF
Introduction of ES2015
PDF
D-Talk: What's awesome about Ruby 2.x and Rails 4
PDF
Introduction to jRuby
PDF
Fertile Ground: The Roots of Clojure
ODP
PDF
Lập trình Python cơ bản
PDF
Happy Go Programming Part 1
Frege is a Haskell for the JVM
Descobrindo a linguagem Perl
Chrome拡張開発者のためのFirefox拡張開発
Intro to Python
Implementing virtual machines in go & c 2018 redux
NUMOSS 4th Week - Commandline Tutorial
Programming Lisp Clojure - 2장 : 클로저 둘러보기
(Fun clojure)
Communities - Perl edition (RioJS)
Alta performance com Python
Python basic
PubNative Tracker
An introduction to Ruby
Introduction of ES2015
D-Talk: What's awesome about Ruby 2.x and Rails 4
Introduction to jRuby
Fertile Ground: The Roots of Clojure
Lập trình Python cơ bản
Happy Go Programming Part 1
Ad

Similar to Python utan-stodhjul-motorsag (20)

PDF
Intro to Python
PDF
Python for Penetration testers
PPTX
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
PPTX
Overview of Python - Bsides Detroit 2012
PPTX
2015 bioinformatics python_strings_wim_vancriekinge
PPTX
Python programming
PPTX
Python Workshop - Learn Python the Hard Way
PPTX
P2 2017 python_strings
PPTX
IoT-Week1-Day1-Lab.pptx
PPTX
Python lec5
PDF
PyCon 2013 : Scripting to PyPi to GitHub and More
PDF
Python: an introduction for PHP webdevelopers
PPTX
file handling in python using exception statement
PPT
Sample Lab Orientation in Python orientation
PDF
Python for PHP developers
PDF
Snakes for Camels
PDF
Python Cookbook_ Nho Vĩnh Share.pdf
PDF
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
PPTX
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)
Intro to Python
Python for Penetration testers
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
Overview of Python - Bsides Detroit 2012
2015 bioinformatics python_strings_wim_vancriekinge
Python programming
Python Workshop - Learn Python the Hard Way
P2 2017 python_strings
IoT-Week1-Day1-Lab.pptx
Python lec5
PyCon 2013 : Scripting to PyPi to GitHub and More
Python: an introduction for PHP webdevelopers
file handling in python using exception statement
Sample Lab Orientation in Python orientation
Python for PHP developers
Snakes for Camels
Python Cookbook_ Nho Vĩnh Share.pdf
File handling3 (1).pdf uhgipughserigrfiogrehpiuhnfi;reuge
Learning python with flask (PyLadies Malaysia 2017 Workshop #1)
Ad

More from niklal (6)

ODP
Something Specific and Simple
PDF
Länkad Data
PDF
(first '(Clojure.))
PDF
Webbens Arkitektur
PDF
Damn Fine CoffeeScript
PDF
Groovy Fly Through
Something Specific and Simple
Länkad Data
(first '(Clojure.))
Webbens Arkitektur
Damn Fine CoffeeScript
Groovy Fly Through

Recently uploaded (20)

PPTX
The various Industrial Revolutions .pptx
PPTX
Tartificialntelligence_presentation.pptx
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
PDF
A contest of sentiment analysis: k-nearest neighbor versus neural network
PPTX
cloud_computing_Infrastucture_as_cloud_p
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
Web App vs Mobile App What Should You Build First.pdf
PDF
August Patch Tuesday
PPTX
Chapter 5: Probability Theory and Statistics
PPT
What is a Computer? Input Devices /output devices
PDF
Hybrid model detection and classification of lung cancer
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
gpt5_lecture_notes_comprehensive_20250812015547.pdf
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PDF
project resource management chapter-09.pdf
PPTX
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
PDF
WOOl fibre morphology and structure.pdf for textiles
PDF
DP Operators-handbook-extract for the Mautical Institute
The various Industrial Revolutions .pptx
Tartificialntelligence_presentation.pptx
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
DASA ADMISSION 2024_FirstRound_FirstRank_LastRank.pdf
A contest of sentiment analysis: k-nearest neighbor versus neural network
cloud_computing_Infrastucture_as_cloud_p
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Web App vs Mobile App What Should You Build First.pdf
August Patch Tuesday
Chapter 5: Probability Theory and Statistics
What is a Computer? Input Devices /output devices
Hybrid model detection and classification of lung cancer
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
gpt5_lecture_notes_comprehensive_20250812015547.pdf
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Univ-Connecticut-ChatGPT-Presentaion.pdf
project resource management chapter-09.pdf
MicrosoftCybserSecurityReferenceArchitecture-April-2025.pptx
WOOl fibre morphology and structure.pdf for textiles
DP Operators-handbook-extract for the Mautical Institute

Python utan-stodhjul-motorsag