SlideShare uma empresa Scribd logo
1 de 62
Baixar para ler offline
Getting started
                 How to design programs
           Python concepts & party tricks




                   Python Workshop 2012
The essentials: getting started, program design, modules & I/O


                                 Eric Talevich

             Institute of Bioinformatics, University of Georgia


                                 Nov. 8, 2012




                            Eric Talevich   Python Workshop 2012
Getting started
                    How to design programs
              Python concepts & party tricks




1   Getting started

2   How to design programs
      Data structures
      Algorithms
      Interfaces

3   Python concepts & party tricks
      File-like objects
      Iteration
      The csv module




                               Eric Talevich   Python Workshop 2012
Getting started
                         How to design programs
                   Python concepts & party tricks


Getting started: Interpreter


  Your interactive interpreter is one of:
         python on the command line
         IDLE — Integrated DeveLopment Environment for Python              1

  We’ll use IDLE.


  Run this in the interpreter:

                                        import this




    1
        Included in the standard Python installation on Windows and Mac
                                    Eric Talevich   Python Workshop 2012
Getting started
                      How to design programs
                Python concepts & party tricks


Getting started: Scripts

    1   Write this in a new, blank text file:
        print "Hello, Athens!"




                                 Eric Talevich   Python Workshop 2012
Getting started
                      How to design programs
                Python concepts & party tricks


Getting started: Scripts

    1   Write this in a new, blank text file:
        print "Hello, Athens!"
    2   Save it in plain-text format with the name hi.py in the same
        directory as your interpreter session is running. Run it:
         python hi.py




                                 Eric Talevich   Python Workshop 2012
Getting started
                           How to design programs
                     Python concepts & party tricks


   Getting started: Scripts

         1   Write this in a new, blank text file:
             print "Hello, Athens!"
         2   Save it in plain-text format with the name hi.py in the same
             directory as your interpreter session is running. Run it:
              python hi.py

A CREDIT Add a line at the top of hi.py to tell Unix this is a Python
         script:
          #!/usr/bin/env python
         Make hi.py executable (from the terminal shell):
          chmod +x hi.py
         Now you don’t need the .py extension:
          mv hi.py hi
         ./hi
                                      Eric Talevich   Python Workshop 2012
Getting started
                        How to design programs
                  Python concepts & party tricks


Getting started: Documentation

       In the interpreter: help(function-or-module )
       On the command line: pydoc function-or-module
       In IDLE: <F1> (launches docs.python.org)
  Also, type(obj ), dir(obj ), vars(obj ) and auto-completion
  (tab or Ctrl+Space) are pretty handy.

  Try it:
            >>>   help(str)
            >>>   s = ’Hello’
            >>>   type(s)
            >>>   dir(s)
            >>>   help(s.capitalize)
            >>>   help(help)

                                   Eric Talevich   Python Workshop 2012
Getting started
                     How to design programs
               Python concepts & party tricks


Example: string methods




  Find the string (str) methods to. . .
      Convert gOoFy-cAsE words to title case, upper case or
      lower case
      Remove certain characters from either end
      Align (justify) within a fixed width, padded by spaces




                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces


How to design programs


  Data structure: Organizes a collection of data units
   Algorithm: Defines operations for a specific task
     Interface: I/O, how a program interacts with the world


  Theorem
        Program = Data Structures + Algorithms + Interfaces




                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
      How to design programs     Algorithms
Python concepts & party tricks   Interfaces




          Data structures
     Organize a program’s information




                 Eric Talevich   Python Workshop 2012
Getting started   Data structures
                       How to design programs     Algorithms
                 Python concepts & party tricks   Interfaces


Units of data: Atoms

   Class        int       float                bool             —          str
   Literal     1, -2    .1, 2.9e8          True, False        None       ’abc’

  Try it:
              >>> num = 0.000000002
              >>> num
              >>> type(num)

  Features:
       Create from a data literal or by calling the class name
       (constructor)
       Always immutable — assigning another value replaces the
       original object


                                  Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces


Collections of data




   Class   Literal      Description
    list     []         Ordered array of arbitrary objects
    dict     {}         Unordered map of fixed to arbitrary objects
    set                 Unordered collection of fixed objects




                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces


Mutable vs. immutable objects


  Some mutable objects have immutable counterparts:
      list vs. tuple
      set vs. frozenset

  >>> x = (1, 2, 3)
  >>> x[0] = 7

  >>> y = list(x)
  >>> y[0] = 7
  >>> print y



                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces


Variables are names, not values
  Mutable collections can be shared:
  >>>   x = [1, 2, 3]
  >>>   y = x
  >>>   y[0] = 4
  >>>   x is y
  >>>   print ’x =’, x, ’y =’, y

  Reassigning to an immutable object replaces (changes the id of)
  the original:
  >>>   x = (1, 2, 3)
  >>>   y = x
  >>>   y = (4, 2, 3)
  >>>   x is y
  >>>   print ’x =’, x, ’y =’, y
                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
      How to design programs     Algorithms
Python concepts & party tricks   Interfaces




                     a fairly short
                     Break




                 Eric Talevich   Python Workshop 2012
Getting started   Data structures
      How to design programs     Algorithms
Python concepts & party tricks   Interfaces




                 Algorithms
                  Specify operations




                 Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Control flow

   Branching The if statement chooses between code paths:
              x = -2
              if x >= 0:
                     print x, "is positive"
              else:
                     print x, "was negative"
                     x = -x




                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Control flow

   Branching The if statement chooses between code paths:
              x = -2
              if x >= 0:
                     print x, "is positive"
              else:
                     print x, "was negative"
                     x = -x

     Iteration The for statement visits each element sequentially:
              for x in [-2, -1, 0, 1, 2]:
                    if x >= 0:
                          print x, "is positive"


                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                      How to design programs     Algorithms
                Python concepts & party tricks   Interfaces

#    Define a function
#   −−−−−−−−−−−−−−−−−
#   T h i s e x a m p l e shows how t o d e f i n e a s i m p l e f u n c t i o n .
#   The f u n c t i o n d e f i n i t i o n s t a r t s w i t h keyword ’ d e f ’ ,
#   t h e n t h e name o f t h e f u n c t i o n and t h e a r g u m e n t s .
#   The ’ d o c s t r i n g ’ i n q u o t e s i s o p t i o n a l , b u t n i c e .
#   The r e s t o f t h e code , i n d e n t e d , i s t h e f u n c t i o n body .
#
#   ( L i n e s t h a t b e g i n w i t h a h a s h (#) a r e comments . )

def n i c e a b s ( x ) :
    ””” R e t u r n t h e a b s o l u t e v a l u e o f a number . ”””
    i f x < 0:
            r e t u r n −x
    else :
            return x




                                 Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces


Algorithms



  Definition: A precise set of instructions for accomplishing a task.

  We’ll treat an algorithm as one or more functions that operate on
  some input data to produce some output according to a
  specification.

  Useful fact: The structure of a function will resemble the
  structure of the data it operates on.




                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
                       How to design programs     Algorithms
                 Python concepts & party tricks   Interfaces


The design recipe: a general method
  Steps, in order, for developing a program from scratch:                2


     Contract: Name the function; specify the types (i.e. atoms and
               data structures) of its input data and its output.
               abs: number → positive number




    2
        http://htdp.org/2003-09-26/Book/curriculum-Z-H-1.html
                                  Eric Talevich   Python Workshop 2012
Getting started   Data structures
                       How to design programs     Algorithms
                 Python concepts & party tricks   Interfaces


The design recipe: a general method
  Steps, in order, for developing a program from scratch:                2


     Contract: Name the function; specify the types (i.e. atoms and
               data structures) of its input data and its output.
               abs: number → positive number
        Purpose: Description of what the program does, in terms of
                 inputs and output — sufficient for a function
                 declaration and docstring.




    2
        http://htdp.org/2003-09-26/Book/curriculum-Z-H-1.html
                                  Eric Talevich   Python Workshop 2012
Getting started   Data structures
                       How to design programs     Algorithms
                 Python concepts & party tricks   Interfaces


The design recipe: a general method
  Steps, in order, for developing a program from scratch:                2


     Contract: Name the function; specify the types (i.e. atoms and
               data structures) of its input data and its output.
               abs: number → positive number
        Purpose: Description of what the program does, in terms of
                 inputs and output — sufficient for a function
                 declaration and docstring.
     Example: Function call with arguments, and expected result.
              abs(-1) → 1
              abs(1) → 1




    2
        http://htdp.org/2003-09-26/Book/curriculum-Z-H-1.html
                                  Eric Talevich   Python Workshop 2012
Getting started   Data structures
                       How to design programs     Algorithms
                 Python concepts & party tricks   Interfaces


The design recipe: a general method
  Steps, in order, for developing a program from scratch:                2


     Contract: Name the function; specify the types (i.e. atoms and
               data structures) of its input data and its output.
               abs: number → positive number
        Purpose: Description of what the program does, in terms of
                 inputs and output — sufficient for a function
                 declaration and docstring.
     Example: Function call with arguments, and expected result.
              abs(-1) → 1
              abs(1) → 1
    Definition: The code!
          Tests: Convert the example to actual code — by running
                 the program on it.
    2
        http://htdp.org/2003-09-26/Book/curriculum-Z-H-1.html
                                  Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Example: Counting words in text


     Given a sample text, count the frequencies of each word.

      Name: wordcount
       Input: A string of text.
     Output: A dictionary, with string keys and integers values.




                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Example: Counting words in text


      Given a sample text, count the frequencies of each word.

       Name: wordcount
       Input: A string of text.
     Output: A dictionary, with string keys and integers values.
     Purpose: Create a dictionary associating each unique word in
              the text with the number of times it appears.




                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Example: Counting words in text


      Given a sample text, count the frequencies of each word.

       Name: wordcount
       Input: A string of text.
     Output: A dictionary, with string keys and integers values.
     Purpose: Create a dictionary associating each unique word in
              the text with the number of times it appears.
    Example: wordcount("yes no yes no maybe")
             → {’yes’: 2, ’no’: 2, ’maybe’: 1}




                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces



def w o r d c o u n t ( t e x t ) :
    ””” Count t h e o c c u r e n c e s o f e a c h word i n t e x t .

     I n p u t : s t r i n g o f w h i t e s p a c e −d e l i m i t e d words
     Output : d i c t o f s t r i n g s and i n t e g e r s ( >0)
     Example :
            >>> w o r d c o u n t ( ” y e s no y e s no maybe ” )
             { ’ maybe ’ : 1 , ’ y e s ’ : 2 , ’ no ’ : 2}
     ”””
     w o r d c o u n t s = {}
     f o r word i n t e x t . s p l i t ( ) :
             i f word not i n w o r d c o u n t s :
                    # New word ; s t a r t c o u n t i n g from 0
                    w o r d c o u n t s [ word ] = 0
             w o r d c o u n t s [ word ] += 1
     return word counts



                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
      How to design programs     Algorithms
Python concepts & party tricks   Interfaces




           Snack Time




                 Eric Talevich   Python Workshop 2012
Getting started   Data structures
      How to design programs     Algorithms
Python concepts & party tricks   Interfaces




                   Interfaces
              Interact with the world




                 Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces


Modules

  Think of a module as a bundle of features. When you import a
  module, you load an additional set of features that your program
  can use.

       >>>   import this
       >>>   type(this)
       >>>   help(this)
       >>>   dir(this)

  A module may also be called a “package” or “library”, or possibly
  “API”. (It’s nuanced.)
  Python has many built-in modules. Together, these are called
  the “standard library”.

                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Built-in I/O functions

  You may already know:

         print Write a line to the command-line interface.
              >>> print ’Eureka!’
              Eureka!




                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Built-in I/O functions

  You may already know:

         print Write a line to the command-line interface.
              >>> print ’Eureka!’
              Eureka!

    raw input Read a line from the command-line interface.
              >>> name = raw input(’Name: ’)
              Name: Jonas
              >>> print ’My name is’, name
              My name is Jonas


                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces


The sys module

  print and raw input are wrappers for standard output and
  standard input:

                                     import sys

    sys.stdout File handle for writing to the program’s output.
               >>> sys.stdout.write(’Eureka!n’)
               Eureka!




                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces


The sys module

  print and raw input are wrappers for standard output and
  standard input:

                                     import sys

    sys.stdout File handle for writing to the program’s output.
               >>> sys.stdout.write(’Eureka!n’)
               Eureka!
     sys.stdin File handle for reading from the program’s input.
               >>> sys.stdout.write(’Name: ’); 
               ... name = sys.stdin.readline()
               Name: Jonas
               >>> sys.stdout.write(’My name is ’ + name)
               My name is Jonas

                                Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Program arguments


  Command-line arguments are stored in sys.argv:
      cat hi.py
      #!/usr/bin/env python
      print ’Hello, Athens!’




                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Program arguments


  Command-line arguments are stored in sys.argv:
      cat hi.py
      #!/usr/bin/env python
      print ’Hello, Athens!’
      echo ’Some text’ > example.txt




                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                    How to design programs     Algorithms
              Python concepts & party tricks   Interfaces


Program arguments


  Command-line arguments are stored in sys.argv:
      cat hi.py
      #!/usr/bin/env python
      print ’Hello, Athens!’
      echo ’Some text’ > example.txt
      python hi.py example.txt
      >>> import sys
      >>> print sys.argv
      [’hi.py’, ’example.txt’]




                               Eric Talevich   Python Workshop 2012
Getting started   Data structures
                     How to design programs     Algorithms
               Python concepts & party tricks   Interfaces


More types of interfaces



      Pipelines (sys.stdin/stdout/stderr)
      API — calling functions from other programs & libraries
      IPC — inter-process communication (shm, subprocess)
      GUI widgets
      Web forms & Javascript events

  (Don’t worry about the details here. Just keep this stuff separate
  from the main algorithm if you encounter it.)




                                Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                    How to design programs     Iteration
              Python concepts & party tricks   The csv module


What is a file?



  Consider:
      A local file larger than available RAM
      Reading data over an internet connection


     Problem: Data can’t be viewed all at once
     Solution: Retrieve bytes on demand




                               Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                     How to design programs     Iteration
               Python concepts & party tricks   The csv module


File handles



  A handle points to a location in a byte stream (e.g. the first byte
  of the file to be read/written).

         >>> myfile = open(’example.txt’)
         >>> print myfile.read()
         >>> myfile.seek(0)
         >>> print myfile.readlines()
         >>> myfile.close()




                                Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                    How to design programs     Iteration
              Python concepts & party tricks   The csv module


File-like objects



      Text (ASCII or Unicode) file on disk
      Binary file on disk
      Standard input, output, error
      Devices, pretty much everything else on Unix
      Network connection
      Memory map (inter-process communication)
      Any Python object supporting the right methods (e.g.
      StringIO)




                               Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                     How to design programs     Iteration
               Python concepts & party tricks   The csv module


Features of Python file objects

  Modes:
                      infile = open(myfile, ’r’)

      r, w — read, write
      b — binary, to keep Windows from clobbering CR/LF bytes
      U — Unicode

  Iteration:
                            for line in infile:
                                print line.split()


                                Eric Talevich   Python Workshop 2012
Getting started   File-like objects
      How to design programs     Iteration
Python concepts & party tricks   The csv module




                     another short
                     Break




                 Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                       How to design programs     Iteration
                 Python concepts & party tricks   The csv module


Iteration



  Iterable objects “know” how they can be looped over.
  Python has functions that operate on each item in an iterable:

    “for” loop: for x in iterable : ...
            zip: for left , right in zip ( iter1 , iter2 ): ...
   enumerate: for index , x in enumerate( iterable ): ...
  List comprehension: [x ∗ x for x in range(20) if x % 2 == 0]




                                  Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                     How to design programs     Iteration
               Python concepts & party tricks   The csv module


Example: Counting words in a file

      Count the words in a file, and print a table sorted by
      word frequency.
  Let’s expand the wordcount function into a complete script.
      Separate algorithms from interfaces
      Don’t do any I/O inside wordcount.
      Independent output formatting
      Use a separate function to print the dictionary wordcount
      produces.
      Flexible file input
      Take a file name as a program argument, or read from
      standard input.


                                Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                     How to design programs     Iteration
               Python concepts & party tricks   The csv module


Enhancing wordcount


   1   Read from an open file handle, not a string
       Don’t worry about opening or closing it here:
       def count words(infile): ...




                                Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                     How to design programs     Iteration
               Python concepts & party tricks   The csv module


Enhancing wordcount


   1   Read from an open file handle, not a string
       Don’t worry about opening or closing it here:
       def count words(infile): ...
   2   Remove punctuation, ignore case when counting words
       str.strip and str.lower will work — but could make ’’




                                Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                     How to design programs     Iteration
               Python concepts & party tricks   The csv module


Enhancing wordcount


   1   Read from an open file handle, not a string
       Don’t worry about opening or closing it here:
       def count words(infile): ...
   2   Remove punctuation, ignore case when counting words
       str.strip and str.lower will work — but could make ’’
   3   Save a line of code with collections.defaultdict
       Write what we want more directly:
       >>> counts = collections.defaultdict(int)
       >>> counts[’new’]
       0



                                Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                      How to design programs     Iteration
                Python concepts & party tricks   The csv module

import c o l l e c t i o n s

def c o u n t w o r d s ( i n f i l e ) :
    ””” Count o c c u r r e n c e s o f e a c h word i n i n f i l e .
    I n p u t : F i l e h a n d l e open f o r r e a d i n g
    Output : d i c t o f { s t r i n g : i n t e g e r }
    Example : ( i n f i l e c o n t a i n s ” y e s no y e s no maybe ” )
           >>> c o u n t w o r d s ( i n f i l e )
            { ’ maybe ’ : 1 , ’ y e s ’ : 2 , ’ no ’ : 2}
    ”””
    w counts = c o l l e c t i o n s . d e f a u l t d i c t ( i n t )
    for l i n e in i n f i l e :
            f o r word i n l i n e . s p l i t ( ) :
                  # I g n o r e c a s e and a d j a c e n t p u n c t u a t i o n
                  word = word . s t r i p ( ’ ,.;:?! -()" ’ ’ ) . l o w e r ( )
                  w c o u n t s [ word ] += 1
    return w counts



                                 Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                     How to design programs     Iteration
               Python concepts & party tricks   The csv module


Output formatting

  Given the dictionary produced by count words . . .
    1   Sort entries by counts, in descending order
        Use the key argument to select values for comparison:
        >>> pairs = [(’one’,1), (’three’,3), (’two’,2)]
        >>> select second = lambda x: x[1]
        >>> pairs.sort(key=select second); print pairs
        [(’one’, 1), (’two’, 2), (’three’, 3)]




                                Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                      How to design programs     Iteration
                Python concepts & party tricks   The csv module


Output formatting

  Given the dictionary produced by count words . . .
    1   Sort entries by counts, in descending order
        Use the key argument to select values for comparison:
        >>> pairs = [(’one’,1), (’three’,3), (’two’,2)]
        >>> select second = lambda x: x[1]
        >>> pairs.sort(key=select second); print pairs
        [(’one’, 1), (’two’, 2), (’three’, 3)]
    2   Justify the printed words in a fixed-with column
        Use the length of the longest word as the column width.
        >>> words = ’thanks for all the fish’.split()’
        >>> max(len(word) for word in words)
        6


                                 Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                      How to design programs     Iteration
                Python concepts & party tricks   The csv module



def p r i n t d i c t i o n a r y ( d c t ) :
    ””” P r i n t t h e k e y s and v a l u e s i n d c t .

      S o r t s i t e m s by d e c r e a s i n g v a l u e ; l i n e s up c o l u m n s .

     I n p u t : d i c t w i t h s t r i n g k e y s and any−t y p e v a l u e s
     ”””
     # Width n e e d e d f o r d i s p l a y i n g t h e k e y column
     k e y w i d t h = max ( l e n ( k e y ) f o r k e y i n d c t )
     k v p a i r s = dct . items ()
     # S o r t by t h e s e c o n d i t e m i n t h e p a i r , d e c r e a s i n g
     k v p a i r s . s o r t ( k e y=lambda kv : kv [ 1 ] , r e v e r s e=True )
     f o r key , v a l u e i n k v p a i r s :
            # A l i g n both columns a g a i n s t a s t r i p o f t a b s
             p r i n t k e y . r j u s t ( k e y w i d t h ) , ’t’ , v a l u e




                                 Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                      How to design programs     Iteration
                Python concepts & party tricks   The csv module


File I/O and scaffolding

  Let’s put it all together.
    1   Document usage at the top of the script
        Several ways to view this: pydoc, help, doc




                                 Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                      How to design programs     Iteration
                Python concepts & party tricks   The csv module


File I/O and scaffolding

  Let’s put it all together.
    1   Document usage at the top of the script
        Several ways to view this: pydoc, help, doc
    2   Check the given program arguments
            If none: read from standard input
            If one: open the file and read it
            Otherwise: print a helpful error message




                                 Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                      How to design programs     Iteration
                Python concepts & party tricks   The csv module


File I/O and scaffolding

  Let’s put it all together.
    1   Document usage at the top of the script
        Several ways to view this: pydoc, help, doc
    2   Check the given program arguments
            If none: read from standard input
            If one: open the file and read it
            Otherwise: print a helpful error message
    3   Exit with proper Unix return codes
        Use sys.exit: 0 means OK, otherwise error
        $ python -c ’import sys; sys.exit(1)’ && echo OK
        $ python -c ’import sys; sys.exit()’ && echo OK
        OK


                                 Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                       How to design programs     Iteration
                 Python concepts & party tricks   The csv module

#! / u s r / b i n / env p y t h o n

””” Count t h e words i n a t e x t f i l e o r str eam , and
p r i n t a t a b l e o f word c o u n t s s o r t e d by f r e q u e n c y .

Usage :
    w o r d c o u n t . py [ f i l e n a m e ]
”””

import s y s
import c o l l e c t i o n s

def c o u n t w o r d s ( i n f i l e ) :
    ...

def p r i n t d i c t i o n a r y ( d c t ) :
    ...



                                  Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                    How to design programs     Iteration
              Python concepts & party tricks   The csv module



if    name         == ’__main__ ’ :
     i f l e n ( s y s . a r g v ) == 1 :
            # Text s t r e a m i n p u t , e . g . from a p i p e
            i n f i l e = sys . stdin
     e l i f l e n ( s y s . a r g v ) == 2 :
            # Read t e x t from t h e g i v e n f i l e
            i n f i l e = open ( s y s . a r g v [ 1 ] , ’r’ )
     else :
            # Too many a r g u m e n t s ! P r i n t u s a g e & q u i t
            sys . exit ( doc )

     # Now , do e v e r y t h i n g
     word counts = count words ( i n f i l e )
     p r i n t d i c t i o n a r y ( word counts )




                               Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                        How to design programs     Iteration
                  Python concepts & party tricks   The csv module


CSV: Comma Separated Values


  Python can read and write spreadsheet files in CSV format.               3

  (It’s handy if you don’t have a database set up.)

                              KEY         one      three       five
                              two          2         6         10
                              four         4        12         20
                               six         6        18         30

  Let’s convert this to a dictionary-of-dictionaries in Python — the
  outer dictionary is keyed by the row labels (from the KEY column),
  and the inner dictionary is the row data, keyed by column label.


    3
        Conversions seem to be easier in OpenOffice/LibreOffice Calc than in Excel.
                                   Eric Talevich   Python Workshop 2012
Getting started     File-like objects
                       How to design programs       Iteration
                 Python concepts & party tricks     The csv module

# Save t h e p r e v i o u s t a b l e a s ’ m t a b l e . c s v ’
# Here , we c o n v e r t i t t o a d i c t −of −d i c t s
import c s v
i n f i l e = open ( ’mtable .csv ’ )
csvreader = csv . DictReader ( i n f i l e )
t a b l e = {}
fo r rowdata in c s v r e a d e r :
        k e y = r o w d a t a . pop ( ’KEY ’ )
        t a b l e [ key ] = rowdata

# P r e t t y −p r i n t t a b l e w i t h         n i c e l y a l i g n e d rows
from p p r i n t import p p r i n t
pprint ( table )
# { ’ four ’: { ’ f i v e ’: ’20 ’ ,                ’ one ’ : ’ 4 ’ , ’ t h r e e ’ : ’ 1 2 ’ } ,
# ’ s i x ’: { ’ f i v e ’: ’30 ’ ,               ’ one ’ : ’ 6 ’ , ’ t h r e e ’ : ’ 1 8 ’ } ,
# ’ two ’ : { ’ f i v e ’ : ’ 1 0 ’ ,             ’ one ’ : ’ 2 ’ , ’ t h r e e ’ : ’ 6 ’ } }

p r i n t t a b l e [ ’four ’ ] [ ’five ’ ]               # ’20 ’


                                  Eric Talevich     Python Workshop 2012
Getting started   File-like objects
      How to design programs     Iteration
Python concepts & party tricks   The csv module




                    Thanks
                      ’Preciate it.
                           Gracias




                 Eric Talevich   Python Workshop 2012
Getting started   File-like objects
                     How to design programs     Iteration
               Python concepts & party tricks   The csv module


Further reading


  The official Python tutorial is quite good:
  http://docs.python.org/tutorial/index.html


  This is the book I recommend for learning Python:
  http://learnpythonthehardway.org/


  This presentation on Slideshare, and the example script on GitHub:
  http://www.slideshare.net/etalevich/
  python-workshop-1-uga-bioinformatics
  https://gist.github.com/661869



                                Eric Talevich   Python Workshop 2012

Mais conteúdo relacionado

Mais procurados

Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundationKevlin Henney
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| FundamentalsMohd Sajjad
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid DeconstructionKevlin Henney
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programmingSrinivas Narasegouda
 
Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)IoT Code Lab
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming LanguageTahani Al-Manie
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python ProgrammingKamal Acharya
 
R and Python, A Code Demo
R and Python, A Code DemoR and Python, A Code Demo
R and Python, A Code DemoVineet Jaiswal
 
PYTHON NOTES
PYTHON NOTESPYTHON NOTES
PYTHON NOTESNi
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programsJames Brotsos
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answersRojaPriya
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Ranel Padon
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019Samir Mohanty
 
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Edureka!
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to PythonNowell Strite
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way PresentationAmira ElSharkawy
 

Mais procurados (20)

Python Advanced – Building on the foundation
Python Advanced – Building on the foundationPython Advanced – Building on the foundation
Python Advanced – Building on the foundation
 
Python-01| Fundamentals
Python-01| FundamentalsPython-01| Fundamentals
Python-01| Fundamentals
 
Solid Deconstruction
Solid DeconstructionSolid Deconstruction
Solid Deconstruction
 
Python Tutorial Part 1
Python Tutorial Part 1Python Tutorial Part 1
Python Tutorial Part 1
 
Introduction to python programming
Introduction to python programmingIntroduction to python programming
Introduction to python programming
 
Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)Chapter 0 Python Overview (Python Programming Lecture)
Chapter 0 Python Overview (Python Programming Lecture)
 
Python 3 Programming Language
Python 3 Programming LanguagePython 3 Programming Language
Python 3 Programming Language
 
Fundamentals of Python Programming
Fundamentals of Python ProgrammingFundamentals of Python Programming
Fundamentals of Python Programming
 
R and Python, A Code Demo
R and Python, A Code DemoR and Python, A Code Demo
R and Python, A Code Demo
 
PYTHON NOTES
PYTHON NOTESPYTHON NOTES
PYTHON NOTES
 
Chapter 03 python libraries
Chapter 03 python librariesChapter 03 python libraries
Chapter 03 python libraries
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 
Ch01 basic-java-programs
Ch01 basic-java-programsCh01 basic-java-programs
Ch01 basic-java-programs
 
Python interview questions and answers
Python interview questions and answersPython interview questions and answers
Python interview questions and answers
 
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
Python Programming - IV. Program Components (Functions, Classes, Modules, Pac...
 
Overview of python 2019
Overview of python 2019Overview of python 2019
Overview of python 2019
 
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
Python Tutorial For Beginners | Python Crash Course - Python Programming Lang...
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Introduction to Python
Introduction to PythonIntroduction to Python
Introduction to Python
 
Learn Python The Hard Way Presentation
Learn Python The Hard Way PresentationLearn Python The Hard Way Presentation
Learn Python The Hard Way Presentation
 

Destaque (6)

Besut Kode - Workshop 1
Besut Kode - Workshop 1Besut Kode - Workshop 1
Besut Kode - Workshop 1
 
Ap GoPo One Day Workshop
Ap GoPo One Day WorkshopAp GoPo One Day Workshop
Ap GoPo One Day Workshop
 
Media
MediaMedia
Media
 
APSI Day One Welcome
APSI Day One WelcomeAPSI Day One Welcome
APSI Day One Welcome
 
VC Workshop - one day
VC Workshop -  one dayVC Workshop -  one day
VC Workshop - one day
 
Social media training workshop – Day 1
Social media training workshop – Day 1Social media training workshop – Day 1
Social media training workshop – Day 1
 

Semelhante a Python workshop #1 at UGA

Python For Scientists
Python For ScientistsPython For Scientists
Python For Scientistsaeberspaecher
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experiencedzynofustechnology
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughgabriellekuruvilla
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdfsamiwaris2
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfExaminationSectionMR
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data sciencedeepak teja
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonRanjith kumar
 
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...DRVaibhavmeshram1
 
Python programming
Python programmingPython programming
Python programmingsaroja20
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1Abdul Haseeb
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxsushil155005
 
python presentation
python presentationpython presentation
python presentationVaibhavMawal
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txvishwanathgoudapatil1
 
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON Nandakumar P
 

Semelhante a Python workshop #1 at UGA (20)

Learn python
Learn pythonLearn python
Learn python
 
MODULE 1.pptx
MODULE 1.pptxMODULE 1.pptx
MODULE 1.pptx
 
Python For Scientists
Python For ScientistsPython For Scientists
Python For Scientists
 
Python Interview Questions For Experienced
Python Interview Questions For ExperiencedPython Interview Questions For Experienced
Python Interview Questions For Experienced
 
Python and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthroughPython and Pytorch tutorial and walkthrough
Python and Pytorch tutorial and walkthrough
 
Python (3).pdf
Python (3).pdfPython (3).pdf
Python (3).pdf
 
Interview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdfInterview-level-QA-on-Python-Programming.pdf
Interview-level-QA-on-Python-Programming.pdf
 
Python_intro.ppt
Python_intro.pptPython_intro.ppt
Python_intro.ppt
 
Python introduction towards data science
Python introduction towards data sciencePython introduction towards data science
Python introduction towards data science
 
Using Parallel Computing Platform - NHDNUG
Using Parallel Computing Platform - NHDNUGUsing Parallel Computing Platform - NHDNUG
Using Parallel Computing Platform - NHDNUG
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
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 programming
Python programmingPython programming
Python programming
 
Python programming workshop session 1
Python programming workshop session 1Python programming workshop session 1
Python programming workshop session 1
 
Python PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptxPython PPT by Sushil Sir.pptx
Python PPT by Sushil Sir.pptx
 
python presentation
python presentationpython presentation
python presentation
 
Python Workshop
Python WorkshopPython Workshop
Python Workshop
 
Python_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. txPython_Haegl.powerpoint presentation. tx
Python_Haegl.powerpoint presentation. tx
 
CPPDS Slide.pdf
CPPDS Slide.pdfCPPDS Slide.pdf
CPPDS Slide.pdf
 
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
 

Último

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024The Digital Insurer
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbuapidays
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Jeffrey Haguewood
 

Último (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

Python workshop #1 at UGA

  • 1. Getting started How to design programs Python concepts & party tricks Python Workshop 2012 The essentials: getting started, program design, modules & I/O Eric Talevich Institute of Bioinformatics, University of Georgia Nov. 8, 2012 Eric Talevich Python Workshop 2012
  • 2. Getting started How to design programs Python concepts & party tricks 1 Getting started 2 How to design programs Data structures Algorithms Interfaces 3 Python concepts & party tricks File-like objects Iteration The csv module Eric Talevich Python Workshop 2012
  • 3. Getting started How to design programs Python concepts & party tricks Getting started: Interpreter Your interactive interpreter is one of: python on the command line IDLE — Integrated DeveLopment Environment for Python 1 We’ll use IDLE. Run this in the interpreter: import this 1 Included in the standard Python installation on Windows and Mac Eric Talevich Python Workshop 2012
  • 4. Getting started How to design programs Python concepts & party tricks Getting started: Scripts 1 Write this in a new, blank text file: print "Hello, Athens!" Eric Talevich Python Workshop 2012
  • 5. Getting started How to design programs Python concepts & party tricks Getting started: Scripts 1 Write this in a new, blank text file: print "Hello, Athens!" 2 Save it in plain-text format with the name hi.py in the same directory as your interpreter session is running. Run it: python hi.py Eric Talevich Python Workshop 2012
  • 6. Getting started How to design programs Python concepts & party tricks Getting started: Scripts 1 Write this in a new, blank text file: print "Hello, Athens!" 2 Save it in plain-text format with the name hi.py in the same directory as your interpreter session is running. Run it: python hi.py A CREDIT Add a line at the top of hi.py to tell Unix this is a Python script: #!/usr/bin/env python Make hi.py executable (from the terminal shell): chmod +x hi.py Now you don’t need the .py extension: mv hi.py hi ./hi Eric Talevich Python Workshop 2012
  • 7. Getting started How to design programs Python concepts & party tricks Getting started: Documentation In the interpreter: help(function-or-module ) On the command line: pydoc function-or-module In IDLE: <F1> (launches docs.python.org) Also, type(obj ), dir(obj ), vars(obj ) and auto-completion (tab or Ctrl+Space) are pretty handy. Try it: >>> help(str) >>> s = ’Hello’ >>> type(s) >>> dir(s) >>> help(s.capitalize) >>> help(help) Eric Talevich Python Workshop 2012
  • 8. Getting started How to design programs Python concepts & party tricks Example: string methods Find the string (str) methods to. . . Convert gOoFy-cAsE words to title case, upper case or lower case Remove certain characters from either end Align (justify) within a fixed width, padded by spaces Eric Talevich Python Workshop 2012
  • 9. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces How to design programs Data structure: Organizes a collection of data units Algorithm: Defines operations for a specific task Interface: I/O, how a program interacts with the world Theorem Program = Data Structures + Algorithms + Interfaces Eric Talevich Python Workshop 2012
  • 10. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Data structures Organize a program’s information Eric Talevich Python Workshop 2012
  • 11. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Units of data: Atoms Class int float bool — str Literal 1, -2 .1, 2.9e8 True, False None ’abc’ Try it: >>> num = 0.000000002 >>> num >>> type(num) Features: Create from a data literal or by calling the class name (constructor) Always immutable — assigning another value replaces the original object Eric Talevich Python Workshop 2012
  • 12. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Collections of data Class Literal Description list [] Ordered array of arbitrary objects dict {} Unordered map of fixed to arbitrary objects set Unordered collection of fixed objects Eric Talevich Python Workshop 2012
  • 13. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Mutable vs. immutable objects Some mutable objects have immutable counterparts: list vs. tuple set vs. frozenset >>> x = (1, 2, 3) >>> x[0] = 7 >>> y = list(x) >>> y[0] = 7 >>> print y Eric Talevich Python Workshop 2012
  • 14. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Variables are names, not values Mutable collections can be shared: >>> x = [1, 2, 3] >>> y = x >>> y[0] = 4 >>> x is y >>> print ’x =’, x, ’y =’, y Reassigning to an immutable object replaces (changes the id of) the original: >>> x = (1, 2, 3) >>> y = x >>> y = (4, 2, 3) >>> x is y >>> print ’x =’, x, ’y =’, y Eric Talevich Python Workshop 2012
  • 15. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces a fairly short Break Eric Talevich Python Workshop 2012
  • 16. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Algorithms Specify operations Eric Talevich Python Workshop 2012
  • 17. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Control flow Branching The if statement chooses between code paths: x = -2 if x >= 0: print x, "is positive" else: print x, "was negative" x = -x Eric Talevich Python Workshop 2012
  • 18. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Control flow Branching The if statement chooses between code paths: x = -2 if x >= 0: print x, "is positive" else: print x, "was negative" x = -x Iteration The for statement visits each element sequentially: for x in [-2, -1, 0, 1, 2]: if x >= 0: print x, "is positive" Eric Talevich Python Workshop 2012
  • 19. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces # Define a function # −−−−−−−−−−−−−−−−− # T h i s e x a m p l e shows how t o d e f i n e a s i m p l e f u n c t i o n . # The f u n c t i o n d e f i n i t i o n s t a r t s w i t h keyword ’ d e f ’ , # t h e n t h e name o f t h e f u n c t i o n and t h e a r g u m e n t s . # The ’ d o c s t r i n g ’ i n q u o t e s i s o p t i o n a l , b u t n i c e . # The r e s t o f t h e code , i n d e n t e d , i s t h e f u n c t i o n body . # # ( L i n e s t h a t b e g i n w i t h a h a s h (#) a r e comments . ) def n i c e a b s ( x ) : ””” R e t u r n t h e a b s o l u t e v a l u e o f a number . ””” i f x < 0: r e t u r n −x else : return x Eric Talevich Python Workshop 2012
  • 20. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Algorithms Definition: A precise set of instructions for accomplishing a task. We’ll treat an algorithm as one or more functions that operate on some input data to produce some output according to a specification. Useful fact: The structure of a function will resemble the structure of the data it operates on. Eric Talevich Python Workshop 2012
  • 21. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces The design recipe: a general method Steps, in order, for developing a program from scratch: 2 Contract: Name the function; specify the types (i.e. atoms and data structures) of its input data and its output. abs: number → positive number 2 http://htdp.org/2003-09-26/Book/curriculum-Z-H-1.html Eric Talevich Python Workshop 2012
  • 22. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces The design recipe: a general method Steps, in order, for developing a program from scratch: 2 Contract: Name the function; specify the types (i.e. atoms and data structures) of its input data and its output. abs: number → positive number Purpose: Description of what the program does, in terms of inputs and output — sufficient for a function declaration and docstring. 2 http://htdp.org/2003-09-26/Book/curriculum-Z-H-1.html Eric Talevich Python Workshop 2012
  • 23. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces The design recipe: a general method Steps, in order, for developing a program from scratch: 2 Contract: Name the function; specify the types (i.e. atoms and data structures) of its input data and its output. abs: number → positive number Purpose: Description of what the program does, in terms of inputs and output — sufficient for a function declaration and docstring. Example: Function call with arguments, and expected result. abs(-1) → 1 abs(1) → 1 2 http://htdp.org/2003-09-26/Book/curriculum-Z-H-1.html Eric Talevich Python Workshop 2012
  • 24. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces The design recipe: a general method Steps, in order, for developing a program from scratch: 2 Contract: Name the function; specify the types (i.e. atoms and data structures) of its input data and its output. abs: number → positive number Purpose: Description of what the program does, in terms of inputs and output — sufficient for a function declaration and docstring. Example: Function call with arguments, and expected result. abs(-1) → 1 abs(1) → 1 Definition: The code! Tests: Convert the example to actual code — by running the program on it. 2 http://htdp.org/2003-09-26/Book/curriculum-Z-H-1.html Eric Talevich Python Workshop 2012
  • 25. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Example: Counting words in text Given a sample text, count the frequencies of each word. Name: wordcount Input: A string of text. Output: A dictionary, with string keys and integers values. Eric Talevich Python Workshop 2012
  • 26. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Example: Counting words in text Given a sample text, count the frequencies of each word. Name: wordcount Input: A string of text. Output: A dictionary, with string keys and integers values. Purpose: Create a dictionary associating each unique word in the text with the number of times it appears. Eric Talevich Python Workshop 2012
  • 27. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Example: Counting words in text Given a sample text, count the frequencies of each word. Name: wordcount Input: A string of text. Output: A dictionary, with string keys and integers values. Purpose: Create a dictionary associating each unique word in the text with the number of times it appears. Example: wordcount("yes no yes no maybe") → {’yes’: 2, ’no’: 2, ’maybe’: 1} Eric Talevich Python Workshop 2012
  • 28. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces def w o r d c o u n t ( t e x t ) : ””” Count t h e o c c u r e n c e s o f e a c h word i n t e x t . I n p u t : s t r i n g o f w h i t e s p a c e −d e l i m i t e d words Output : d i c t o f s t r i n g s and i n t e g e r s ( >0) Example : >>> w o r d c o u n t ( ” y e s no y e s no maybe ” ) { ’ maybe ’ : 1 , ’ y e s ’ : 2 , ’ no ’ : 2} ””” w o r d c o u n t s = {} f o r word i n t e x t . s p l i t ( ) : i f word not i n w o r d c o u n t s : # New word ; s t a r t c o u n t i n g from 0 w o r d c o u n t s [ word ] = 0 w o r d c o u n t s [ word ] += 1 return word counts Eric Talevich Python Workshop 2012
  • 29. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Snack Time Eric Talevich Python Workshop 2012
  • 30. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Interfaces Interact with the world Eric Talevich Python Workshop 2012
  • 31. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Modules Think of a module as a bundle of features. When you import a module, you load an additional set of features that your program can use. >>> import this >>> type(this) >>> help(this) >>> dir(this) A module may also be called a “package” or “library”, or possibly “API”. (It’s nuanced.) Python has many built-in modules. Together, these are called the “standard library”. Eric Talevich Python Workshop 2012
  • 32. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Built-in I/O functions You may already know: print Write a line to the command-line interface. >>> print ’Eureka!’ Eureka! Eric Talevich Python Workshop 2012
  • 33. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Built-in I/O functions You may already know: print Write a line to the command-line interface. >>> print ’Eureka!’ Eureka! raw input Read a line from the command-line interface. >>> name = raw input(’Name: ’) Name: Jonas >>> print ’My name is’, name My name is Jonas Eric Talevich Python Workshop 2012
  • 34. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces The sys module print and raw input are wrappers for standard output and standard input: import sys sys.stdout File handle for writing to the program’s output. >>> sys.stdout.write(’Eureka!n’) Eureka! Eric Talevich Python Workshop 2012
  • 35. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces The sys module print and raw input are wrappers for standard output and standard input: import sys sys.stdout File handle for writing to the program’s output. >>> sys.stdout.write(’Eureka!n’) Eureka! sys.stdin File handle for reading from the program’s input. >>> sys.stdout.write(’Name: ’); ... name = sys.stdin.readline() Name: Jonas >>> sys.stdout.write(’My name is ’ + name) My name is Jonas Eric Talevich Python Workshop 2012
  • 36. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Program arguments Command-line arguments are stored in sys.argv: cat hi.py #!/usr/bin/env python print ’Hello, Athens!’ Eric Talevich Python Workshop 2012
  • 37. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Program arguments Command-line arguments are stored in sys.argv: cat hi.py #!/usr/bin/env python print ’Hello, Athens!’ echo ’Some text’ > example.txt Eric Talevich Python Workshop 2012
  • 38. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces Program arguments Command-line arguments are stored in sys.argv: cat hi.py #!/usr/bin/env python print ’Hello, Athens!’ echo ’Some text’ > example.txt python hi.py example.txt >>> import sys >>> print sys.argv [’hi.py’, ’example.txt’] Eric Talevich Python Workshop 2012
  • 39. Getting started Data structures How to design programs Algorithms Python concepts & party tricks Interfaces More types of interfaces Pipelines (sys.stdin/stdout/stderr) API — calling functions from other programs & libraries IPC — inter-process communication (shm, subprocess) GUI widgets Web forms & Javascript events (Don’t worry about the details here. Just keep this stuff separate from the main algorithm if you encounter it.) Eric Talevich Python Workshop 2012
  • 40. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module What is a file? Consider: A local file larger than available RAM Reading data over an internet connection Problem: Data can’t be viewed all at once Solution: Retrieve bytes on demand Eric Talevich Python Workshop 2012
  • 41. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module File handles A handle points to a location in a byte stream (e.g. the first byte of the file to be read/written). >>> myfile = open(’example.txt’) >>> print myfile.read() >>> myfile.seek(0) >>> print myfile.readlines() >>> myfile.close() Eric Talevich Python Workshop 2012
  • 42. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module File-like objects Text (ASCII or Unicode) file on disk Binary file on disk Standard input, output, error Devices, pretty much everything else on Unix Network connection Memory map (inter-process communication) Any Python object supporting the right methods (e.g. StringIO) Eric Talevich Python Workshop 2012
  • 43. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Features of Python file objects Modes: infile = open(myfile, ’r’) r, w — read, write b — binary, to keep Windows from clobbering CR/LF bytes U — Unicode Iteration: for line in infile: print line.split() Eric Talevich Python Workshop 2012
  • 44. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module another short Break Eric Talevich Python Workshop 2012
  • 45. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Iteration Iterable objects “know” how they can be looped over. Python has functions that operate on each item in an iterable: “for” loop: for x in iterable : ... zip: for left , right in zip ( iter1 , iter2 ): ... enumerate: for index , x in enumerate( iterable ): ... List comprehension: [x ∗ x for x in range(20) if x % 2 == 0] Eric Talevich Python Workshop 2012
  • 46. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Example: Counting words in a file Count the words in a file, and print a table sorted by word frequency. Let’s expand the wordcount function into a complete script. Separate algorithms from interfaces Don’t do any I/O inside wordcount. Independent output formatting Use a separate function to print the dictionary wordcount produces. Flexible file input Take a file name as a program argument, or read from standard input. Eric Talevich Python Workshop 2012
  • 47. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Enhancing wordcount 1 Read from an open file handle, not a string Don’t worry about opening or closing it here: def count words(infile): ... Eric Talevich Python Workshop 2012
  • 48. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Enhancing wordcount 1 Read from an open file handle, not a string Don’t worry about opening or closing it here: def count words(infile): ... 2 Remove punctuation, ignore case when counting words str.strip and str.lower will work — but could make ’’ Eric Talevich Python Workshop 2012
  • 49. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Enhancing wordcount 1 Read from an open file handle, not a string Don’t worry about opening or closing it here: def count words(infile): ... 2 Remove punctuation, ignore case when counting words str.strip and str.lower will work — but could make ’’ 3 Save a line of code with collections.defaultdict Write what we want more directly: >>> counts = collections.defaultdict(int) >>> counts[’new’] 0 Eric Talevich Python Workshop 2012
  • 50. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module import c o l l e c t i o n s def c o u n t w o r d s ( i n f i l e ) : ””” Count o c c u r r e n c e s o f e a c h word i n i n f i l e . I n p u t : F i l e h a n d l e open f o r r e a d i n g Output : d i c t o f { s t r i n g : i n t e g e r } Example : ( i n f i l e c o n t a i n s ” y e s no y e s no maybe ” ) >>> c o u n t w o r d s ( i n f i l e ) { ’ maybe ’ : 1 , ’ y e s ’ : 2 , ’ no ’ : 2} ””” w counts = c o l l e c t i o n s . d e f a u l t d i c t ( i n t ) for l i n e in i n f i l e : f o r word i n l i n e . s p l i t ( ) : # I g n o r e c a s e and a d j a c e n t p u n c t u a t i o n word = word . s t r i p ( ’ ,.;:?! -()" ’ ’ ) . l o w e r ( ) w c o u n t s [ word ] += 1 return w counts Eric Talevich Python Workshop 2012
  • 51. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Output formatting Given the dictionary produced by count words . . . 1 Sort entries by counts, in descending order Use the key argument to select values for comparison: >>> pairs = [(’one’,1), (’three’,3), (’two’,2)] >>> select second = lambda x: x[1] >>> pairs.sort(key=select second); print pairs [(’one’, 1), (’two’, 2), (’three’, 3)] Eric Talevich Python Workshop 2012
  • 52. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Output formatting Given the dictionary produced by count words . . . 1 Sort entries by counts, in descending order Use the key argument to select values for comparison: >>> pairs = [(’one’,1), (’three’,3), (’two’,2)] >>> select second = lambda x: x[1] >>> pairs.sort(key=select second); print pairs [(’one’, 1), (’two’, 2), (’three’, 3)] 2 Justify the printed words in a fixed-with column Use the length of the longest word as the column width. >>> words = ’thanks for all the fish’.split()’ >>> max(len(word) for word in words) 6 Eric Talevich Python Workshop 2012
  • 53. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module def p r i n t d i c t i o n a r y ( d c t ) : ””” P r i n t t h e k e y s and v a l u e s i n d c t . S o r t s i t e m s by d e c r e a s i n g v a l u e ; l i n e s up c o l u m n s . I n p u t : d i c t w i t h s t r i n g k e y s and any−t y p e v a l u e s ””” # Width n e e d e d f o r d i s p l a y i n g t h e k e y column k e y w i d t h = max ( l e n ( k e y ) f o r k e y i n d c t ) k v p a i r s = dct . items () # S o r t by t h e s e c o n d i t e m i n t h e p a i r , d e c r e a s i n g k v p a i r s . s o r t ( k e y=lambda kv : kv [ 1 ] , r e v e r s e=True ) f o r key , v a l u e i n k v p a i r s : # A l i g n both columns a g a i n s t a s t r i p o f t a b s p r i n t k e y . r j u s t ( k e y w i d t h ) , ’t’ , v a l u e Eric Talevich Python Workshop 2012
  • 54. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module File I/O and scaffolding Let’s put it all together. 1 Document usage at the top of the script Several ways to view this: pydoc, help, doc Eric Talevich Python Workshop 2012
  • 55. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module File I/O and scaffolding Let’s put it all together. 1 Document usage at the top of the script Several ways to view this: pydoc, help, doc 2 Check the given program arguments If none: read from standard input If one: open the file and read it Otherwise: print a helpful error message Eric Talevich Python Workshop 2012
  • 56. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module File I/O and scaffolding Let’s put it all together. 1 Document usage at the top of the script Several ways to view this: pydoc, help, doc 2 Check the given program arguments If none: read from standard input If one: open the file and read it Otherwise: print a helpful error message 3 Exit with proper Unix return codes Use sys.exit: 0 means OK, otherwise error $ python -c ’import sys; sys.exit(1)’ && echo OK $ python -c ’import sys; sys.exit()’ && echo OK OK Eric Talevich Python Workshop 2012
  • 57. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module #! / u s r / b i n / env p y t h o n ””” Count t h e words i n a t e x t f i l e o r str eam , and p r i n t a t a b l e o f word c o u n t s s o r t e d by f r e q u e n c y . Usage : w o r d c o u n t . py [ f i l e n a m e ] ””” import s y s import c o l l e c t i o n s def c o u n t w o r d s ( i n f i l e ) : ... def p r i n t d i c t i o n a r y ( d c t ) : ... Eric Talevich Python Workshop 2012
  • 58. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module if name == ’__main__ ’ : i f l e n ( s y s . a r g v ) == 1 : # Text s t r e a m i n p u t , e . g . from a p i p e i n f i l e = sys . stdin e l i f l e n ( s y s . a r g v ) == 2 : # Read t e x t from t h e g i v e n f i l e i n f i l e = open ( s y s . a r g v [ 1 ] , ’r’ ) else : # Too many a r g u m e n t s ! P r i n t u s a g e & q u i t sys . exit ( doc ) # Now , do e v e r y t h i n g word counts = count words ( i n f i l e ) p r i n t d i c t i o n a r y ( word counts ) Eric Talevich Python Workshop 2012
  • 59. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module CSV: Comma Separated Values Python can read and write spreadsheet files in CSV format. 3 (It’s handy if you don’t have a database set up.) KEY one three five two 2 6 10 four 4 12 20 six 6 18 30 Let’s convert this to a dictionary-of-dictionaries in Python — the outer dictionary is keyed by the row labels (from the KEY column), and the inner dictionary is the row data, keyed by column label. 3 Conversions seem to be easier in OpenOffice/LibreOffice Calc than in Excel. Eric Talevich Python Workshop 2012
  • 60. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module # Save t h e p r e v i o u s t a b l e a s ’ m t a b l e . c s v ’ # Here , we c o n v e r t i t t o a d i c t −of −d i c t s import c s v i n f i l e = open ( ’mtable .csv ’ ) csvreader = csv . DictReader ( i n f i l e ) t a b l e = {} fo r rowdata in c s v r e a d e r : k e y = r o w d a t a . pop ( ’KEY ’ ) t a b l e [ key ] = rowdata # P r e t t y −p r i n t t a b l e w i t h n i c e l y a l i g n e d rows from p p r i n t import p p r i n t pprint ( table ) # { ’ four ’: { ’ f i v e ’: ’20 ’ , ’ one ’ : ’ 4 ’ , ’ t h r e e ’ : ’ 1 2 ’ } , # ’ s i x ’: { ’ f i v e ’: ’30 ’ , ’ one ’ : ’ 6 ’ , ’ t h r e e ’ : ’ 1 8 ’ } , # ’ two ’ : { ’ f i v e ’ : ’ 1 0 ’ , ’ one ’ : ’ 2 ’ , ’ t h r e e ’ : ’ 6 ’ } } p r i n t t a b l e [ ’four ’ ] [ ’five ’ ] # ’20 ’ Eric Talevich Python Workshop 2012
  • 61. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Thanks ’Preciate it. Gracias Eric Talevich Python Workshop 2012
  • 62. Getting started File-like objects How to design programs Iteration Python concepts & party tricks The csv module Further reading The official Python tutorial is quite good: http://docs.python.org/tutorial/index.html This is the book I recommend for learning Python: http://learnpythonthehardway.org/ This presentation on Slideshare, and the example script on GitHub: http://www.slideshare.net/etalevich/ python-workshop-1-uga-bioinformatics https://gist.github.com/661869 Eric Talevich Python Workshop 2012