Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Python basics guide

Avatar for justasabc justasabc
October 21, 2013

Python basics guide

A quick start to python basics

Avatar for justasabc

justasabc

October 21, 2013

Other Decks in Programming

Transcript

  1. Outline • Basic Structure • Input & Output • Comment

    • Variable • Built-in Type • Basic Statement • Function • Module • Class
  2. Basic Structure • Greatest feature indentation • Start tag :

    • No need to use ; { } Editor or IDE vim,emacs;IDLE,eclipse ...
  3. Variable • Variables are created when they are assigned •

    No declaration required • Case sensitive:'var' different from 'Var' • Type is determined by Python • A variable can be reassigned to whatever,whenever
  4. Built-in Type • Numbers - int,long,float,complex • String • List

    • Dictionary • Tuple - immutable:Numbers,String,Tuple - mutable:List,Dictionary
  5. Numbers • Integers: 12 -12 0123 0X12AF - type 'int'

    - octal literals begin with 0,contain 0-7 - Hex literals begin with 0X,contain 0-9 and A-F • Floating point: 12.3 1E1 -1.54E-21 - type 'float' - e or E • Long integers: 10000000000000000000000000000000L - type 'long' - end with l or L - any magnitude,no overflow • Complex numbers: 1+2J 3-5j - type 'complex' - end with j or J
  6. String • One line,use '...' or "..." • More,use '''...'''

    or """...""" - useful for large chunks of text • Can't be changed in Python!Immutable • Escape character: \ - \n,\t,\\,\',\"... Raw string: r or R - useful for regular expression - eg,path=r'F:\Develop\Python\code\basic.py'
  7. String Formating • Formating: format % value - format: %s

    %d %f ... - value: when >1 items,use tuple • The best way to create new strings
  8. List • Ordered collection of objects;array • One of the

    6 built-in sequence • Can contain mix of objects of any type • Mutable;can be changed in-place • Dynamic;size can be changed
  9. Sequence • Every element is assigned an index - first

    to last:0,1,2... - last to first:-1,-2,-3... Index can be negative! • 6 built-in sequence - list,tuple,string,Unicode string,buffer,xrange Common sequence operation - indexing,sliceing,adding,multiplying,checking membership
  10. List indexing • Operation format: [n] • Index can be

    negative • Get element by given index n
  11. List sliceing • Operation format: [n1:n2] • Get elements by

    index n1 and n2 • Include n1,not include n2
  12. List other methods • append • count • extend •

    index • insert • pop • remove • reverse • sort
  13. Dictionary • Unordered collection of key/value pairs • Each key

    maps to a value • Also called "mapping" or "hash table" • The key - must be an immutable object - usually be an integer or a string - occurs at most once in a dictionary • The value - may be any object - occurs many times in a dictionary
  14. Dictionary other methods • clear • copy • get •

    has_key • items • keys • pop • update • values
  15. Tuple • Same as list,except immutable • Once created,can't be

    changed • Can be used as keys in mapping • Some functions return tuples
  16. Basic Statement • 3 basic statements: if for while •

    No statement: switch case - if elif ...else - dictionary
  17. if statement • if else • if elif else •

    pass statement - do nothing - sometimes necessary
  18. Dictionary often better than if...elif... • Particularly with many hardcoded

    choices • More compact,and more efficient • This pattern is very useful
  19. for statement • Repetition of a block of statements •

    Iterate through a sequence(list,string...)
  20. range & xrange • Useful with 'for' • range -

    create a list - may use lots of memory;inefficient • xrange - create a iterator,which works like a list - very memory-efficient
  21. while statement • Repetition of a block of statements •

    Loop until test becomes false,or 'break'
  22. Optional 'else' block in loops • 'else' block executed if

    no 'break' encountered • May often replace success/failure flags • Valid in 'for' and 'while' loops
  23. Iteration • Iteration: repeat doing many times; loops • Iterator:

    an object with 'next' method - method '__iter__' return an iterator itself - method 'next' return next value,else raise StopIteration - one value one time,low memory compared with list
  24. Function How to define - use the 'def' statement -

    function body follows;indented - can be placed basically anywhere - required:define the function before calling it Function features - use the documentation string;strongly encouraged - may return more than one value;tuple
  25. Function arguments:variable • List of any number of arguments •

    Useful when unknown number of arguments need • The argument values collected into a tuple - Call 'args',by convention - The '*' is magical part
  26. Function arguments:default values • Arguments may have default values •

    When argument not given in a call,default value is used • If no default value,and not given when called:bombs • Use explicit names to override argument order
  27. Function arguments:keywords • Keyword/value arguments • The argument values collected

    into a dictionary - Call 'kwargs',by convention - The '**' is magical part
  28. Function without 'return': value None • A function does not

    have to use the 'return' statement • If not,then same as a 'procedure' in other languages • Actually returns a value:'None' • 'None' is a special value built-in Python - meaing 'nothing' - useful in many contexts
  29. Lambda expression • format: labmda args:expression - a simple function

    - include only argument expression - can call other functions - limited but useful
  30. Module • A file with extension '.py' • A bag

    of functions and classes • Easy to create:every Python source code is a module • Powerful:many standard library modules • Easy to extend:many third-part library modules available
  31. How to use the module:'import' • The 'import' statement makes

    a module available - import module [as newname] (usage: module.fun) - from module import fun [as newname] (usage: fun)
  32. How are modules are found 'import' • how to find

    - first,current directory - second,sys.path - else,error • if not found,how to solve - add module path to sys.path - use package to organise module
  33. Package • Benefits - avoid name conflct - useful for

    organizing modules • Consist - must exist a '__init__.py' file in package dir - can include other packages • Usage - import A.B.a - from A.B import a
  34. The special '__xxx__' variable • In Python,the variable names '__xxx__'

    are special • Some are created automatically during execution - __name__,__doc__,__file__,__builtins_  Use '__name__' to self-test in module - if executed as the main program,then value '__main__' - if executed as a module,then some other module name
  35. Some modules • re • sys • os • Tkinter

    • time • random • cgi • xml
  36. Class • A class defines potential objects - What their

    structure will be;attributes - What they will be able to do;methods • Objects are instances of classes - An object is a container of data;attributes - An object has associated functions;methods • Classes are the basicis of OOP - abstract,encapsulation,inheritance,polymorphism
  37. Class attributes and methods • Use keyword 'class' • Default

    public,'__xxx' means private • The first argument of methods must be 'self' • Access attrs and methods by 'self.' in class • Special methods '__xxx__',automatically called - __init__,__del__,__repr__,__len__
  38. Class inheritance • Inherit one or more class to create

    another - superclass,subclass - multiple inheritance: more than one superclass Override superclass methods Polymorphism
  39. Plan in the future • Python - RE(regular expression) -

    Threading - DB - Web • SecondLife • OpenSim • Linux