Python Introduction

(for Agile Girls)

By Carmen Berros / @mcberros

Carmen Berros

(Who's that girl?)

[Carmen Berros, circa 2011]
  • Working as a professional since 2000
  • Worked with Apache Web Server and JAVA Web Applications at big companies
  • Fell in love with Devops
  • Python used for automatization
  • Follow me at @mcberros

This talk

  1. Environment
  2. Basic Syntax
  3. Built-in Types and Operators
  4. Assignment
  5. Control Flow
  6. Functions
  7. Modules and classes
  8. Tools
  9. Resources

Environment

Original by Sebastian Niedlich (Grabthar): http://bit.ly/YDQxdA

Running Python

Interactive Interpreter


        $python             # Unix/Linux
        python%             # Unix/Linux
        C:>python           # Windows/DOS
      

Script from the Command-line


    $python  script.py          # Unix/Linux
    python% script.py           # Unix/Linux
    C:>python script.py         # Windows/DOS
      

Executable Python Scripts(I)

    Unix Systems
  • Python scripts can be made directly executable
  • Putting the follow line at the beginning of the script
  • 
              #! /usr/bin/env python
              
  • Giving the file an executable mode
  • 
              $ chmod +x myscript.py
              

Executable Python Scripts (II)

    Windows systems
  • The Python installer automatically associates .py files with python.exe
  • A double-click on a Python file will run it as a script

Basic Syntax

Original by Dave Bleasdale: http://bit.ly/119ujqW

Comments

Each line of a block comment starts with a # and a single space


        # First comment example
        var = 1   # second comment
                  # ... and now a third
      

Indentation

Very important

  • 4 spaces per indentation level
  • Old code: 8-space
  • Never mix tabs and spaces!

Indentation

Good code


        def get_var_l(l):
          # Compute var r
          if len(l) <= 1:
            return [l]
      

Noooooooo


        def perm(l):
      # Compute var r
      if len(l) <= 1:
          return [l]
      

Built-in Types and Operators

Original by Joseph Robertson: http://bit.ly/ZMZxxN

Boolean

    Values considered as False
  • None
  • False
  • Zero of numeric types: 0, 0L, 0.0, 0j
  • Empty sequence: '', (), []
  • Empty mapping: {}
  • Methods of classes that return false

  • All other values are considered as True

Boolean Operators

Operation Result
x and y if x is false, then x, else y
x or y if x is false, then y, else x
not x if x is false, then True, else False

Numeric

  • Integers: 4
  • Long integers: 4L
  • Floating point: 4.4
  • Complex numbers: 4j

Numeric Operators (I)

Operation Result
x+y sum of x and y
x-y difference of x and y
x*y product of x and y
x/y quotient of x and y
x//y (floored) quotient of x and y
x%y remainder of x / y
-x x negated
+x x unchanged

Numeric Operators (II)

Operation Result
abs(x) absolute value or magnitude of x
int(x) x converted to integer
long(x) x converted to long integer
float(x) x converted to floating point
divmod(x,y) the pair (x//y,x%y)
x**y x to the power y

Sequence Types

String

There isn't a character type; these are treated as strings of length one


  word = 'word'
  sentence = "This is a sentence."
  paragraph = """This is a paragraph. It is
                    made up of multiple lines and sentences."""
      

Sequence Types

Print statement

This function converts the expressions you pass it to a string and writes the result to standard output


        >>> print 'Hello World!'
        Hello World!
        >>> print 10
        10
      

Sequence Types

String Format Operator


  >>> name ='Zara'
  >>> weight=55
  >>> sentence='My name is %s and my weight is %d' % (name,weight)
  >>> print sentence
  My name is Zara and my weight is 12 
      

Sequence Types

List

Lists are mutable: support additional operation

s that allow in-place modification of the object


        list1 = [1990, 1992, 1997, 2000]
        list2 = [1, 2, 3, 4, 5 ]
        list3 = ["a", "b", "c", "d"]
      

Sequence Types

Tuple


        tup1 = (1990, 1992, 1997, 2000)
        tup2 = (1, 2, 3, 4, 5 )
        tup3 = ("a", "b", "c", "d")
      
    Tuples vs Lists
  • Tuples are faster than lists
  • Code safer if you “write-protect” data that does not need to be changed
  • Tuples can be used as dictionary keys

Sequence Types

Unicode


        print u'Hello, world!'
      

Sequence Type Operators (I)

Operation Result
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n, n * s n copies of s concatenated
len(s) length of s
s.index(i) index of the first occurence of i in s
s.count(i) total number of occurences of i in s
s[i] ith item of s, origin 0. If i > len(s) then raises IndexError

Sequence Type Operators (II)

Operation Result
s[i:j] slice of s from i to j. If j > len(s) then return until the end of the string

            >>> var2 = "Python Programming"
            >>> print "var2[1:5]: ", var2[1:5]
            var2[1:5]:  ytho
            
s[i:j:k] slice of s from i to j with step k

                >>> var2 = "Python Programming"
                >>> print "var2[1:5:2]: ", var2[1:5:2]
                var2[1:5:2]:  yh
              

Mutable Sequence Type Operators (I)

Lists and Bytearrays

Operation Result
s[i]=x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s.append(x) same as s[len(s):len(s)] = [x]
s.extend(x) same as s[len(s):len(s)] = x
s.count(x) return number of i‘s for which s[i] == x

Mutable Sequence Type Operators (II)

Lists and Bytearrays

Operation Result
s.insert(i, x) same as s[i:i] = [x]
s.pop([i]) same as x = s[i]; del s[i]; return x
s.remove(x) same as del s[s.index(x)]
s.reverse() reverses the items of s in place
s.sort([cmp[, key[, reverse]]]) sort the items of s in place

Mapping type: Dict

  • Pairs (items) of keys and values
  • 
            dict = {'Mercy': 12, 'Joe': 17, 'Henry': 45}
            
  • More than one entry per key not allowed.
  • 
            dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}
            # Wins 'Manni'
            
  • Keys always immutable. You can use strings, numbers or tuples
  • 
            # Nooooooo
            dict = {['Name']: 'Zara', 'Age': 7};
            

Dict Operators (I)

Operation Result
len(d) Return the number of items in the dictionary d
d[key] Return the item of d with key key. Raises a KeyError if key is not in the map
d[key] = value Set d[key] to value
del d[key] Remove d[key] from d. Raises a KeyError if key is not in the map
key in d Return True if d has a key key, else False.
key not in d Equivalent to not key in d

Dict Operators (II)

Operation Result
popitem() Remove and return an arbitrary (key, value) pair from the dictionary.
clear() Remove all items from the dictionary
copy() Return a shallow copy of the dictionary

Dict Operators (III)

Operation Result
items(), iteritems() items() return a copy of the dictionary’s list of (key, value) pairs. iteritems() return an iterator over the dictionary’s (key, value) pairs
keys(), iterkeys(), iter(d) keys() return a copy of the dictionary’s list of keys. iterkeys() and iter(d), return an iterator over the dictionary’s keys.
values(), itervalues() values() return a copy of the dictionary’s list of values. itervalues() return an iterator over the dictionary’s values.

More types

  • Sequence Types
    • Bytearray
    • Buffer
    • Xrange

  • Set Types
    • Set
    • Frozenset

Comparation Operators

Operation Meaning
< strictly less than
<= less than or equal
> strictly greater than
>= greater than or equal
== equal
!= not equal
is object identity
is not negated object identity

Precedence in operators (I)

Operator Description
or Boolean OR
and Boolean AND
not x Boolean NOT
in, not in, is, is not, <, <=, >, >=, <>, !=, == Comparisons, membership tests , identity tests
+, - Addition, subtraction
*, /, //, % Multiplication, division, remainder
+x, -x Positive, negative
** Exponentiation

Precedence in operators (II)

Operator Description
x[index], x[index:index], x(arguments...), x.attribute Subscription, slicing, call, attribute reference
(expressions...), [expressions...], {key:value...}, `expressions...` Binding or tuple display, list display, dictionary display, string conversion

Assignment

Original by asenat29: http://bit.ly/PEy6YJ

Assignment

The equal sign ('=') is used to assign a value to a variable


        width = 20
        height = 5*9
      

A value can be assigned to several variables simultaneously


        x = y = z = 0  # Zero x, y and z
      

Destructuring assignment / tuple unpack in Python


        »> x,y = 1,2
        »> x,y
        (1, 2)
        # equal as
        »> x, y = [1,2]
        »> x, y = (1,2)
      

Python 3 deprecates this feature and offers taking rest of tuple into last variable


        »> x,y,*z = 1,2,3,4,5
        »> x,y,z
        (1, 2, [3, 4, 5])
      

Control Flow

Original by ¡Carlitos: http://bit.ly/114Tfwe

if

  • If logical_expression is true, then execute statements.
  • 
              #!/usr/bin/python
              var1 = 100
              if var1:
                print "var1 is true"
              
  • If logical_expresion is false, then execute code after the end of the if statement.
  • 
                #!/usr/bin/python
                var2 = 0
                if not var2:
                  print "var2 is false"
                print "Out if"
              

if...elif...else (I)

    elif
  • To check multiple expressions for truth value
  • Execute a block of code as soon as one of the conditions evaluates to true.
  • Optional and there can be an arbitrary number

if...elif...else (II)

    else
  • Block of code that executes if the conditional expression in the if statement resolves false value
  • Optional
  • At most only one

          var = 100
          if var > 100:
            print "var > 100"
          elif var < 100:
            print "var < 100"
          else:
            print "var == 100"
        

while

  • Repeatedly executes a target statement as long as a given condition is true
  • The else statement is executed when the condition becomes false (optional)

        #!/usr/bin/python
        count = 0
        while count < 5:
          print count, " is  less than 5"
          count = count + 1
        else:
          print count, " is greater than 5"
      

for

  • Syntax
    
              for iterating_var in sequence:
                statements(s)
             
  • Sequence contains a list
  • Each item is assigned to iterating_var, and the statements block is executed until the sequence is exhausted
  • else

        #!/usr/bin/python
        fruits = ['banana', 'apple', 'mango']
        for fruit in fruits:
          print 'Current fruit :', fruit
      

List comprehension

A more concise way to create lists


    >>> print [i for i in range(10)]
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
       

    >>> print [i for i in range(20) if i%2 == 0]
    [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
       

    >>> nums = [1,2,3,4]
    >>> fruit = ["Apples", "Peaches", "Pears", "Bananas"]
    >>> print [(i,f) for i in nums for f in fruit]
    [(1, 'Apples'), (1, 'Peaches'), (1, 'Pears'), (1, 'Bananas'),
     (2, 'Apples'), (2, 'Peaches'), (2, 'Pears'), (2, 'Bananas'),
     (3, 'Apples'), (3, 'Peaches'), (3, 'Pears'), (3, 'Bananas'),
     (4, 'Apples'), (4, 'Peaches'), (4, 'Pears'), (4, 'Bananas')]
      

Functions

Original by Thomas Kamann: http://bit.ly/YLI1fI

Function

  • Block of organized, reusable code
  • Used to perform a single action
  • Provide better modularity

        def add(a, b):    # add 2 numbers
          """Add to numbers."""
          c = a + b
          return c
        
        # Now call the function we just defined:
        add(1, 2)
        3
      

Arguments (I)

Required arguments

  • Arguments passed to a function in correct positional order
  • The number of arguments in the function call should match exactly with the function definition

  def print_arg(arg):
    print arg

  >>> print_arg()
  Traceback (most recent call last):
  File "", line 1, in 
  TypeError: print_arg() takes exactly 1 argument (0 given)
  >>> 
      

Arguments (II)

Keyword arguments

  • The caller identifies the arguments by the parameter name
  • Allow to skip arguments or place them out of order

        #!/usr/bin/python

        # Function definition is here
        def printinfo( name, age ):
           "This prints a passed info into this function"
           print "Name: ", name
           print "Age ", age
           return

        # Now you can call printinfo function
        printinfo( age=50, name="miki" )
      

Arguments (III)

Default Argument Values

  • Specify a default value for one or more arguments
  • The function can be called with fewer arguments than it is defined to allow.

        #!/usr/bin/python

        # Function definition is here
        def printinfo( name, age = 35 ):
           "This prints a passed info into this function"
           print "Name: ", name
           print "Age ", age
           return

        # Now you can call printinfo function
        printinfo( age=50, name="miki" )
        printinfo( name="miki" )
      

Arguments (IV)

Arbitrary Argument Lists

  • These arguments will be wrapped up in a tuple

        #!/usr/bin/python

        # Function definition is here
        def printinfo( arg1, *vartuple ):
           "This prints a variable passed arguments"
           print "Output is: "
           print arg1
           for var in vartuple:
              print var
           return;

        # Now you can call printinfo function
        printinfo( 10 );
        printinfo( 70, 60, 50 );
      

Modules and classes

Original by ishabluebell: http://bit.ly/WyWkEF

Module

Defining

  • File with Python code to organize the code
  • File name = module_name.py

        # Module hello in hello.py file
        def print_func( par ):
          print "Hello : ", par
          return
      

Module

Using

  • Can import other modules
  • Customary but not required to place all import statements at the beginning of a module

        # Using the module hello
        #!/usr/bin/python

        import hello

        hello.print_func("Zara")
      

Class

Defining


  class Employee:
    'Common base class for all employees'
    empCount = 0

    def __init__(self, name, salary):
      self.name = name
      self.salary = salary
      Employee.empCount += 1
   
    def displayCount(self):
      print "Total Employee %d" % Employee.empCount

    def displayEmployee(self):
      print "Name : ", self.name,  ", Salary: ", self.salary
      

Creating instance objects

Call the class using class name and pass in whatever arguments its __init__ method accepts


  # This would create first object of Employee class
  emp1 = Employee("Zara", 2000)
  # This would create second object of Employee class
  emp2 = Employee("Manni", 5000)
      

Accessing attributes and methods


  emp1.displayEmployee()
  emp2.displayEmployee()
  print "Total Employee %d" % Employee.empCount
      

Inheritance (I)

  • You can create a class by deriving it from a preexisting class
  • The child class inherits the attributes of its parent class

  #!/usr/bin/python

  class Parent:        # define parent class
    def __init__(self):
      print "Calling parent constructor"

    def parentMethod(self):
      print 'Calling parent method'

      

Inheritance (II)


class Child(Parent): # define child class
  def __init__(self):
    print "Calling child constructor"

  def childMethod(self):
    print 'Calling child method'

c = Child()          # instance of child
c.childMethod()      # child calls its method
c.parentMethod()     # calls parent's method
      

Multiple Inheritance (I)

    Old-style classes
  • Until 2.2 Version
  • Rule depth-first, left-to-right
  • If an attribute is not found in C, it is searched in A, then (recursively) in the base classes of A, and only if it is not found there, it is searched in B, and so on.

  class A:        # define your class A
  .....

  class B:         # define your class B
  .....

  class C(A, B):   # subclass of A and B
      

Multiple Inheritance (II)

    New-style classes
  • From 2.3 Version
  • The method resolution order changes dynamically
  • http://www.python.org/download/releases/2.3/mro/

Overriding Methods


  class Parent:     # define parent class
     def myMethod(self):
        print 'Calling parent method'

  class Child(Parent): # define child class
     def myMethod(self):
        print 'Calling child method'

  c = Child()    # instance of child
  c.myMethod()   # child calls overridden method
  
  #result
  Calling child method
      

Overloading Operators

  class Vector:
     def __init__(self, a, b):
        self.a = a
        self.b = b

     def __str__(self):
        return 'Vector (%d, %d)' % (self.a, self.b)
     
     def __add__(self,other):
        return Vector(self.a + other.a, self.b + other.b)

  v1 = Vector(2,10)
  v2 = Vector(5,-2)
  print v1 + v2
  #result
  Vector(7,8)

Private methods and attributes (I)

  • Privateness is a matter of convention, not force
  • http://stackoverflow.com/questions/70528/why-are-pythons-private-methods-not-actually-private
  • 
      #!/usr/bin/python
    
      class JustCounter:
        __secretCount = 0
      
        def count(self):
          self.__secretCount += 1
          print self.__secretCount
    
          

Private methods and attributes (II)


    counter = JustCounter()
    counter.count()
    counter.count()
    print counter.__secretCount

    #Result
    1
    2
  Traceback (most recent call last):
  File "test.py", line 12, in 
    print counter.__secretCount
  AttributeError: JustCounter instance has no attribute '__secretCount'
      

      print counter._JustCounter__secretCount

      # Result
    2
      

Tools

Original by JanneM: http://bit.ly/Z9fdup

Resources

  • Official Web Site: http://www.python.org/
  • Tutorials
  • http://learnpythonthehardway.org/book/ http://en.wikibooks.org/wiki/A_Beginner
  • Koans: Koans: https://github.com/gregmalcolm/python_koans
  • Style guide: http://www.python.org/dev/peps/pep-0008/
  • Good courses using python: https://www.udacity.com/

The End

Some questions?

Original by Scott McLeod: http://bit.ly/WRqGV3