3. Python in general
What is python?
• High level programming language
• Emphasize on code readability
• Very clear syntax + large and comprehensive
• Multiprogramming paradigm: OO, imperative,
functional, procedural, reflective
• A fully dynamic type system and automatic
• Scripting language + standalone executable
program + interpreter
• Can run on many platform: Windows, Linux,
5. Why Do People Use Python?
Because there are many programming languages
available today, this is the usual first question of
6. Python execution speed may not always be as fast
as that of compiled languages such as C and C++
Whether you will ever care about the execution
speed difference depends on what kinds of
programs you write.
Processing a file or constructing a graphical user
interface (GUI), your program will actually run at C
speed, since such tasks are immediately
dispatched to compiled C code inside the Python
7. Who Uses Python Today?
Google makes extensive use of Python in its web
search systems, and employs Python’s creator.
The YouTube video sharing service is largely written
The popular BitTorrent peer-to-peer file sharing
system is a Python program.
Google’s popular App Engine web development
framework uses Python as its application language.
EVE Online, a Massively Multiplayer Online Game
(MMOG), makes extensive use of Python.
8. Maya, a powerful integrated 3D modeling
and animation system, provides a Python
Intel, Cisco, Hewlett-Packard, Seagate,
Qualcomm, and IBM use Python for
Industrial Light & Magic, Pixar, and others
use Python in the production of animated
JPMorgan Chase, UBS, Getco, and Citadel
apply Python for financial market
9. Python’s Capability:
Numeric and Scientific Programming
Gaming, Images, Serial Ports, XML, Robots,
11. -Built-in tools
It’s Easy to Use
It’s Easy to Learn
12. History of Python
Python was conceived in the late1980s and its
implementation was started in December
1989 by Guido van Rossum at CWI in the
Netherlands as a successor to the ABC
programming language capable of exception
handling and interfacing with the Amoeba
operating system. Van Rossum is Python's principal
author, and his continuing central role in deciding
the direction of Python is reflected in the title given
to him by the Python community, Benevolent
Dictator for Life (BDFL).
13. How Python Runs Programs ?
14. Windows users fetch and run a self-installing
executable file that puts Python on their
machines. Simply double-click and say Yes
or Next at all prompts.
Linux and Mac OS X users probably already
have a usable Python preinstalled on their
computers—it’s a standard component on
these platforms today.
Some Linux and Mac OS X users (and most
Unix users) compile Python from its full
source code distribution package.
15. The Python Virtual Machine (PVM)
- Once your program has been compiled to
byte code (or the byte code has been loaded
from existing .pyc files), it is shipped off for
execution to something generally known as the
Python Virtual Machine
- The PVM is the runtime engine of Python
- It’s always present as part of the Python
system, and it’s the component that truly runs
your scripts. Technically, it’s just the last step of
what is called the “Python interpreter.”
17. How to run Python?
The Interactive Prompt
simplest way to run Python programs is to
type them at Python’s interactive
command line sometimes called the
interactive prompt. There are a variety of
ways to start this command line: in an IDE,
from a system console, and so on.
The most platformneutral way to start an
interactive interpreter session is usually just
to type python at your operating system’s
prompt, without any arguments.
18. • On Windows, you can type python in a DOS
• On Unix, Linux, and Mac OS X, you might type this
command in a shell or terminal window .
• Other systems may use similar or platform-specific
devices. On handheld devices,for example, you
generally click the Python icon in the home or
application window to launch an interactive
19. If you have not set your shell’s PATH
environment variable to include Python’s
install directory, you may need to
replace the word “python” with the full
path to the Python executable on your
machine. On Unix, Linux, and similar,
or /usr/bin/python will often suffice. On
Windows, try typing C:Python30python
(for version 3.0)
21. Ordered collections of arbitrary objects
Accessed by offset
Variable-length, heterogeneous, and
Of the category “mutable sequence”
Arrays of object references
22. Accessed by key, not offset
Variable-length, heterogeneous, and
Of the category “mutable mapping”
Tables of object references (hash
23. Ordered collections of arbitrary objects
Accessed by offset
Of the category “immutable sequence”
Fixed-length, heterogeneous, and
Arrays of object references
24. Integers and floating-point numbers
Fixed-precision decimal numbers
Rational fraction numbers
Unlimited integer precision
A variety of numeric built-ins and
25. Variables, Objects, References:
•Variables are entries in a system
table, with spaces for links to objects.
•Objects are pieces of allocated
memory, with enough space to
represent the values for which they
•References are automatically
followed pointers from variables to
26. • 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.
27. 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
• Small integers and strings are cached and reused,
though, is tells us they reference the same single object.
29. Python program structures:
• Programs are composed of modules.
• Modules contain statements.
• Statements contain expressions.
• Expressions create and process
30. Assignment Properties:
• Assignments create object references
• Names are created when first assigned
• Names must be assigned before being
• Some operations perform assignments
Assignment Statement Forms:
31. Syntax: (underscore or letter) + (any number of
letters, digits, or underscores)
Case matters: SPAM is not the same as spam
Reserved words are off-limits
32. Call format
34. General Format:
The if/else ternary expression:
36. Conditional expression:
Any nonzero number or nonempty object is true.
Zero numbers, empty objects, and the special
None are considered false.
Comparisons and equality tests are applied
recursively to data structures.
Comparisons and equality tests return True or False
(custom versions of 1 and 0).
Boolean “and” and “or” operators return a true or
false operand object
37. • “and” and “or” operands:
38. General while format:
40. General Format:
41. Loop Coding Techniques:
• The built-in range function produces a
series of successively higher integers, which
can be used as indexes in a for.
• The built-in zip function returns a series of
parallel-item tuples,which can be used to
traverse multiple sequences in a for.
• Notice: for loops typically run quicker
than while-based counter loops, it’s to your
advantage to use tools like these that allow
you to use for when possible.
• an object is considered iterable if it is either a
physically stored sequence or an object that
produces one result at a time in the context of an
iteration tool like a for loop.
• iterable objects include both physical sequences
and virtual sequences computed on demand.
• Any object with a __next__ method to advance
to a next result,which raises Stop Iteration at the
end of the series of results, is considered iterable in
43. • Example:
44. • Example:
• (x + 10): arbitrary expression
• (for x in L): iterable object
• Extend List Comprehension:
46. Function Basics
47. Function: A function is a device that groups
a set of statements so they can be run
more than once in a program.
• Maximizing code reuse and minimizing
• Procedural decomposition
48. General format:
49. Use “def” statements:
50. Three different scopes
• If a variable is assigned inside a def, it is local to
• 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.
• 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.
51. • Global Statement:
52. • Other ways to access Globals
53. 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.
54. • Nested scope and lambda:
55. The nonlocal statement:
• Is a close cousin to global
• Like global: nonlocal declares that a name will
be changed in an enclosing scope.
• nonlocal applies to a name in an enclosing
function’s scope, not the global module scope
outside all defs.
• nonlocal names must already exist in the
enclosing function’s scope when declared
56. • Arguments are passed by automatically assigning
objects to local variable names.
• Assigning to argument names inside a function does
not affect the caller.
• Changing a mutable object argument in a function
may impact the caller.
• Immutable arguments are effectively passed “by
• Mutable arguments are effectively passed “by
57. General guidelines:
• Coupling: use arguments for inputs and return
• Coupling: use global variables only when truly
• Coupling: don’t change mutable arguments
unless the caller expects it.
• Cohesion: each function should have a single,
• Size: each function should be relatively small.
• Coupling: avoid changing variables in another
module file directly
59. • Alternatives
60. Lambda format:
• Use lambda for:
-inline a function definition
-defer execution of a piece of code
• lambda is an expression, not a statement
• lambda’s body is a single expression, not a block
• 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
61. • Examples:
62. List Comprehension:
• Vs. Map:
63. • Vs. filter:
• Generator functions: are coded as normal def
statements but use yield statements to return results
one at a time, suspending and resuming their state
• Generator expressions: are similar to the list
comprehensions of the prior section, but they
return an object that produces results on demand
instead of building a result list.
65. Generator functions
66. Class Coding Basics
Class Coding Detail
Advanced Class topics
67. OOP program must show:
• Abstraction (or sometimes called encapsulation)
• Inheritance (vs. composition)
• Class vs. Instance Object:
Class: Serve as instance factories. Their attributes
provide behavior—data and functions—that is
inherited by all the instances generated from them.
Instance: Represent the concrete items in a
program’s domain.Their attributes record data that
varies per specific object
68. Each class statement generates a new
Each time a class is called, it generates a
new instance object.
Instances are automatically linked to the
classes from which they are created.
Classes are linked to their superclasses by
listing them in parentheses in a class header
line; the left-to-right order there gives the
order in the tree.
• 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.
70. • Attributes are usually attached to classes by
assignments made within class statements,
and not nested inside function def
• Attributes are usually attached to instances
by assignments to a special argument
passed to functions inside classes, called
71. Class Object:
• The class statement creates a class object and
assigns it a name.
• Assignments inside class statements make class
• Class attributes provide object state and behavior.
• Calling a class object like a function makes a new
• Each instance object inherits class attributes and
gets its own namespace.
• Assignments to attributes of self in methods make
72. Class statement:
• Assigning names inside the class statement makes
class attributes, and nested defs make class
methods, but other assignments make attributes,
74. Method call:
75. I believe the trial has shown conclusively that it is both
possible and desirable to use Python as the principal
it is Free (as in both cost and source code).
it is a flexible tool that allows both the teaching of
traditional procedural programming and modern OOP;
It can be used to teach a large number of transferable
it is a real-world programming language that can
be and is used in academia and the commercial world;
it appears to be quicker to learn and, in combination
with its many libraries, this offers the possibility of more
rapid student development allowing the course to be
made more challenging and varied;
76. and most importantly, its clean syntax offers
increased understanding and enjoyment for
Python should be used as the first year teaching
language. If used it will be possible to teach
students more programming and less of the
peculiarities of a particular language. Teaching a
mid-level language like C in just one day is
inadvisable. Too much time must be spent
teaching C and not enough time teaching generic
skills to students with no programming experience.
In conclusion, Python offers the optimum
compromise of teach ability and applicability.