What is python?

  • "Python is an interpreted, object-oriented, high-level programming language with dynamic semantics. Its high-level built in data structures, combined with dynamic typing and dynamic binding, make it very attractive for Rapid Application Development, as well as for use as a scripting or glue language to connect existing components together. Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance. Python supports modules and packages, which encourages program modularity and code reuse."
    Source: What is Python? Executive Summary
  • Ask questions
  • Feel free to follow along - http://repl.it

"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance."

Simple, easy to learn syntax

  • ...and now, the simplest 'Hello World'
#Lets say hi
print "Hello World."
>> 'Hello World.'
      

"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance."

Simple, easy to learn syntax

  • Function blocks begin with the keyword def followed by the function name.
  • Indentation is syntax
  • `return` keyword causes function to exit and pass value back to its caller
  • Function arguments can have default values!
def addVariables(x, y=2):
  """This method has a default argument.
  This makes the second argument optional, neat!
  """
  if y >= 500:
    return "That number is too damn high!"
  else:
    return x + y

print addVariables(2)
>> 4
some_var = addVariables(2,51252)
print some_var
>> "That number is too damn high!"
      

"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance."

  • Throw away your {} blocks!
  • Throw away your ;'s!
  • Embrace indentation
    • Never again struggle to read this:
    • if( gravy ){
        if( cheddar ){
         foo( gravy, cheddar );
      }
      else{
        bacon();
      }}
                    
  • Follow the PEP8
    • ...to the grave
    • 4 SPACES to indent

"Python's simple, easy to learn syntax emphasizes readability and therefore reduces the cost of program maintenance."

  • All block statements are denoted by indentation
  • if my_var == "gravy":
      print "bacon"
    elif:
      print "fail"
    
    for thing in things:
      print thing
            
  • You can still do it wrong if you insist on it...
  • def perm(l):
    # Compute the list of all permutations of l
      if len(l) <= 1:
        return [l]
       r = []
        for i in range(len(l)):
                 s = l[:i] + l[i+1:]
                 p = perm(s)
                 for x in p:
                  r.append(l[i:i+1] + x)
        return r
          

Its high-level built in data structures types, combined with dynamic typing and dynamic binding"

Strings

  • Strings can be wrapped in ", ', ''', or """
  • #These are all valid strings
    string_a = "This is a string"
    string_b = 'This is a string'
    string_c = """This is a string"""
    string_d = '''This is a string'''
            
  • """ and ''' can be multiple lines
  • PEP8 recommends using "triple doubles" ( """ ) for docstrings
  • Docstrings defined in this way become accessible via the __doc__ attr of that object
  • def gravyMaker():
      """ This method makes the gravy """
      return "Gravy."
    
    gravyMaker.__doc__
    >> 'This method makes the gravy'
            

Its high-level built in data structures, combined with dynamic typing and dynamic binding"

Lists

  • Array-like data structure
  • 0 Indexed
  • Heterogeneous
  • my_list = []
    my_list.append('gravy')
    my_list.insert(0,'bacon')
    my_list.extend(['cheddar','tacos',True])
    
    len(my_list)
    >> 5
    
    print my_list
    >> ['bacon', 'gravy', 'cheddar', 'tacos', True]
    
    print my_list[0]
    >> 'bacon'
    
    print my_list[0:3]
    >> ['bacon', 'gravy', 'cheddar']
    
    print my_list[-1]
    >> True
            

Its high-level built in data structures, combined with dynamic typing and dynamic binding"

Dictionaries

  • Hash-able structure
  • Variable length, heterogeneous, arbitrarily nestable
  • Keys can be any immutable type ( string, int, float, tuple )
  • Iterable
    • Use .iteritems() in Python 2.6+
    • Use .items() in Python 3.x and 2.5-
  • Subscriptable
  • Unordered
    • Python 2.7 added OrderedDict to Collections module

Its high-level built in data structures, combined with dynamic typing and dynamic binding"

    me = {}
    me['first_name'] = 'TJ'
    
    print me['first_name']
    >> 'TJ'
    
    me.update({
      'last_name':'Kells'
      ,'hair': 'Brown'
    })
    
    print me.get('last_name')
    >> 'Kells'
    
    #Dict keys can be any immutable type
    me[43.03] = 'latitude'
    me[87.90] = 'longitude'
    
    me["friends"] = ["Arthur", "Ford", "Zaphod", "Trillian"]
    
    me["car"] = {
      "make": "Subaru"
      ,"model": "Outback"
    }
    me.get('car').get('make')
    >> 'Subaru'
    
    for key, value in me.iteritems():
      print "{0} => {1}".format( key, value )
    
    >> first_name => TJ
    >> last_name => Kells
    >> 87.9 => longitude
    >> 43.03 => latitude
    >> car => {'make': 'Subaru', 'model': 'Outback'}
    >> hair => Brown
    >> friends => ['Arthur', 'Ford', 'Zaphod', 'Trillian']
            

Python supports modules and packages, which encourages program modularity and code reuse

Modules

  • Any valid python file can be a module
  • Logically organize code
  • Module can contain
    • Variables/Properties
    • Methods
    • Classes
    • Anything!

Python supports modules and packages, which encourages program modularity and code reuse

    #/home/tkells/MyModule.py
    def say_hi( world_part ):
      print "Hello : ", world_part
      return
    
    my_name = 'TJ Kells'
            
    #/home/tkells/arbitrary.py
    import MyModule
    
    MyModule.say_hi('World!')
    >> 'Hello World!'
    
    print MyModule.my_name
    >> 'TJ Kells'
    
    from MyModule import say_hi
    
    say_hi('World!')
    >> 'Hello World!'
            

Python supports modules and packages, which encourages program modularity and code reuse

Packages

  • Created by adding __init__.py to directory
  • Collection of modules in directories that give a package hierarchy
  • Allows dotted notation import of sub-modules -ex Module.Submodule.Function()
  • #/home/tkells/MyPackage/Extras/MyModule.py
    def say_hi( world_part ):
      print "Hello : ", world_part
      return
            
    #/home/tkells/arbitrary.py
    from MyPackage.Extras import MyModule
    
    MyModule.say_hi('World!')
    >> 'Hello World!'
    
    import MyPackage
    MyPackage.Extras.MyModule.say_hi('World!')
    >> 'Hello World!'
            

"Python is an interpreted, object-oriented, high-level programming language with dynamic semantics."

"Python is an interpreted, object-oriented, high-level programming language with dynamic semantics."

  • Everythings an object!
    x = 5
    dir(x)
    >> ['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__'
    ...SNIP... ,'__init__' ...SNIP...
    'bit_length', 'conjugate', 'denominator', 'imag', 'numerator', 'real']
    x.real
    >> 5
              
  • Simple Class System
    class Person(object):
      def __init__(self, name, age):
        self.name = name
        self.age = age
    
      def is_old(self):
          return self.age > 40
    
    person = Person('TJ Kells', 28)
    print person.is_old()
    >> False
                  

"Python is an interpreted, object-oriented, high-level programming language with dynamic semantics."

  • Dynamic Semantics
    • Strongly and dynamically typed ( Strong Typing != Strict Typing )!
    • Interpreter does not munge types
      "x"+3
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      TypeError: cannot concatenate 'str' and 'int' objects
                    
    • Supports dynamic variable assignment
      x = "Hello"
      print x
      >> Hello
      x = 5
      print x + 5
      >> 10
                      

Resources

<Thank You!>

TJ Kells

tj.kells@corvisa.com