Professional Documents
Culture Documents
INTRODUCTION TO PYTHON
(BASIC LEVEL)
Editor: Nguyễn Đức Minh Khôi
@HCMC University of Technology, September 2011
9/2/2011 Training Python Chapte 0: Introduction to Python 1
TRAINING PYTHON
Chapter 0: INTRODUCTION TO PYTHON
9/2/2011 Training Python Chapte 0: Introduction to Python 2
CONTENTS
Python in general
Python in general
• What is python?
• High level programming language
• Emphasize on code readability
• Very clear syntax + large and comprehensive standard library
• Use of indentation for block delimiters
• Multiprogramming paradigm: OO, imperative, functional,
procedural, reflective
• A fully dynamic type system and automatic memory management
• Scripting language + standalone executable program + interpreter
• Can run on many platform: Windows, Linux, Mactonish
• Updates:
• Newest version: 3.2.2 (CPython, JPython, IronPython)
• Website: www.python.org
9/2/2011 Training Python Chapte 0: Introduction to Python 4
Dictionaries
Tuples
Files
Numeric Typing
Dynamic Typing
Summary
5/22/2011 Training Python 3
Lists
• Ordered collections of arbitrary objects
• Accessed by offset
• Variable-length, heterogeneous, and arbitrarily nestable
• Of the category “mutable sequence”
• Arrays of object references
5/22/2011 Training Python 4
Dictionaries
• Accessed by key, not offset
• Accessed by key, not offset
• Variable-length, heterogeneous, and arbitrarily nestable
• Of the category “mutable mapping”
• Tables of object references (hash tables)
5/22/2011 Training Python 7
Tuples
• Ordered collections of arbitrary objects
• Accessed by offset
• Of the category “immutable sequence”
• Fixed-length, heterogeneous, and arbitrarily nestable
• Arrays of object references
5/22/2011 Training Python 10
NUMERIC TYPES
• Integers and floating-point numbers
• Complex numbers
• Fixed-precision decimal numbers
• Rational fraction numbers
• Sets
• Booleans
• Unlimited integer precision
• A variety of numeric built-ins and modules
3
• Notices:
• It’s also just the default: if you don’t want such behavior, you can
request that Python copy objects instead of making references.
Dynamic Typing (Cont’) - Shared references
• Notices (next):
• “is” function returns False if the names point to equivalent but different
objects, as is the case when we run two different literal expressions.
• Small integers and strings are cached and reused, though, is tells us
they reference the same single object.
5/22/2011 Training Python 13
Summary
• Object just classification
5/22/2011 Training Python 14
Summary (con’t)
• Object Flexibility
• Lists, dictionaries, and tuples can hold any kind of object.
• Lists, dictionaries, and tuples can be arbitrarily nested.
• Lists and dictionaries can dynamically grow and shrink.
• Object copy
• Slice expressions with empty limits (L[:]) copy sequences.
• The dictionary and set copy method (X.copy()) copies a dictionary
or set.
• Some built-in functions, such as list, make copies (list(L)).
• The copy standard library module makes full copies.
9/2/2011 Learning Python Chapter 1 1
TRAINING PYTHON
STATEMENTS AND SYNTAX
9/2/2011 Learning Python Chapter 2 2
Content
Statements
Conditional statements
Loop statements
Python statements
9/2/2011 Learning Python Chapter 2 5
Assignment Statements
Assignment Properties:
• Assignments create object references
• Names are created when first assigned
• Names must be assigned before being referenced
• Some operations perform assignments implicitly
Assignment Statement Forms:
9/2/2011 Learning Python Chapter 2 8
Expression Statements
9/2/2011 Learning Python Chapter 2 10
Print Operations
• Call format
• Example:
9/2/2011 Learning Python Chapter 2 11
Conditional Statements - IF
• General Format:
• Example:
9/2/2011 Learning Python Chapter 2 12
• Notice:
9/2/2011 Learning Python Chapter 2 15
List comprehension
• Example:
• (x + 10): arbitrary expression
• (for x in L): iterable object
• Extend List Comprehension:
9/2/2011 Learning Python Chapter 2 19
TRAINING PYTHON
Chapter 3: FUNCTION
9/6/2011 Training Python Chapter 3 2
CONTENTS
Function Basics
Scope
Arguments
Function Advanced
Function Basics
• Function: A function is a device that groups a set of
statements so they can be run more than once in a
program.
• Why use?:
• Maximizing code reuse and minimizing redundancy
• Procedural decomposition
9/6/2011 Training Python Chapter 3 4
Scopes
• Three different scopes
• If a variable is assigned inside a def, it is local to that function.
• If a variable is assigned in an enclosing def, it is nonlocal to nested
functions.
• If a variable is assigned outside all defs, it is global to the entire file.
• Notice:
• All names assigned inside a function def statement (or a lambda,
an expression we’ll meet later) are locals by default.
• Functions can freely use names as-signed in syntactically
enclosing functions and the global scope, but they must declare
such nonlocals and globals in order to change them.
9/6/2011 Training Python Chapter 3 7
Scopes – examples
Global names: X, func
Local names: Y, Z
• Factory function
• These terms refer to a function object that remembers values in enclosing
scopes regardless of whether those scopes are still present in memory.
9/6/2011 Training Python Chapter 3 12
Arguments - Examples
9/6/2011 Training Python Chapter 3 18
Function Advanced
• General guidelines:
• Coupling: use arguments for inputs and return for outputs.
• Coupling: use global variables only when truly necessary.
• Coupling: don’t change mutable arguments unless the caller
expects it.
• Cohesion: each function should have a single, unified purpose.
• Size: each function should be relatively small.
• Coupling: avoid changing variables in another module file directly.
9/6/2011 Training Python Chapter 3 21
• Alternatives:
9/6/2011 Training Python Chapter 3 22
• Notices:
• lambda is an expression, not a statement
• lambda’s body is a single expression, not a block of statements.
• If you have larger logic to code, use def; lambda is for small pieces of
inline code. On the other hand, you may find these techniques useful in
moderation
• Examples:
9/6/2011 Training Python Chapter 3 23
• Nested lambda:
• Vs. filter:
Function Pitfall
• “List comprehensions were nearly twice as fast as equivalent for
loop statements, and map was slightly quicker than list
comprehensions when mapping a built-in function such as abs
(absolute value)”
• Python detects locals statically, when it compiles the def’s code,
rather than by noticing assignments as they happen at runtime.
9/6/2011 Learning Python Chapter 2 29
Contents
Modules Basics
Modules Package
Modules in advance
9/15/2011 Training Python Chapter 4 3
Modules Basics
• Modules are process with:
• import: Lets a client (importer) fetch a module as a whole
• from: Allows clients to fetch particular names from a module
• imp.reload: Provides a way to reload a module’s code without
stopping Python
• Why use Modules?
• Code reuse
• System namespace partitioning
• Implementing service or data
9/15/2011 Training Python Chapter 4 4
Be careful:
9/15/2011 Training Python Chapter 4 8
• In mod1.py:
9/15/2011 Training Python Chapter 4 9
•
9/15/2011 Training Python Chapter 4 11
Modules package
• Package __init__.py files:
• Directory: dir0\dir1\dir2\mod.py
• Import statement: import dir1.dir2.mod
• Rules:
• dir1 and dir2 both must contain an __init__.py file.
• dir0, the container, does not require an __init__.py file; this file will
simply be ignored if present.
• dir0, not dir0\dir1, must be listed on the module search path (i.e., it must
be the home directory, or be listed in your PYTHONPATH, etc.).
• Present in tree mode:
9/15/2011 Training Python Chapter 4 12
Modules package
• Relative import:
Module Gotchas
• Statement Order Matters in Top-Level Code
• from Copies Names but Doesn’t Link
• from * Can Obscure the Meaning of Variables
Contents
• Notice:
• Python uses multiple inheritance: if there is more than one
superclass listed in parentheses in a class statement (like C1’s
here), their left-to-right order gives the order in which those
superclasses will be searched for attributes.
• Attributes are usually attached to classes by assignments made
within class statements, and not nested inside function def
statements.
• Attributes are usually attached to instances by assignments to a
special argument passed to functions inside classes, called self.
9/18/2011 Training Python Chapter 5: Classes and OOP 6
• Example:
9/18/2011 Training Python Chapter 5: Classes and OOP 12
• Real:
9/18/2011 Training Python Chapter 5: Classes and OOP 14
In pizzashop.py file
Express: has - relationship
9/18/2011 Training Python Chapter 5: Classes and OOP 21
• Notice:
9/18/2011 Training Python Chapter 5: Classes and OOP 26
• Example:
9/18/2011 Training Python Chapter 5: Classes and OOP 28
• Example:
9/18/2011 Training Python Chapter 5: Classes and OOP 29
Contents
Basic Concepts
Exception in Details
Examples
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 4
Basic Concepts
• What is Exceptions:
• Are events that can modify the flow of control through a program
• Are triggered automatically on errors, and they can be triggered and
intercepted by your code.
• What is Exception Handlers:
• Try statement
• Roles of Exceptions:
• Error Handling
• Event Notification
• Special case Handling
• Termination Actions
• Unusual control flows
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 5
• Default handler:
• Catching Exception:
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 6
• Let’s compare:
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 8
Contents
Basic Concepts
Exception in Details
Examples
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 9
Exception in Details
• Try statement clauses:
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 10
Vs.
• Else:
• Vs.
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 12
• How it works?
• If no exception occurs while the try block is running, Python jumps back
to run the finally block and then continues execution past below the try
statement.
• If an exception does occur during the try block’s run, Python still comes
back and runs the finally block, but it then propagates the exception up
to a higher try or the top-level default handler; the program does not
resume execution below the try statement. That is, the finally block is
run even if an exception is raised, but unlike an except, the finally does
not terminate the exception—it continues being raised after the finally
block runs.
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 13
• Example
• Example:
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 16
Exception in Details
• Python Built in Exception:
• You can use directly or inherit
them to your own Exception
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 18
Contents
Basic Concepts
Exception in Details
Examples
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 19
Examples
• The try/finally statement examples:
• allows you to specify cleanup actions that always must occur, such as file
closes and server disconnects.
7/13/2012 Training Python @HCMUT Summer 2012 - Chapter 6 20
Examples (cont.)
• Unified Try Example:
THANKS FOR LISTENING
Editor: Nguyễn Đức Minh Khôi
Contact: nguyenducminhkhoi@gmail.com
Main reference: Part VI – Classes and OOP
Learning Python 4th Edition – O’reilly 2010