Skip to content

Latest commit

 

History

History
55 lines (45 loc) · 2.46 KB

PYTHON_SYNTAX_101.md

File metadata and controls

55 lines (45 loc) · 2.46 KB

First things to know about Python

Acknowledgements: Chapters 3 and 7 of http://www.johnny-lin.com/pyintro/

  • Case sensitive (capitalization matters!)

  • Indentation is meaningful (loops, conditions, function definition)

    • unless you see \ at the end of the previous line
      • thus, \ allows arbitrary indents, for clarity, of multi-line long statements
  • Multiple commands can be on a line separated by ;

  • Data types

    • Dynamically typed (variable type is set when assigned, upcast when needed)
    • Strings are in single or double quotes; triple it to verbatim special characters
    • True, False and None are Boolean and empty values
  • Lists and tuples. Indexing starts from 0. [0:1] means ONLY the first element

    • Lists [] are ordered, mutable (you can insert, remove, append)
    • Tuples() are ordered, immutable
  • Arrays are in the numpy module, not basic Python

    • reshape, ravel, resize, squeeze(), etc.
  • Dictionaries are unordered sets of {key:value} pairs.

  • Flow control * if : <-- Note Colon!

    • action * while : <-- Note Colon!
    • action that had better change the condition! * for in : <-- Iterable may be a list, or range(n) from 0 to n
    • action
  • Exceptions and errors

    • try: <-- Note Colon!

      • action
    • except: <-- Note Colon!

      • backup action
    • raise (errortype)

  • Procedural syntax: result = function(arguments, keywords)

    • arguments must be present, ordered by position; then keyword=value,... optionally in any order
  • Object oriented syntax: the . symbol

    • An object is an instance of a class
    • object.something is an attribute
    • object.method() calls the method (makes its action happen)
    • dir(object) shows all available methods/attributes for its class
    • some core methods have underscores like a.__doc__ are "private" (definitional). Don't mess with these.
    • class names follow the CapWords convention
  • Modules and namespaces: The heart of Python's power

    • import module (as shortname)
    • from module import submodule ... (as shortname)
    • modules are objects: they have attribiutes and methods
      • Hover over an object and hit shift+tab in Jupyter to see its definition
      • Hover to the right of . and hit tab to see autocomplete help on its available attributes and methods