SlideShare ist ein Scribd-Unternehmen logo
1 von 53
Downloaden Sie, um offline zu lesen
Introduction to Python



   Master in Free Software   2009/2010

  Joaquim Rocha <jrocha@igalia.com>




                                23, April 2010
What is it?


* General­purpose, high­level programming 
language

* Created by Guido van Rossum




                      Master in Free Software | 2009­2010   2
What is it?


* Named after Monty Python's Flying Circus

* Managed by the Python Software Foundation


* Licensed under the Python Software Foundation 
license (Free Software and compatible with GPL)


                         Master in Free Software | 2009­2010   3
How is it?

* Multi­paradigm

* Features garbage­collection

* Focuses on readability and productivity

* Strong introspection capabilities

                        Master in Free Software | 2009­2010   4
How is it?


* Batteries included!

* Guido is often called Python's Benevolent 
Dictator For Life (BDFL) for he makes the final 
calls in Python's matters




                        Master in Free Software | 2009­2010   5
Brief history


* Created in 1991 at the Stichting Mathematisch
Centrum (Amsterdam)

* Designed as a scripting language for the
Amoeba system

* January 1994: version 1.0


                         Master in Free Software | 2009­2010   6
Brief history

* October 2000: version 2.0

* December 2001: version 2.2 (first release under
PSF license)

* October 2008: version 2.6

* December 2008: version 3.0

                         Master in Free Software | 2009­2010   7
Python Software Foundation 
                License

* Free Software license (recognized by the Open
Source Initiative)

* GPL-compatible

* http://python.org/psf/license/

* http://www.python.org/download/releases/2.6.2/license/



                                   Master in Free Software | 2009­2010   8
Companies using Python
* Google (and YouTube)

* NASA

* Philips

* Industrial Light & Magic

* EVE Online
...
                        Master in Free Software | 2009­2010   9
Projects using Python

* Django
* Pitivi
* Trac
* Plone
* Frets on Fire
* Miro
* OCRFeeder
...
                   Master in Free Software | 2009­2010   10
Some books on Python


* Programming Python (O'Reilly)

* Python in a Nutshell (O'Reilly)

* Dive Into Python (Apress)

* Expert Python Programming (Packt Publishing)


                          Master in Free Software | 2009­2010   11
How to install it


* It's already installed in most mainstream 
distros

* If not, on Debian:

              apt­get install python


                        Master in Free Software | 2009­2010   12
Python Shell

$ python
Python 2.6.4 (r264:75706, Dec  7 2009, 18:45:15)
[GCC 4.4.1] on linux2
Type "help", "copyright", "credits" or "license" for 
more information.
>>> import this
The Zen of Python, by Tim Peters
...

                           Master in Free Software | 2009­2010   13
Documentation


* Python is really well documented

  http://docs.python.org

* On Debian distros, install python2.6­doc to 
view it with Devhelp


                        Master in Free Software | 2009­2010   14
Some helpful functions

* The help command displays the help on a symbol
  >>> import os
  >>> help(os.path)

* The dir command displays attributes or available 
names
  >>> dir() # displays names in current scope
  >>> dir(str) # displays attributes of the class and its 
bases

                              Master in Free Software | 2009­2010   15
Python packages and modules

  # This is a module, and would be the execution script
  myapp_run.py 
  myapp/ # A package
      __init__.py # A special module
      myappcode.py # A module
      lib/ # A sub­package
          __init__.py
          util_functions.py # Another module

* The __init__.py is often empty but is what allows the 
package to be imported as a if it was a module.

                               Master in Free Software | 2009­2010   16
Example of types
*  In Python everything is an object

* str : strings (there is also a string module, that 
most functions are now available in str)

  'This is a string'
  “This is also a string!”
  “””And this is a
  
  multiline string...”””
                             Master in Free Software | 2009­2010   17
Example of types

* int: integer numbers

  i = 12 + 4

* float: floating point numbers

  f = 0.45



                         Master in Free Software | 2009­2010   18
Example of types

* bool: booleans

  b = True
  e = b and c or d

* list: list objects

  list_var = ['foo', 45, False]


                                  Master in Free Software | 2009­2010   19
Example of types


* dict: dictionary objects

  d = {'type': 'person', 'age': 24,
          10: 'just to show off an int key'}

...


                                   Master in Free Software | 2009­2010   20
Checking a type




 >>> type(some_object) # gives the object's type
 >>> isinstance('foo bar', str) # returns True




                             Master in Free Software | 2009­2010   21
Castings


  int('5') # gives the integer 5

  str(5) # gives the string '5'

  bool('') # gives False



                             Master in Free Software | 2009­2010   22
Whitespace indentation


* Python blocks are defined by indentation 
instead of curly brackets or begin/end 
statements.

* Failing to properly indent blocks raises 
indentation exceptions



                         Master in Free Software | 2009­2010   23
Whitespace indentation


* If a new block is expected and none is to be 
defined, the pass keyword can be used

  if x is None:
      pass



                       Master in Free Software | 2009­2010   24
Control flow: if


  if x < 0:
      print 'X is negative!'
  elif x > 0:
      print 'X is positive!'
  else:
      print 'X is zero...'


                               Master in Free Software | 2009­2010   25
Control flow: for



  for x in range(10): # this is [0..9]
      if x % 2 == 0:
          continue
      print x ** 2



                              Master in Free Software | 2009­2010   26
Control flow: while


  fruits = ['bananas', 'apples', 'melon', 'grapes',         
                 'oranges']
  i = 0
  while i < len(fruits):
      if len(fruits[i]) == 5:
          break
      i += 1


                              Master in Free Software | 2009­2010   27
Functional programming
* Being multi­paradigm, Python also has functions 
common in functional programming

* It features lambda, map, filter, reduce, ...

  numbers = [1, 2, 3, 4]
  map(lambda x: x ** 2, numbers) # gives [1, 4, 9, 16]

  filter(lambda x: x % 2 == 0, numbers) # gives [2, 4]

  reduce(lambda x, y: x + y, numbers) # gives 10
                              Master in Free Software | 2009­2010   28
Functional programming



* List comprehension

  numbers = [1, 2, 3, 4, 5, 6, 7, 8]
  even_numbers = [n for n in numbers 
                                 if n % 2 == 0] 



                              Master in Free Software | 2009­2010   29
Error handling: try / except
* Equivalent to try, catch statements

  import random

  n = random.choice(['three', 1])
  try:
      a = 'three ' + n
  except TypeError:
      a = 3 + n
  else: # else body is executed is try's body didn't raise an exception
      a = 'The answer is ' + a
  finally: # this is always executed
      print a


                                       Master in Free Software | 2009­2010   30
Error handling: try / except

* Getting exception details

  try:
      a = not_defined_var
  except Exception as e: 
      # the "as" keyword exists since Python 2.6
      # for Python 2.5, use “,” instead
      print type(e)

                           Master in Free Software | 2009­2010   31
Error handling: try / except


* Raising exceptions

  password = 'qwerty'
  if password != 'ytrewq':
      raise Exception('Wrong password!')



                          Master in Free Software | 2009­2010   32
Imports

* Import a module:

  import datetime
  d = datetime.date(2010, 4, 22)

* Import a single class from a module:

  from datetime import date
  d = date(2010, 4, 22)

                           Master in Free Software | 2009­2010   33
Imports

* Import more than one class from a module:

  from datetime import date, time
  d = date(2010, 4, 22)
  t = time(15, 45)

* Import a single module from another module:

  from os import path
  notes_exist = path.exists('notes.txt')

                                  Master in Free Software | 2009­2010   34
Imports

* Import everything from a module:

  from datetime import *
  t = time(15, 45)

* Rename imported items:

  from datetime import date
  from mymodule import date as mydate
  # otherwise it would have overridden the previous date

                            Master in Free Software | 2009­2010   35
Functions


  def cube(number):
      return number ** 3

  # optional arguments
  def power_from_square(base, exponent = 2):
      # every argument after an optional argument
      # must be also optional
      return base ** exponent



                               Master in Free Software | 2009­2010   36
Functions

  # the exponent argument is optional
  power(2) # returns 4
  power(2, 3) # returns 8

  # named arguments can be used
  power(base=8, exponent=4)

  # and can be even interchanged
  power(exponent=2, base=4)


                               Master in Free Software | 2009­2010   37
Object Oriented Programming

class Car:

      # this is a class variable
      min_doors = 3

      # contructor
      def __init__(self, model):
          # this is an instance variable
          self.model = model
          # this is a private variable
          self._color = 'white'


                                           Master in Free Software | 2009­2010   38
Object Oriented Programming
      # private method
      def _is_black(self):
          if self._color == 'black' or self._color == '#000':
              return True
          return False

      # public method
      def set_color(self, color):
          if color in ['black', 'white', 'red', 'blue']:
              self._color = color

      def get_extense_name(self):
          return 'A very fine %s %s' % (self.model, self._color)

                                               Master in Free Software | 2009­2010   39
Inheritance

  # this is how we say Car extends the Vehicle class
  class Car(Vehicle):

      def __init__(self, model):
          # we need to instantiate the superclass
          Vehicle.__init__(self, tyres = 4)
          self.model = model
          …


                                Master in Free Software | 2009­2010   40
Executing code

* Here is how is Python's main:

  if __name__ == '__main__':
      a = 1
      print a

* Execute it with:

  $ python print_one.py
                          Master in Free Software | 2009­2010   41
Properties

* Properties abstract actions on an attribute, as get, set, 
del or doc

  # When you set/get person.name, it will do a customized set/get
  class Person:
      def __init__(self, name):
          self.name = name
      def _set_name(self, name):
          self._name = str(name)
      def _get_name(self):
          return 'My name is ' + self._name
      name = property(_get_name, _set_name)

                                    Master in Free Software | 2009­2010   42
Distributing your application
* Distutils allows to easily packages your application, install it, etc.

* Our app structure:

  SupApp/
    setup.py
    supaapp
    data/
      supaapp.png
    src/
      supaApp/
       supaapp.py
        lib/
          util.py

                                     Master in Free Software | 2009­2010   43
Distributing your application
* The magic script

  from distutils.core import setup
  setup(name = 'SupaApp',
             version = '0.5beta'
             description = 'A supa­dupa app!'
             author = 'Cookie Monster'
             author_email = 'cookiesmonster@sesamestree.fun'
             license = 'GPL v3',
             packages = ['SupaApp', 'SupaApp.lib'],
             package_dir = {'': 'src'},
             scripts = ['supaapp'],
             data_files = [('share/icons/hicolor/scalable/apps',          
                                    ['data/supaapp.png'])]
       )
                                           Master in Free Software | 2009­2010   44
Distributing your application


* The MANIFEST.in generates the MANIFEST file 
which describes what's to be included in the 
package:

  include supaapp
  recursive­include data *



                             Master in Free Software | 2009­2010   45
Distributing your application

* How to generate a source package

  $ python setup.py sdist

* How to install an app

  $ python setup.py install


                            Master in Free Software | 2009­2010   46
Docstrings
* Are nowadays written in ReStructuredText

* Documentation of a module:

  """This is a nice module.
       It shows you how to document modules
  """
  class Person:
      """This class represents a person.
          A person can have a name and ...
      """
      def __init__(self, name):
          "Instantiates a Person object with the given name"
          self.name = name
                                        Master in Free Software | 2009­2010   47
Some useful modules

import sys
# Available packages/modules must be under the folders
# sys.path has
print sys.path
# shows the arguments given after the python command
print sys.argv 

# get png image names
import os
png_names = [os.path.splitext(f)[0] for f in    
                        os.listdir('/home/user/images') if f.endswith('png')]

                                       Master in Free Software | 2009­2010   48
Some useful modules


* ElementTree is an easy to use XML library

from xml.etree import ElementTree as ET
tree = ET.parse("index.html")
print tree.findall('body/p')



                        Master in Free Software | 2009­2010   49
Decorators
* Decorators are functions that control other functions

import sys
import os

def verbose(function):

    def wrapper(*args, **kwargs):
         print 'Executing function: ', function.__name__
         print 'Arguments: ', args
         print 'Keyword Arguments: %sn' % kwargs
         return function(*args, **kwargs)
    return wrapper

                                        Master in Free Software | 2009­2010   50
Decorators


@verbose # this is how you apply a decorator
def list_dir(directory):
    for f in os.listdir(directory):
         print f

if __name__ == '__main__':
    # list the directory we specify as the first program's argument
    list_dir(sys.argv[1])




                                       Master in Free Software | 2009­2010   51
Decorators
* Testing the decorator

  $ python decorator_example.py /home/user/Documents
   
     Executing function:  list_dir
     Arguments:  ('/home/user/Documents/',)
     Keyword Arguments: {}

     notes.txt
     python_presentation.odp
     book_review.odt
                               Master in Free Software | 2009­2010   52
PDB: The Python Debugger

* Calling pdb.set_trace function will stop the 
execution and let you use commands similar 
to GDB

def weird_function():
    import pdb;
    pdb.set_trace()

    # code that is to be analyzed...

                                Master in Free Software | 2009­2010   53

Weitere ähnliche Inhalte

Was ist angesagt?

Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming languageSlawomir Dorzak
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17LogeekNightUkraine
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityGeorgePeterBanyard
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++Dmitri Nesteruk
 
Introduction to Programming Bots
Introduction to Programming BotsIntroduction to Programming Bots
Introduction to Programming BotsDmitri Nesteruk
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminarygo-lang
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)jeffz
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and deletePlatonov Sergey
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overviewgourav kottawar
 
Intro python-object-protocol
Intro python-object-protocolIntro python-object-protocol
Intro python-object-protocolShiyao Ma
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - BasicMosky Liu
 
Go Language Hands-on Workshop Material
Go Language Hands-on Workshop MaterialGo Language Hands-on Workshop Material
Go Language Hands-on Workshop MaterialRomin Irani
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsMohammad Shaker
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better JavaGarth Gilmour
 

Was ist angesagt? (20)

Functional go
Functional goFunctional go
Functional go
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
Vladymyr Bahrii Understanding polymorphism in C++ 16.11.17
 
PHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing InsanityPHP 8: Process & Fixing Insanity
PHP 8: Process & Fixing Insanity
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Design Patterns in Modern C++
Design Patterns in Modern C++Design Patterns in Modern C++
Design Patterns in Modern C++
 
Introduction to Programming Bots
Introduction to Programming BotsIntroduction to Programming Bots
Introduction to Programming Bots
 
Golang iran - tutorial go programming language - Preliminary
Golang iran - tutorial  go programming language - PreliminaryGolang iran - tutorial  go programming language - Preliminary
Golang iran - tutorial go programming language - Preliminary
 
Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)Why Java Sucks and C# Rocks (Final)
Why Java Sucks and C# Rocks (Final)
 
С++ without new and delete
С++ without new and deleteС++ without new and delete
С++ without new and delete
 
classes & objects in cpp overview
classes & objects in cpp overviewclasses & objects in cpp overview
classes & objects in cpp overview
 
Intro python-object-protocol
Intro python-object-protocolIntro python-object-protocol
Intro python-object-protocol
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5Object Oriented Programming using C++ - Part 5
Object Oriented Programming using C++ - Part 5
 
Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1Object Oriented Programming using C++ - Part 1
Object Oriented Programming using C++ - Part 1
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
 
Go Language Hands-on Workshop Material
Go Language Hands-on Workshop MaterialGo Language Hands-on Workshop Material
Go Language Hands-on Workshop Material
 
Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4Object Oriented Programming using C++ - Part 4
Object Oriented Programming using C++ - Part 4
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and Objects
 
Kotlin as a Better Java
Kotlin as a Better JavaKotlin as a Better Java
Kotlin as a Better Java
 

Andere mochten auch

Hands On The New Hildon
Hands On The New HildonHands On The New Hildon
Hands On The New HildonJoaquim Rocha
 
Introducción a Django
Introducción a DjangoIntroducción a Django
Introducción a DjangoJoaquim Rocha
 
Seriesfinale, a TV shows' tracker for Maemo 5
Seriesfinale, a TV shows' tracker for Maemo 5Seriesfinale, a TV shows' tracker for Maemo 5
Seriesfinale, a TV shows' tracker for Maemo 5Joaquim Rocha
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
Adapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo FremantleAdapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo FremantleJoaquim Rocha
 

Andere mochten auch (6)

Hands On The New Hildon
Hands On The New HildonHands On The New Hildon
Hands On The New Hildon
 
Introducción a Django
Introducción a DjangoIntroducción a Django
Introducción a Django
 
Seriesfinale, a TV shows' tracker for Maemo 5
Seriesfinale, a TV shows' tracker for Maemo 5Seriesfinale, a TV shows' tracker for Maemo 5
Seriesfinale, a TV shows' tracker for Maemo 5
 
Ocrfeeder
OcrfeederOcrfeeder
Ocrfeeder
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
Adapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo FremantleAdapting GNOME Applications to Maemo Fremantle
Adapting GNOME Applications to Maemo Fremantle
 

Ähnlich wie Python introduction

Ähnlich wie Python introduction (20)

Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Spsl iv unit final
Spsl iv unit  finalSpsl iv unit  final
Spsl iv unit final
 
Python ppt
Python pptPython ppt
Python ppt
 
unit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptxunit (1)INTRODUCTION TO PYTHON course.pptx
unit (1)INTRODUCTION TO PYTHON course.pptx
 
Python
PythonPython
Python
 
#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started#OOP_D_ITS - 2nd - C++ Getting Started
#OOP_D_ITS - 2nd - C++ Getting Started
 
Python lec1
Python lec1Python lec1
Python lec1
 
Pythonpresent
PythonpresentPythonpresent
Pythonpresent
 
Core Python.doc
Core Python.docCore Python.doc
Core Python.doc
 
05 python.pdf
05 python.pdf05 python.pdf
05 python.pdf
 
Python fundamentals
Python fundamentalsPython fundamentals
Python fundamentals
 
Python basics
Python basicsPython basics
Python basics
 
Introduction to python.pptx
Introduction to python.pptxIntroduction to python.pptx
Introduction to python.pptx
 
Learn python
Learn pythonLearn python
Learn python
 
python-160403194316.pdf
python-160403194316.pdfpython-160403194316.pdf
python-160403194316.pdf
 
Xdebug
XdebugXdebug
Xdebug
 
python into.pptx
python into.pptxpython into.pptx
python into.pptx
 
Python Course
Python CoursePython Course
Python Course
 
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
Introduction to Python 01-08-2023.pon by everyone else. . Hence, they must be...
 
Python unit1
Python unit1Python unit1
Python unit1
 

Python introduction