An Introduction to Python and Its Use in Bioinformatics

Slides:



Advertisements
Similar presentations
Web编程技术 Web Programming Technology
Advertisements

Python 3000 and You Guido van Rossum EuroPython July 7, 2008.
The State of the Python Union OSCON – August 3, 2005 Guido van Rossum Elemental Security, Inc.
Python 3000 and You Guido van Rossum PyCon March 14, 2008.
Python Regrets OSCON, July 25, 2002
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
Setting the PYTHONPATH PYTHONPATH is where Python looks for modules it is told to import List of paths Add new path to the end with: setenv PYTHONPATH.
Perkovic, Chapter 7 Functions revisited Python Namespaces
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez May 19, 2005.
An Introduction to Python – Part IV Dr. Nancy Warter-Perez June 23, 2005.
Concepts when Python retrieves a variable’s value Namespaces – Namespaces store information about identifiers and the values to which they are bound –
An Introduction to Python – Part IV Dr. Nancy Warter-Perez.
1 Outline 7.1 Introduction 7.2 Implementing a Time Abstract Data Type with a Class 7.3 Special Attributes 7.4Controlling Access to Attributes 7.4.1Get.
Writing Solid Code Introduction to Python. Program 1 python -c "print 'Hello World' “ python -c "import time; print time.asctime()“ Start an interactive.
Introduction to Python (for C++ programmers). Background Information History – created in December 1989 by Guido van Rossum Interpreted Dynamically-typed.
Guide to Programming with Python Chapter Nine Working with/Creating Modules.
Python Crash Course Programming Bachelors V1.0 dd Hour 5.
7-Sep-15 Python structure  modules: Python source files or C extensions  import, top-level via from, reload  statements  control flow  create objects.
CIS 218 Python CIS 218 Oakton Community College. CIS 218 Python features no compiling or linkingrapid development cycle no type declarationssimpler, shorter,
November 15, 2005ICP: Chapter 7: Files and Exceptions 1 Introduction to Computer Programming Chapter 7: Files and Exceptions Michael Scherger Department.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Builtins, namespaces, functions. There are objects that are predefined in Python Python built-ins When you use something without defining it, it means.
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
Functions Reading/writing files Catching exceptions
Python Modules An Introduction. Introduction A module is a file containing Python definitions and statements. The file name is the module name with the.
1 CSC 221: Introduction to Programming Fall 2012 Functions & Modules  standard modules: math, random  Python documentation, help  user-defined functions,
Chapter 24 Exception CSC1310 Fall Exceptions Exceptions Exceptions are events that can modify the flow or control through a program. They are automatically.
By James Braunsberg. What are Modules? Modules are files containing Python definitions and statements (ex. name.py) A module’s definitions can be imported.
Exceptions COMPSCI 105 SS 2015 Principles of Computer Science.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Overview Intro to functions What are functions? Why use functions? Defining functions Calling functions Documenting functions Top-down design Variable.
Python Functions.
Introduction to Computing Using Python for loop / def- ining a new function  Execution control structures ( if, for, function call)  def -ining a new.
Python Overview  Last week Python 3000 was released  Python 3000 == Python 3.0 == Py3k  Designed to break backwards compatibility with the 2.x.
CSC 310 – Procedural Programming Languages, Spring, 2009 Chapters 7 and 8: Python Data Types, Subroutines and Control Abstraction.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
CS2021 Week 2 Off and Running with Python. Two ways to run Python The Python interpreter – You type one expression at a time – The interpreter evaluates.
Introduction to Computing Using Python Exceptions (Oops! When things go wrong)  Errors and Exceptions  Syntax errors  State (execution) errors.
Lecture 4 Python Basics Part 3.
Python Built-in Exceptions Data Fusion Albert Esterline Source:
Lecture 07 – Exceptions.  Understand the flow of control that occurs with exceptions  try, except, finally  Use exceptions to handle unexpected runtime.
12. MODULES Rocky K. C. Chang November 6, 2015 (Based on from Charles Dierbach. Introduction to Computer Science Using Python and William F. Punch and.
Modules. Modules Modules are the highest level program organization unit, usually correspond to source files and serve as libraries of tools. Each file.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
Indentations makes the scope/block Function definition def print_message (): print “hello” Function usages print_message () hubo.move ()// hubo is a class.
Rajkumar Jayachandran.  Classes for python are not much different than those of other languages  Not much new syntax or semantics  Python classes are.
Juancho Datu. What is a Module? File containing Python definitions and statements with the suffix ‘.py’ in the current directory For example file name:
COMPSCI 107 Computer Science Fundamentals
Python’s Modules Noah Black.
George Mason University
Introduction to Python
Python’s Modules by E. Esin GOKGOZ.
Core libraries Scripts, by default only import sys (various system services/functions) and builtins (built-in functions, exceptions and special objects.
Python for Introduction to Complex NetworksStudents
Python Classes By Craig Pennell.
Python’s Errors and Exceptions
ERRORS AND EXCEPTIONS Errors:
(Oops! When things go wrong)
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Rocky K. C. Chang 15 November 2018 (Based on Dierbach)
G. Pullaiah College of Engineering and Technology
COMPUTER PROGRAMMING SKILLS
By Ryan Christen Errors and Exceptions.
def-ining a function A function as an execution control structure
UW CSE 190p Section 7/19, Summer 2012 Dun-Yu Hsiao.
SPL – PS1 Introduction to C++.
Presentation transcript:

An Introduction to Python and Its Use in Bioinformatics Csc 487/687 Computing for Bioinformatics

Scopes Scopes define the “visibility” of a variable Variables defined outside of a function are visible to all of the functions within a module (file) Variables defined within a function are local to that function To make a variable that is defined within a function global, use the global keyword Ex 2: x = 5 def fnc(): global x x = 2 print x, fnc() print x >>> ? Ex 1: x = 5 def fnc(): x = 2 print x, fnc() print x >>> ?

Modules Why use? Module Code reuse System namespace partitioning (avoid name clashes) Implementing shared services or data Module A file containing Python definitions and statements. The file name is the module name with the suffix .py appended Definitions from a module can be imported into other modules or into the main module As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you've written in several programs without copying its definition into each program. To support this, Python has a way to put definitions and statements into a file. Such a file is called a module.

Modules How to structure a Program One top-level file Main control flow of program Zero or more supplemental files known as modules Libraries of tools the collection of variables that you have access to in a script executed at the top level and in calculator mode

Modules - Import Import – used to gain access to tools in modules Ex: contents of file b.py def spam(text): print text, 'spam' contents of file a.py import b b.spam('gumby')

Modules - Import Within a module, the module's name (as a string) is available as the value of the global variable _ _name_ _ >>> import b >>>print b._ _name_ _ ? spam=b.spam spam(“How are you”) If you intend to use a function often you can assign it to a local name:

The Module Search Path The current directory The list of directories specified by the environment variable PYTHONPATH When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python.

Standard Modules Python Library Reference Built into the interpreter >>> import sys >>> sys.ps1 '>>> ' >>> sys.ps2 '... ' >>> sys.ps1 = ‘L> ' L> print ‘Hello!' Yuck! L> sys.path.append(“C:\\”) Python comes with a library of standard modules, Python Library Reference . Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts: The variable sys.path is a list of strings that determines the interpreter's search path for modules

Python Documentation Sources #comments In-file documentation The dir function Lists of attributes available on objects Docstrings:__doc__ In-file documentation attached to objects

The Dir() Function used to find out which names a module defines. It returns a sorted list of strings. dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module __builtin__.

The Dir() Function Example def fib2(n): result = [] a, b = 0, 1 while b < n: result.append(b) a, b = b, a+b return result The contents of fibo.py def fib(n): a, b = 0, 1 while b < n: print b, a, b = b, a+b

The Dir() Function Example >>> import fibo, sys >>> dir(fibo) ['__name__', 'fib', 'fib2'] >>> dir(sys) ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', 'builtin_module_names', 'byteorder', 'callstats', 'copyright', 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags', 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'version', 'version_info', 'warnoptions']

The Dir() Function Example(2) >>> import __builtin__ >>> dir(__builtin__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']

Python Docstrings Provide a convenient way of associating documentation with Python modules, functions, classes, and methods. An object's docsting is defined by including a string constant as the first statement in the object's definition. Docstrings can be accessed from the interpreter and from Python programs using the "__doc__" attribute

DocString Example Ex: b.py # Internal comment """Module Docstring comment """ def fn(): """Function Docstring comment """ >>> print b.__doc__ Module Docstring comment >>> print b.fn.__doc__ Function Doctring comment

Class Definition Syntax class ClassName: <statement-1> . . . <statement-N> The simplest form of class definition looks like: Class definition, like function definition, must be executed before they have effect.

Class Objects Attribute references Instantiation Valid attribute names are all the names that were in the class's namespace when the class object was created. Instantiation uses function notation Just pretend that the class object is a parameterless function that returns a new instance of the class Class objects support two kinds of operations: attribute references and instantiation class MyClass: "A simple example class" i = 12345 def f(self): return 'hello world' MyClass.i MyClass.f are valid attribute references, returning an integer and a function object, respectively. MyClass.__doc__ x = MyClass() creates a new instance of the class and assigns this object to the local variable x.

Inheritance class DerivedClassName(BaseClassName): <statement-1> . . . <statement-N> The name BaseClassName must be defined in a scope containing the derived class definition class DerivedClassName(modname.BaseClassName): when the base class is defined in another module: class DerivedClassName(modname.BaseClassName): Execution of a derived class definition proceeds the same as for a base class. When the class object is constructed, the base class is remembered. This is used for resolving attribute references: if a requested attribute is not found in the class, the search proceeds to look in the base class. This rule is applied recursively if the base class itself is derived from some other class.

Multiple Inheritance class DerivedClassName(Base1, Base2, Base3): <statement-1> . . . <statement-N> The only rule necessary to explain the semantics is the resolution rule used for class attribute references. This is depth-first, left-to-right. Thus, if an attribute is not found in DerivedClassName, it is searched in Base1, then (recursively) in the base classes of Base1, and only if it is not found there, it is searched in Base2, and so on.

Iterators for element in [1, 2, 3]: print element for key in {'one':1, 'two':2}: print key for char in "123": print char for line in open("myfile.txt"): print line By now you have probably noticed that most container objects can be looped over using a for statement:

Iterators >>> s = 'abc' >>> it = iter(s) <iterator object at 0x00A1DB50> >>> it.next() 'a‘ 'b‘ 'c‘ Traceback (most recent call last): File "<stdin>", line 1, in ? it.next() StopIteration The use of iterators pervades and unifies Python. Behind the scenes, the for statement calls iter() on the container object. The function returns an iterator object that defines the method next() which accesses elements in the container one at a time. When there are no more elements, next() raises a StopIteration exception which tells the for loop to terminate.

Debugging Can use print statements to “manually” debug Can use debugger in PythonWin