Learning Python: A Study Guide
Part I: Getting Started 📖
Chapter 1: A Python Q&A Session 🤔
Why Use Python?
Software Quality: Python emphasizes code readability and
maintainability, leading to higher-quality software.
Developer Productivity: Python's concise syntax and extensive libraries
boost developer productivity.
Scripting Language?: While often used for scripting, Python is a
general-purpose language capable of much more.
Downsides?
Python can be slower than compiled languages for computationally
intensive tasks.
Who Uses Python?
A wide range of users, from system administrators to data scientists,
utilize Python.
What Can I Do with Python?
Python's applications span:
Systems programming
Graphical User Interfaces (GUIs)
Internet scripting
Component integration
Database programming
Rapid prototyping
Numeric and scientific programming
Gaming, image processing, serial port control, XML handling, robotics, and
more.
Python's Support and Strengths:
Support: Python boasts a large and active community, providing ample
resources and support.
Strengths:
Object-Oriented: Supports object-oriented programming principles.
Free and Open Source: Freely available and distributable.
Portable: Runs on various operating systems.
Powerful: Provides extensive libraries and capabilities.
Mixable: Integrates with other languages.
Easy to Use and Learn: User-friendly syntax and learning curve.
Python vs. Other Languages: Python's suitability depends on the
specific project requirements and constraints.
Chapter 2: How Python Runs Programs ⚙️
The Python Interpreter: Python code is executed by an interpreter,
translating code into machine-readable instructions.
Program Execution: The interpreter reads, compiles, and executes
Python code line by line.
Programmer's vs. Python's View: Programmers see their source code;
Python sees bytecode (an intermediate representation).
Execution Model Variations: The interpreter's implementation can
affect execution speed and behavior.
Python Implementation Alternatives: Different implementations
(CPython, Jython, IronPython) exist, each with its own strengths.
Execution Optimization Tools: Tools like bytecode compilers can
enhance performance.
Frozen Binaries: Python code can be packaged into standalone
executables.
Other Execution Options: Various ways exist to run Python code
(interactive prompt, scripts, IDEs).
Chapter 3: How You Run Programs 🧑💻
Interactive Prompt: A command-line interface for directly interacting
with the Python interpreter.
The interactive prompt is great for testing small snippets of code and
experimenting with Python's features.
Running Code Interactively: The prompt allows for immediate
feedback, facilitating iterative development.
Why Use the Interactive Prompt?: It's excellent for learning and
testing.
Using the Interactive Prompt: Commands are typed and executed
immediately.
System Command Lines and Files: Python scripts can be saved
as .py files and executed from the command line.
A First Script: A simple example illustrates creating and running a basic
Python script.
Running Files with Command Lines: Executing Python files from the
command line.
Using Command Lines and Files: Combining command-line arguments
with script execution.
Unix Executable Scripts (#!): Specifying the interpreter directly in the
script for execution.
Clicking File Icons: Running scripts by clicking their icons (platform-
dependent).
Clicking Icons on Windows: Similar to Unix, but with Windows-specific
configurations.
The input() Trick: Using the input() function to get user input.
Other Icon-Click Limitations: Directly running .py files via icons may
have limitations.
Module Imports and Reloads: Importing external modules to extend
functionality.
Modules are files containing reusable Python code. import statements
bring this code into your current script's scope.
The Grander Module Story: Attributes: Modules have attributes
(variables, functions, classes) which can be accessed.
import and reload Usage Notes: Proper use
of import and reload statements.
Using exec to Run Module Files: Dynamically executing Python code
from files.
The IDLE User Interface: A built-in Python IDE.
IDLE Basics: A brief introduction to IDLE's interface and features.
Using IDLE: Editing, running, and debugging code in IDLE.
Advanced IDLE Tools: IDLE's more advanced features (debugging, code
completion).
Other IDEs: Various other Integrated Development Environments for
Python.
Other Launch Options: Various other methods to launch and run Python
code.
Embedding Calls: Integrating Python code within other applications.
Frozen Binary Executables: Creating standalone executables from
Python code.
Text Editor Launch Options: Using text editors to edit and run Python
scripts.
Still Other Launch Options: Various other ways to execute Python
code.
Future Possibilities?: Potential future advancements in Python
execution.
Which Option Should I Use?: Choosing the best approach based on
your needs.
Part II: Types and Operations 🧮
(Continues in the next section)
Multiple-Target Assignments 🎯
Multiple-target assignments allow assigning a single value to multiple
variables simultaneously.
Augmented Assignments ➕
Augmented assignments combine an operation with an assignment. For
example, x += 1 is equivalent to x = x + 1. This applies to other operators
like -=, *=, /=, etc.
Variable Name Rules 🔤
Variable names must start with a letter or underscore and can contain
letters, numbers, and underscores. Keywords (like if, else, while, etc.)
cannot be used as variable names.
Expression Statements 🧮
An expression statement is a line of code that evaluates an expression.
The result might be discarded, or it might produce a side effect (e.g.,
modifying a variable).
Expression Statements and In-Place
Changes 🔄
Some operations modify variables directly (in-place). For
example, [Link]() modifies the list directly, rather than creating a
new one. The += operator also often performs an in-place change if the
object supports it.
Print Operations 🖨️
Print operations display information to the user. The specifics changed
between Python 2.6 and Python 3.0.
The Python 3.0 print() Function 🤔
In Python 3.0, print() is a function: print(value1, value2, ..., sep=' ',
end='\n'). sep specifies the separator between values, and end specifies
the character(s) printed after the values.
The Python 2.6 print Statement 🗣️
In Python 2.6, print is a statement: print value1, value2, ... .
Print Stream Redirection ➡️
You can redirect the output of the print() function to a file or another
stream using techniques like file redirection.
Version-Neutral Printing 🔄
To write code compatible with both Python 2.6 and Python 3.0, use
the print() function and explicitly specify sep and end arguments. A
conditional check for the Python version can be used if complete
compatibility is needed.
if Statements and Syntax Rules 🚦
if statements control program flow based on conditions.
General Format
if condition1:
# Code block if condition1 is true
elif condition2:
# Code block if condition1 is false and condition2 is true
else:
# Code block if all previous conditions are false
Basic Examples
Simple examples using boolean conditions and comparisons.
Multiway Branching
Using elif to create more than two branches in your if statements.
Python Syntax Rules
Indentation: Python uses indentation to define code blocks.
Line Continuation: Use backslashes ( \) to continue statements on
multiple lines.
Block Delimiters: Indentation Rules
Python uses indentation to group statements into blocks of code.
Inconsistent indentation leads to IndentationError.
Statement Delimiters: Lines and
Continuations
A single line of code generally constitutes a single statement, but lines
can be continued to improve readability.
A Few Special Cases
Some examples of special cases concerning syntax and indentation.
Truth Tests 🧐
Evaluates conditions in if statements. Many types are considered truthy
or falsy in Python.
The if/else Ternary Expression ❔
A concise way to write simple if/else statements: value_if_true if
condition else value_if_false
while and for Loops 🔁
Loops are used to repeat code blocks.
while Loops
while condition:
# Code block to repeat as long as condition is true
Examples
Various uses of while loops for different tasks and scenarios.
break, continue, pass, and the
Loop else Clause
break: Exits the loop immediately.
continue: Skips the rest of the current iteration and proceeds to the next.
pass: Does nothing. Useful as a placeholder or in empty code blocks.
Loop else: Code in the else block executes only if the loop completes
normally (without a break).
General Loop Format
The general structure and components of a loop.
pass
Placeholder statement that does nothing.
continue
Skips to the next iteration of the loop.
break
Exits the loop prematurely.
Loop else
Executed only if the loop terminates naturally (not by break).
for Loops
for item in iterable:
# Code block executed for each item in the iterable
Examples
Illustrative examples showcasing for loop applications.
Loop Coding Techniques
Efficient loop coding practices to optimize code performance and
readability.
Counter Loops: while and range
Using while loops and the range() function to create counter-controlled
loops.
Nonexhaustive Traversals: range and Slices
Using range() and slicing to iterate through parts of sequences.
Changing Lists: range
Modifying lists while iterating using range().
Parallel Traversals: zip and map
Iterating through multiple sequences simultaneously
using zip() and map().
Generating Both Offsets and
Items: enumerate
Using enumerate() to get both the index and value while iterating.
Iterations and Comprehensions, Part 1 🔄
Iterators and list comprehensions are discussed in this section.
Iterators: A First Look
Introduction to iterators and their role in iteration.
The Iteration Protocol: File Iterators
The mechanics behind iteration; how file iterators work.
Manual Iteration: iter and next
Manually iterating using iter() and next().
Other Built-in Type Iterators
Iterators for various built-in data types.
List Comprehensions: A First Look
Introduction to list comprehensions as a concise way to create lists.
List Comprehension Basics
Fundamental aspects of list comprehension syntax and usage.
Using List Comprehensions on Files
Applying list comprehensions to files for data processing.
Extended List Comprehension Syntax
Advanced features and capabilities of list comprehensions.
Other Iteration Contexts
Various contexts where iteration is used.
New Iterables in Python 3.0
New iterable features introduced in Python 3.0.
The range Iterator
Details about the range iterator.
The map, zip, and filter Iterators
Information regarding the map, zip, and filter iterators.
Multiple Versus Single Iterators
Explanation of multiple iterators and single iterators.
Dictionary View Iterators
Iterators for dictionaries.
Other Iterator Topics
Further topics related to iterators.
Python Class Deep Dive 📖
Are Attributes in Modules? 🤔
This section delves into the relationship between attributes and modules
in Python. The provided text does not contain specifics on this topic,
therefore, a detailed explanation cannot be provided.
Classes Intercepting Python Operators 🧮
The lecture notes mention that classes can intercept Python operators.
This is achieved through a concept called operator overloading. The
specifics of how this is implemented are detailed in later sections, but the
core idea is that you can redefine how standard operators (+, -, *, /, etc.)
behave when used with objects of a custom class. This allows for more
intuitive and natural code when working with objects.
A Third Example ➡️
Details of a third example are not present in the provided text.
Why Use Operator Overloading? 🤔
The benefits of operator overloading aren't detailed in the provided text.
The World's Simplest Python Class 👶
The lecture notes refer to a "world's simplest Python class," but the actual
code defining this class is not included in the provided text.
Classes Versus Dictionaries 🆚
The provided text does not offer a comparison between classes and
dictionaries.
Chapter Summary 📝
The provided text only mentions the existence of a chapter summary, but
does not include the actual summary content.
Test Your Knowledge: Quiz & Answers 📝
The content of the quiz and answers are not included in the provided text.
A More Realistic Example 🏢
This section introduces a more complex example to illustrate class usage.
The example is broken down into several steps:
Step 1: Making Instances 👶
This step covers the creation of class instances (objects). The lecture
mentions coding constructors, which are special methods ( __init__)
used to initialize objects when they are created. The process involves
testing as the code is written.
Step 2: Adding Behavior (Methods) 🤸♀️
This step focuses on adding methods (functions) to the class. These
methods define the behavior of objects.
Step 3: Operator Overloading ➕➖✖️➗
This step revisits operator overloading, showing how to customize
operator behavior for the class. It also mentions providing print
displays, likely referring to custom __str__ or __repr__ methods for
displaying object information.
Step 4: Customizing Behavior by
Subclassing ➡️
This section discusses subclassing, creating new classes that inherit
from existing ones. This allows for extending and modifying existing class
behavior. The lecture notes mention both "the bad way" and "the good
way" to augment methods via subclassing, but the specific differences are
not detailed. The concept of polymorphism (using a single interface for
multiple types) is mentioned in relation to subclassing.
Step 5: Customizing Constructors, Too 🛠️
This step expands on customizing constructors in subclasses, illustrating
how to modify the initialization process for derived classes.
Step 6: Using Introspection Tools 🔎
This section explores using introspection tools to examine class attributes.
It mentions special class attributes and a generic display tool, likely
for inspecting object data. A distinction is made
between instance and class attributes. Name considerations in tool
classes are mentioned, suggesting best practices for naming conventions
in these tools.
Step 7 (Final): Storing Objects in a
Database 🗄️
The final step covers storing class objects in a database using pickles
and shelves. The lecture describes using a shelve database for object
storage and updating objects within this database. The text also refers
to exploring shelves interactively.
Future Directions 🚀
The lecture mentions future directions, but these are not detailed in the
provided transcript.
Chapter Summary 📝
A chapter summary is mentioned, but its contents are not provided.
Test Your Knowledge: Quiz & Answers 📝
The quiz and its answers are not included in the provided text.
Python Management Techniques 💻
Compared Management Techniques (962)
This section covers various management techniques in Python. Specific
details on the techniques compared are not provided in the transcript.
Intercepting Built-in Operation Attributes
(966)
This section discusses how to intercept and modify the behavior of built-in
Python operations using attributes. No further details are given in the
transcript.
Delegation-Based Managers Revisited (970)
This section revisits the concept of delegation-based managers in Python.
The transcript does not provide specifics on what was discussed.
Attribute Validation Techniques 🧪
Using Properties to Validate (973)
This section explains how to use Python's property mechanism for
attribute validation. No specific examples or code are included in the
transcript.
Using Descriptors to Validate (975)
This section covers using descriptors to perform attribute validation.
Further details on the specific methods or techniques are not provided in
the transcript.
Using __getattr__ to Validate (977)
This section describes using the special method __getattr__ for attribute
validation. No further details are provided in the transcript.
Using __getattribute__ to Validate (978)
This section explains the use of the special method __getattribute__ for
attribute validation. No specifics are provided in the transcript.
Python Decorators 🐍
What's a Decorator? (983)
A decorator is a way to modify or enhance the behavior of a function or
class.
Managing Calls and Instances (984)
This section discusses how decorators manage function calls and class
instances. No specifics are given.
Using and Defining Decorators (984)
This section explains how to use and define decorators in Python. Specific
examples or code are not included in the transcript.
Why Decorators? (985, 1019)
Decorators provide a clean and concise way to add functionality to
functions and classes without modifying their core code.
Function Decorators (986)
This section focuses on function decorators, a way to modify or enhance
the behavior of functions. The transcript does not include specific
examples.
Class Decorators (990)
This section explains class decorators, used to modify or enhance the
behavior of classes. No specifics are provided.
Decorator Nesting (993)
This section covers nesting decorators. No further details are included in
the transcript.
Decorator Arguments (994)
This section discusses passing arguments to decorators. The transcript
lacks specifics.
Decorators Manage Functions and Classes,
Too (995)
This section reinforces that decorators can manage both functions and
classes. No further information is provided.
Coding Function Decorators (996)
This section provides guidance on writing function decorators. The
transcript does not include example code.
Tracing Calls (996)
This section demonstrates how decorators can be used to trace function
calls. No specific code examples are given.
State Information Retention Options (997)
This section discusses techniques for retaining state information within
decorators. The transcript lacks specifics.
Class Blunders I: Decorating Class Methods
(1001)
This section addresses common mistakes when decorating class methods.
No details are provided.
Timing Calls (1006)
This section covers using decorators to time function execution. No code
examples are included.
Adding Decorator Arguments (1008)
This section shows how to add arguments to decorators. No specific code
is included.
Coding Class Decorators (1011)
This section details the process of coding class decorators. The transcript
lacks example code.
Singleton Classes (1011)
This section explains how to create singleton classes using decorators. No
code is provided.
Tracing Object Interfaces (1013)
This section covers tracing object interfaces using decorators. No details
are given.
Class Blunders II: Retaining Multiple
Instances (1016)
This section discusses common errors related to managing multiple
instances with decorators. Further information is not provided.
Decorators Versus Manager Functions
(1018)
This section compares decorators with manager functions. No details are
included in the transcript.
Managing Functions and Classes Directly
(1021)
This section explains directly managing functions and classes. No specifics
are included.
Example: Private and Public Attributes
(1023)
This section uses an example to illustrate private and public attributes.
The example's details are not provided in the transcript.
Implementing Private Attributes (1023)
This section covers implementing private attributes. No details are
included.
Implementation Details I (1025)
This section provides implementation details. No specifics are given.
Generalizing for Public Declarations, Too
(1026)
This section discusses generalizing for public declarations. No details are
given.
Implementation Details II (1029)
This section provides additional implementation details. No specifics are
included.
Open Issues (1030)
This section lists open issues. No details are given.
Python Isn't About Control (1034)
This section emphasizes that Python's approach is not solely focused on
strict control. No details are included.
Example: Validating Function Arguments
(1034)
This section presents an example of validating function arguments using
decorators. The example's details are not included in the transcript.
The Goal (1034)
This section states the goal of argument validation. No specifics are
provided.
A Basic Range-Testing Decorator for
Positional Arguments (1035)
This section describes a basic range-testing decorator. No code is
provided.
Generalizing for Keywords and Defaults,
Too (1037)
This section discusses generalizing the decorator for keyword arguments
and default values. No details are included.
Implementation Details (1040)
This section provides implementation details. No specifics are included.
Open Issues (1042)
This section lists open issues. No details are given.
Decorator Arguments Versus Function
Annotations (1043)
This section compares decorator arguments with function annotations. No
details are provided.
Other Applications: Type Testing (If You
Insist!) (1045)
This section mentions other applications, such as type testing. No details
are included.
Python Metaclasses 🧙♀️
To Metaclass or Not to Metaclass (1051)
This section discusses when to use metaclasses. No specifics are
provided.
Increasing Levels of Magic (1052)
This section explores the increasing levels of abstraction with
metaclasses. No details are included.
The Downside of Helper Functions (1054)
This section discusses the drawbacks of using helper functions instead of
metaclasses. No details are given.
Metaclasses Versus Class Decorators:
Round 1 (1056)
This section compares metaclasses and class decorators. No specifics are
provided.
The Metaclass Model (1058)
This section describes the metaclass model in Python. No details are
provided.
Classes Are Instances of type (1058)
This section explains that classes are instances of the type class.
Metaclasses Are Subclasses of type (1061)
This section explains that metaclasses are subclasses of the type class.
Class Statement Protocol (1061)
This section describes the class statement protocol. No details are
included.
Declaring Metaclasses (1062)
This section covers declaring metaclasses. No details are given.
Coding Metaclasses (1063)
This section discusses coding metaclasses. No details are given.
A Basic Metaclass (1064)
This section presents a basic metaclass example. No code is provided.
Customizing Construction and Initialization
(1065)
This section explains customizing class construction and initialization
using metaclasses. No details are given.
Other Metaclass Coding Techniques (1065)
This section mentions other metaclass coding techniques. No details are
included.
Instances Versus Inheritance (1068)
This section compares instances and inheritance in the context of
metaclasses. No specifics are provided.
Example: Adding Methods to Classes (1070)
This section provides an example of adding methods to classes using
metaclasses. The example's details are not included.
Manual Augmentation (1070)
This section describes manually adding methods to classes. No details are
given.
Metaclass-Based Augmentation (1071)
This section describes adding methods to classes using metaclasses. No
details are provided.
Metaclasses Versus Class Decorators:
Round 2 (1073)
This section compares metaclasses and class decorators. No specifics are
provided.
Example: Applying Decorators to Methods
(1076)
This section presents an example of applying decorators to methods. The
example's details are not given.
Tracing with Decoration Manually (1076)
This section describes manually tracing method calls using decorators. No
details are included.
Tracing with Metaclasses and Decorators
(1077)
This section describes tracing method calls using metaclasses and
decorators. No details are given.
Applying Any Decorator to Methods (1079)
This section discusses applying arbitrary decorators to methods. No
details are provided.
Metaclasses Versus Class Decorators:
Round 3 (1080)
This section compares metaclasses and class decorators. No specifics are
given.
New Chapters in the Book 📖
Chapter 27: A new class tutorial using a realistic example to explore the
basics of Python object-oriented programming (OOP). This chapter is
designed to show OOP in a more realistic context than earlier examples
and to illustrate how class concepts come together into larger, working
programs.
Chapter 36: Details on Unicode and byte strings and outlines string and
file differences between Python 3.0 and 2.6.
Chapter 37: Managed attribute tools such as properties and new
coverage of descriptors.
Chapter 38: Function and class decorators with comprehensive
examples.
Chapter 39: Metaclasses and a comparison/contrast with decorators.
These four chapters are collected in a new final part of the book,
"Advanced Topics," and are considered optional reading.
Changes to Existing Material 🔄
Several existing chapters have been updated with new examples and
reorganized for clarity:
Multiple inheritance now has a new case study example that lists class
trees (Chapter 30).
New examples for generators that manually implement map and zip are in
Chapter 20.
Chapter 31 has new code illustrating static and class methods.
Chapter 23 includes examples of package relative imports.
Chapter 29 now illustrates the __contains__, __bool__,
and __index__ operator overloading methods, along with new overloading
protocols for slicing and comparison.
Five prior chapters have been split into two each to avoid topic overload.
This resulted in new standalone chapters on:
Operator overloading
Scopes and arguments
Exception statement details
Comprehension and iteration topics
Some reordering has been done to improve topic flow and minimize
forward references, though some circular dependencies remain due to
Python 3.0's changes.
Specific Language Extensions in Python 2.6
and 3.0 ✨
Python 3.0 is described as a cleaner, but more sophisticated language.
Some changes assume prior Python knowledge. The following table lists
prominent new language features and the chapters where they are
covered:
Extension
The print function in 3.0
The nonlocal x, y statement in 3
The [Link] method in 2.6 and
String types in 3.0: str for Unicode, bytes fo
Text and binary file distinctions in
Class decorators in 2.6 and 3.0: @priva
New iterators in 3.0: range, map, z
Dictionary views in 3.0: [Link], [Link]
Extension
Division operators in 3.0: remainders,
Set literals in 3.0: {a, b, c}
Set comprehensions in 3.0: {x**2 for
Dictionary comprehensions in 3.0: {x: x**2
Binary digit-string support in 2.6 and 3.0: 0
The fraction number type in 2.6 and 3.0: F
Function annotations in 3.0: def f(a:99,
Keyword-only arguments in 3.0: def f(a,
Extension
Extended sequence unpacking in 3.0: a
Relative import syntax for packages enabled
Context managers enabled in 2.6 and 3
Exception syntax changes in 3.0: raise, excep
Exception chaining in 3.0: raise e2 f
Reserved word changes in 2.6 and
New-style class cutover in 3.0
Property decorators in 2.6 and 3.0: @p
Extension
Descriptor use in 2.6 and 3.0
Metaclass use in 2.6 and 3.0
Abstract base classes support in 2.6
Specific Language Removals in Python 3.0 🚫
Python 3.0 also removed several language tools to improve design. The
following table summarizes removals and their replacements (many
replacements are available in 2.6 for easier migration):
Removed
reload(M)
apply(f, ps, ks)
`X`
Removed
X <> Y
long
D.has_key(K)
raw_input
xrange
file
[Link]
X.__getslice__
Removed
X.__setslice__
reduce
execfile(filename)
exec open(filename)
0777
print x, y
print >> F, x, y
print x, y,
Removed
u'ccc'
'bbb'
raise E, V
Python 2.x to 3.x Changes 🔄
Exception Handling 💥
except E, X: changed to except E as X:
Lines 32, 33, 34 in the text reference this change.
Function Definitions 🎯
def f((a, b)): changed to def f(x): (a, b) = x
Lines 11, 18, 20 in the text reference this change.
File Iteration ✨
[Link] is replaced with iteration using for line in file: or X =
iter(file).
Lines 13, 14 in the text reference this change.
List Creation from Dictionary Views and
Built-ins 🗂️
Creating lists from dictionary views (e.g., [Link]()) now
uses list([Link]()).
Creating lists from built-ins (e.g., map(), range()) now
uses list(map(...)), list(range(...)).
Lines 8, 14 in the text reference this change.
Sorting Dictionaries 🗄️
Sorting dictionary keys: X = [Link](); [Link]() is replaced
with sorted(D) or list([Link]()).
Lines 4, 8, 14 in the text reference this change.
Comparison Functions ⚖️
cmp(x, y) is replaced by using rich comparison methods
like __lt__, __gt__, __eq__, etc. The expression (x > y) - (x <
y) demonstrates the functionality of cmp.
Lines 29 in the text reference this change.
Boolean Methods 🤔
X.__nonzero__ is replaced with X.__bool__.
Line 29 in the text reference this change.
Other Special Methods 🪄
X.__hex__, X.__oct__, and X._index__ are introduced.
Line 29 in the text reference this change.
Sorting with Keys and Reverse 🔄
The use of key= for custom sort functions and reverse=True for reverse
sorting is highlighted.
Line 8 in the text references this change.
Dictionary Comparisons 📊
Comparing dictionaries <, >, <=, >= now compares sorted([Link]()).
Looping code is an alternative.
Lines 8, 9 in the text reference this change.
Type Checking 🔎
[Link] is replaced with list. types is primarily for non-built-in
types.
Line 9 in the text reference this change.
Metaclasses ⚙️
__metaclass__ = M is replaced with class C(metaclass=M): .
Lines 28, 31, 39 in the text reference this change.
Built-in and Library Renaming 📦
__builtin__ is renamed to builtins.
Tkinter is renamed to tkinter. (Lines 18, 19, 24, 29, 30)
_thread replaces thread, and queue replaces Queue. (Line 17)
dbm replaces anydbm. (Line 27)
_pickle (used automatically) replaces cPickle. (Line 9)
[Link] largely replaces os.popen2/3/4 , though [Link] is
retained. (Line 14)
Exception Handling: String vs. Class-Based
🧱
String-based exceptions are replaced with class-based exceptions.
Lines 32, 33, 34 in the text reference this change.
sys.exc_info() ℹ️
Accessing exception information is updated from sys.exc_type,
exc_value to sys.exc_info()[0], [1] .
Lines 34, 35 in the text reference this change.
Function Code Attribute 👨💻
function.func_code is changed to function.__code__ .
Lines 19, 38 in the text reference this change.
__getattr__ and Wrapper Classes 🥷
The behavior of __getattr__ with built-ins and redefining __X__ methods in
wrappers is discussed.
Lines 30, 37, 38 in the text reference this change.
Command-Line Switches ⌨️
Command-line switches -t and tt are mentioned.
Line 10, 12 in the text reference this change.
Import Statements 📥
Inconsistent tabs/spaces are highlighted as errors.
from ... * inside a function is restricted to top-level file imports.
Relative imports ( from . import mod) and package-relative forms are
discussed.
Lines 22, 23 in the text reference these changes.
Exception Classes 🧱
Creating custom exception classes: class MyException: is changed
to class MyException(Exception): .
Line 34 in the text reference this change.
Modules 📚
The exceptions module and its built-in scope are noted. (Line 34)
String Methods vs. String Module Functions
🧵
String module functions are replaced by string object methods.
Line 7 in the text reference this change.
Unbound Methods unbound methods are
now functions. unbound methods can be
called via instances using staticmethod
Lines 30, 31 in the text reference this change.
Mixed Type Comparisons ⚠️
Nonnumeric mixed-type comparisons now result in errors.
Line 5, 9 in the text reference this change.
Additional Changes in Python 3.0 ➕
The text notes that there are further changes in Python 3.0 not listed,
particularly in the standard library. It recommends the "What's New in
Python 3.0" document and the 2to3 and 3to2 code conversion scripts for
more information.
Learning Python: A Study Guide
Preface 🤔
This section details the book's goals, prerequisites, scope, and style.
This Book's Prerequisites 👨🎓
No prior programming experience is strictly required.
Prior programming exposure is helpful but not mandatory.
The book assumes basic computer literacy.
This Book's Scope and Other Books 📚
The book focuses on core Python fundamentals for speed and simplicity.
It uses small, self-contained examples and may omit minor details found
in reference manuals.
It's an introduction, serving as a stepping stone to more advanced texts.
It's designed to be complemented by other O'Reilly Python books
like Programming Python and Python Pocket Reference.
This Book's Style and Structure 📖
Based on a three-day hands-on course.
Includes quizzes at the end of each chapter and exercises at the end of
each part.
Quiz solutions are in the chapters, and exercise solutions are in Appendix
B.
The structure is linear, progressing from basic to advanced concepts.
Each chapter is mostly self-contained, but later chapters build on earlier
ones.
It uses small, self-contained (possibly artificial) examples.
Part I: Getting Started 🚀
This part provides a general overview of Python and introduces basic
concepts to prepare you for later chapters.
Part II: Types and Operations 🧮
This is the most substantial part, exploring Python's built-in object types
(numbers, lists, dictionaries, etc.) in detail. It lays the groundwork for later
chapters and covers dynamic typing.
Part III: Statements and Syntax 📜
This part will cover Python's statements and syntax. (Details not provided
in this transcript).
Part IV: Functions 🛠️
This section delves into Python's higher-level programming structure
tools, focusing on functions. Functions provide a way to package code for
reuse and prevent redundancy.
Scoping Rules: The rules that determine how a program searches for a
name.
Argument-Passing Techniques: Methods for transferring data to
functions.
Additional concepts related to functions will be explored.
Part V: Modules 📦
This part explains how to create, use, and reload modules in Python.
Modules help organize statements and functions into larger components.
Advanced topics include:
Module Packages: Collections of modules.
Module Reloading: The process of updating a module's code in memory.
The __name__ variable: A special variable used to control code execution
within modules.
Part VI: Classes and OOP 🧑💻
This section explores Python's object-oriented programming
(OOP) capabilities using classes. While optional, classes offer a powerful
way to structure code for customization and reuse. Key concepts:
OOP in Python primarily involves looking up names within linked objects.
It reuses concepts covered earlier in the book.
Classes primarily reuse concepts from previous sections.
OOP is optional but can significantly reduce development time,
particularly for large, long-term projects.
Part VII: Exceptions and Tools 🧰
This part concludes the fundamental language coverage by examining
Python's exception handling model and statements. It also provides a
brief overview of development tools useful when working on larger
programs, such as debugging and testing tools.
Exceptions, although lightweight, are discussed after classes because in
Python they are all now classes.
Part VIII: Advanced Topics (New in Fourth
Edition) 📚
This section (new in the fourth edition) covers advanced topics, which are
optional reading. These topics include:
Unicode and byte strings: Handling text and binary data.
Managed attribute tools: properties and descriptors.
Function and class decorators: Modifying functions and classes'
behavior.
Metaclasses: Classes that control the creation of other classes.
Part IX: Appendixes 🗄️
The book concludes with appendixes offering:
Appendix A: Platform-specific tips for using Python on different
computers.
Appendix B: Solutions to end-of-part exercises. (Solutions to end-of-
chapter quizzes are found within the chapters themselves.)
Note: This book is a tutorial, not a reference. For syntax and built-in tool
details, refer to the Python Pocket Reference, other books, or the official
Python reference manuals at [Link]
Python Study Guide: Lecture
Segment
Why Python? 🤔
The popularity of Python stems from several key factors:
Software Quality: Python prioritizes readability, coherence, and overall
software quality, distinguishing it from other scripting languages. Its
uniform code structure enhances understanding and maintainability, even
for code not written by oneself. Advanced software reuse mechanisms
like object-oriented programming (OOP) are also deeply supported.
Developer Productivity: Python significantly increases developer
productivity compared to languages like C, C++, and Java. Python code is
often 3 to 5 times smaller than equivalent code in C++ or Java, reducing
typing, debugging, and maintenance. The immediate execution of Python
programs (without compilation and linking steps) further accelerates
development.
Program Portability: Most Python programs run seamlessly across
major computer platforms (e.g., Linux and Windows). Porting typically
involves simply copying the script's code. Python also provides versatile
options for creating portable graphical user interfaces, database access
programs, web-based systems, and more.
The Author's Journey 👨🏫
The author's experience teaching Python for 12 years, to over 3,000
students, significantly shaped this book. The text largely derives from his
classroom lessons, refined by student feedback. The author acknowledges
the invaluable insights gained from observing common beginner mistakes.
This iterative process, influenced by feedback and experience teaching
worldwide (U.S., Europe, Canada, Mexico), contributed to the text's
current form.
Python Lecture Notes 🐍
Python's Portability and Extensibility 🚀
Portability: Python code runs on various operating systems with minimal
changes. Even operating system interactions (like launching programs or
processing directories) are highly portable.
Standard Library: Python offers a vast standard library with pre-built
functions for many tasks (text processing, network scripting, etc.).
Third-Party Libraries: Python's extensive third-party library ecosystem
provides tools for web development, numerical computing (like the
powerful NumPy which is comparable to Matlab), serial communication,
game development, and more.
Component Integration: Python seamlessly integrates with other
programming languages (C, C++, Java, .NET) and technologies (COM,
SOAP, XML-RPC, CORBA), making it suitable for extending existing
applications.
Python: Quality and Productivity 🏆
Software Quality: Python's design prioritizes simplicity and readability.
Its consistent syntax and coherent programming model make it easy to
learn, understand, and remember. The language promotes a minimalist
approach, often offering one clear solution to a problem. Python values
explicitness over implicit behavior.
Python's design philosophy emphasizes "explicit is better than implicit"
and "simple is better than complex."
Developer Productivity: Python's simple syntax, dynamic typing, and
lack of compilation steps significantly speed up development. This makes
it highly productive, especially when programmer time is a constraint.
Is Python a Scripting Language? 🤔
Python is a general-purpose language frequently used for scripting tasks.
It blends object-oriented programming (OOP) with scripting capabilities.
The terms "script" and "program" are often used interchangeably in
Python contexts.
Shell Tools: Python can be used to create shell scripts for tasks like text
file processing and launching other programs. However, this is just one of
its applications.
Control Language: Python can act as a "glue" to integrate and control
other application components, enabling customization without recompiling
entire systems.
Ease of Use: Python's primary strength as a scripting language is its
ease of use and rapid development cycle, which facilitates incremental
programming. It's suitable for both small, quick tasks and large-scale
projects.
The term "scripting language" applied to Python best describes its rapid
and flexible development process, not a specific application domain.
Python's Downside: Execution Speed 🐢
The main drawback of Python is that its execution speed may be slower
than compiled languages like C and C++. This is because Python typically
compiles to an intermediate bytecode format before interpretation. While
Python has undergone optimizations and is often fast enough for most
applications, performance differences can exist for computationally
intensive programs.
Python's Speed and Applications 🚀
Python's speed of development is often prioritized over execution speed.
However, for tasks demanding optimal execution (like numeric
programming and animation), components can be split off into
compiled extensions and linked to Python scripts. NumPy exemplifies this,
combining compiled libraries with Python for efficient numeric
programming.
Who Uses Python? 🌎
Estimates suggest around 1 million Python users worldwide. Precise
numbers are difficult due to open-source nature and automatic inclusion
with various systems (Linux, macOS, etc.). Python boasts a large user
base and active community, contributing to its stability and robustness.
Real-world applications:
Google: Web search systems.
YouTube: Video sharing service.
BitTorrent: Peer-to-peer file sharing.
Google App Engine: Web development framework.
EVE Online: Massively Multiplayer Online Game.
Maya: 3D modeling and animation system.
Intel, Cisco, HP, Seagate, Qualcomm, IBM: Hardware testing.
Industrial Light & Magic, Pixar: Animated movie production.
JPMorgan Chase, UBS, Getco, Citadel: Financial market forecasting.
NASA, Los Alamos, Fermilab, JPL: Scientific programming.
iRobot: Commercial robotic devices.
ESRI: GIS mapping products.
NSA: Cryptography and intelligence analysis.
IronPort: Email server (over 1 million lines of Python code).
One Laptop Per Child (OLPC): User interface and activity model.
Python's general-purpose nature makes it applicable across diverse fields.
Many organizations utilize Python for both short-term and long-term tasks.
What Can You Do With Python? 🤔
Python excels in various domains, serving as a scripting tool and for
standalone programs. Its applications are virtually limitless.
Systems Programming ⚙️
Python's OS service interfaces are ideal for system administration tools.
Capabilities include: file and directory searches, program launching,
parallel processing, and more.
Standard library includes POSIX bindings and support for OS tools
(environment variables, files, sockets, pipes, processes, threads, regular
expressions, command-line arguments, streams, shell commands,
filename expansion).
Most system interfaces are portable.
Stackless Python offers advanced multiprocessing solutions.
GUIs 🖼️
Python's simplicity makes it well-suited for GUI programming.
tkinter (or Tkinter in Python 2.6) provides a standard object-oriented
interface to the Tk GUI API, creating portable GUIs.
PMW adds advanced widgets to tkinter.
wxPython offers an alternative, portable GUI toolkit.
Higher-level toolkits like PythonCard and Dabo build upon base APIs.
Other toolkits usable with Python include Qt (with PyQt), GTK (with
PyGTK), MFC (with PyWin32), .NET (with IronPython), and Swing (with
Jython or JPype).
Web browsers or simple interfaces can utilize Jython, Python web
frameworks, or server-side CGI scripts.
Internet Scripting 🌐
Python's standard Internet modules facilitate various networking tasks
(client and server modes).
Capabilities include: socket communication, form information extraction,
file transfer (FTP), XML parsing and generation, email handling, web page
fetching, HTML/XML parsing, communication over XML-RPC, SOAP, and
Telnet.
Numerous third-party tools enhance Internet programming in Python (e.g.,
HTMLGen, mod_python, Jython).
Web development frameworks (Django, TurboGears, web2py, Pylons,
Zope, WebWare) provide tools for building websites with features like
object-relational mappers, Model/View/Controller architecture, server-side
scripting and templating, and AJAX support.
Component Integration 🔗
Python's extensibility (via C and C++) allows it to serve as a "glue
language" for scripting other components.
System and Component Integration 🤝
Integrating a C library into Python allows for testing and launching the
library's components.
Embedding Python in a product enables on-site customization without
recompiling the entire product or shipping its source code.
Tools like SWIG, SIP, and Cython automate linking compiled components
into Python.
Frameworks such as Python's COM support (Windows), Jython, IronPython,
and CORBA toolkits offer alternative ways to script components. For
example, Python scripts can use frameworks to script Word and Excel on
Windows.
Database Programming 🗄️
Python interfaces exist for all commonly used relational database systems
(Sybase, Oracle, Informix, ODBC, MySQL, PostgreSQL, SQLite, etc.).
A portable database API allows scripts written for one system (e.g.,
MySQL) to work largely unchanged on others with minimal modifications.
The pickle module provides a simple object persistence system for saving
and restoring Python objects.
Third-party systems like ZODB offer object-oriented database systems for
Python.
SQLObject and SQLAlchemy map relational tables onto Python's class
model.
SQLite is a standard part of Python 2.5 and later.
Rapid Prototyping 🚀
Components written in Python and C appear the same to Python
programs.
This allows for prototyping in Python and then moving selected
components to compiled languages (C or C++) for delivery.
Unlike some prototyping tools, Python doesn't require a complete rewrite
after prototyping.
Numeric and Scientific Programming 🧮
NumPy provides an array object, interfaces to mathematical libraries, and
more.
It integrates Python with numeric routines for speed, making it a tool for
numeric programming.
SciPy and ScientificPython offer additional scientific programming tools
and use NumPy code. Additional tools support animation, 3D visualization,
and parallel processing.
Other Applications of Python 🐍
Python is used in various domains including:
Game programming and multimedia (pygame)
Serial port communication (PySerial)
Image processing (PIL, PyOpenGL, Blender, Maya)
Robot control (PyRo)
XML parsing (xml library, xmlrpclib, third-party extensions)
Artificial intelligence (neural network simulators, expert system shells)
Natural language analysis (NLTK)
Python Support and Community 🫂
Python has a large and active development community.
Changes follow a formal PEP (Python Enhancement Proposal) protocol and
include regression testing.
The PSF (Python Software Foundation) organizes conferences and handles
intellectual property issues.
PyCon is a major Python-only conference.
Python's Technical Strengths 💪
Object-Oriented: Python is object-oriented, supporting polymorphism,
operator overloading, and multiple inheritance. It's easy to use, even for
beginners. It enables scripting for object-oriented systems (C++, Java,
C#). Procedural programming is also supported.
Object-oriented programming (OOP) is a programming paradigm based on
the concept of "objects", which can contain data and code: data in the
form of fields (often known as attributes or properties), and code, in the
form of procedures (often known as methods).
Free and Open Source: Python is free to use and distribute, with no
restrictions on copying, embedding, or shipping. The open-source nature
fosters a large support community.
Open-source software is software with source code that anyone can
inspect, modify, and enhance.
Large Community: Python's development is largely coordinated online.
It includes Guido van Rossum (BDFL) and thousands of other contributors.
Language changes follow a formal enhancement process.
Python's Portability 🌎
Python's standard implementation is written in portable ANSI C, enabling
it to run on various platforms.
Linux and Unix systems
Microsoft Windows and DOS
Mac OS (OS X and Classic)
BeOS, OS/2, VMS, and QNX
Real-time systems (VxWorks)
Cray supercomputers and IBM mainframes
PDAs (Palm OS, PocketPC, and Linux)
Cell phones (Symbian OS and Windows Mobile)
Gaming consoles and iPods
Python programs, using core language and standard libraries, run
consistently across Linux, Windows, and most systems with a Python
interpreter. Platform-specific extensions exist (e.g., COM support on
Windows), but the core remains consistent. tkinter (Tkinter in Python 2.6)
provides GUI support across major platforms.
Python's Power 💪
Python blends scripting and systems development language features. It
offers the simplicity of scripting languages with advanced tools from
compiled languages, making it suitable for large-scale projects. Key
features include:
Dynamic typing: Python tracks object types during runtime, eliminating
type declarations.
Automatic memory management: Python handles memory allocation
and garbage collection.
Programming-in-the-large support: Modules, classes, and exceptions
aid in building large systems.
Built-in object types: Lists, dictionaries, and strings are intrinsic,
flexible, and easily nested.
Built-in tools: Powerful operations like concatenation, slicing, sorting,
and mapping are included.
Library utilities: Precoded tools for tasks ranging from regular
expressions to networking.
Third-party utilities: Open-source nature encourages community
contributions for diverse tasks (COM, imaging, CORBA ORBs, XML,
database access).
Python's Mixability 🔀
Python integrates well with components written in other languages. Its C
API allows flexible interaction between C and Python programs. This
makes it useful for:
Adding functionality to Python.
Using Python in other environments/systems.
Rapid prototyping (Python for initial development, C for performance-
critical parts).
Python's Ease of Use 🚀
Python executes programs directly without intermediate
compilation/linking steps (unlike C or C++), facilitating an interactive
experience and quick turnaround. Its simple syntax and powerful built-in
tools contribute to its ease of use. Some consider Python "executable
pseudocode" due to its simplicity.
Python's Ease of Learning 🎓
Python's core language is easy to learn; experienced programmers might
grasp it in hours, while others might take days. Many systems leverage
this ease of learning for end-user customization.
Python's Name 🐍
Python's name is derived from the BBC comedy series Monty Python's
Flying Circus, a fact that influences examples (e.g., "spam" and "eggs"
instead of "foo" and "bar").
Python Compared to Other Languages ⚖️
Compared to Perl and Tcl:
Python is more powerful than Tcl for large-scale development due to its
support for "programming in the large."
Python has cleaner syntax and simpler design compared to Perl.
Why Python? 🤔
Reasons for Choosing Python
Software Quality: Python emphasizes code readability and
maintainability, leading to fewer bugs.
Developer Productivity: Its simpler syntax and ease of use allow
developers to write code faster.
Program Portability: Python is highly cross-platform, running on various
operating systems.
Support Libraries: A vast collection of libraries expands Python's
capabilities.
Component Integration: Python integrates well with components
written in other languages.
Simple Enjoyment: Many find Python enjoyable to work with.
Python vs. Other Languages
Language
Java Py
C++ Python is simpler, but they serve different
Visual Basic Pytho
PHP Python
Ruby Python is more mature and has a m
Perl Python offers the same capabilities but with
SmallTalk/Lisp Python shares their dynam
C/C++/Java Python is a viable alternative unless
Python's Application 🤖
Python is used in diverse domains:
Website construction
Robotics
Movie animation
And many other computer domains
Python's Design Philosophy
Python's creator, a mathematician, designed it with uniformity and
orthogonality. Its syntax and toolset are coherent, and most of the
language follows from a small set of core concepts. This contrasts with
Perl, whose design reflects its creator's background in linguistics. Perl
offers multiple ways to achieve the same task, leading to flexibility but
potentially to less readable and maintainable code.
For many, Python's enhanced readability translates to better code
reusability and maintainability, making it a better choice for programs
with a longer lifespan. The trade-off is that Python may not offer the same
peak performance as compiled languages like C and C++. However, its
performance is sufficient for most applications, and compiled extensions
are available when speed is critical.
Python Study Guide: Lecture
Segment Notes
🎨 The Art of Code: Readability and
Maintainability 🤔
Good programmers write code for other humans, not just computers. Code
should be easy to understand and maintain.
Python's syntax emphasizes readability, making it easier to follow the flow
of a program. This is a key differentiator from scripting languages like Perl
where readability can be less emphasized.
Python's focus on limited interactions, code uniformity and
regularity, and feature consistency promotes code longevity.
This approach improves programmer productivity and satisfaction.
Although Python allows for multiple solutions, it encourages good
engineering principles.
The difference between art and engineering is illustrated by comparing
painting/sculpture (done for self-expression) to software development
(done for others to maintain and reuse).
🏃🏽 How Python Runs Programs: The
Interpreter's Role
Python is both a programming language and a software package
(interpreter).
The interpreter executes Python programs by reading and carrying out
instructions. It acts as a layer between code and computer hardware.
A Python installation includes the interpreter and a support library. The
interpreter's form (executable program or library) varies depending on the
implementation (C, Java, etc.).
💻 Python Installation: A Quick Overview
Platform
Windows
Linux/macOS Pre-installed or
Other Platforms
Note: Always check for pre-existing Python installations before installing a
new one. Refer to Appendix A for detailed installation instructions.
🚀 Program Execution: Two Perspectives
🧑💻 The Programmer's View
A Python program is a text file (.py extension) with Python statements.
Execution involves running these statements sequentially from top to
bottom.
Python scripts are launched through command lines, icon clicks, IDEs, or
other methods.
print('hello world')
print(2 ** 100)
🤖 The Python Interpreter's View
The programmer's view is sufficient for most Python programmers.
Internally, more complex processes occur when Python executes. This
internal knowledge isn't always required for programming.
🖼️Example: [Link]
The example script [Link] contains two print statements: one to
display "hello world" and the other to display the result of 2 raised to the
power of 100. The output would appear in the same window where the
script was executed.
Python Runtime Environment 🐍
Byte Code Compilation 📝
When you run a Python program, the source code ( .py files) is
first compiled into byte code. This is a lower-level, platform-
independent representation of your code. Think of it as a translation step.
Python does this to speed up execution; byte code runs faster than the
original source code.
Byte Code: A lower-level, platform-independent representation of your
source code, created during the compilation process. It's essentially a
more efficient version of your human-readable code.
The byte code is often saved in .pyc files (compiled .py source). This
speeds up startup time because the next time you run the program,
Python can load the .pyc files and skip the compilation step, unless you've
changed the source code. Python automatically checks timestamps to
determine whether recompilation is needed. If Python cannot
write .pyc files (due to lack of write access), it still works; the byte code is
created in memory and discarded when the program exits. .pyc files are
also useful for distributing Python programs; Python can run a program
from just the .pyc files, even without the original .py source files.
The Python Virtual Machine (PVM) ⚙️
After compilation to byte code (or loading from existing .pyc files), the
code is executed by the Python Virtual Machine (PVM). The PVM isn't
a separate program; it's a part of the Python system—a big loop that goes
through your byte code instructions one by one. It's the runtime engine of
Python and the component that actually runs your scripts. It's the final
step in what's called the Python interpreter.
Python Virtual Machine (PVM): The runtime engine of Python. It's not
a separate program, but rather a built-in component that iterates through
your byte code instructions to execute them.
The figure below illustrates the runtime structure. Note that all this
complexity is hidden from you, the programmer. Byte code compilation is
automatic, and the PVM is part of your installed Python system.
Performance Implications
The Python model differs from fully compiled languages like C and C++.
There's typically no separate build step; code runs immediately. Python
byte code isn't binary machine code (like instructions for an Intel chip); it's
Python-specific. Because the PVM must interpret the byte code, Python
code isn't as fast as C or C++ code. However, Python's internal compile
step means it doesn't have to re-analyze each statement repeatedly,
making Python's speed somewhere between traditional compiled and
interpreted languages.
Development Implications 🛠️
In Python, the development and execution environments are the same.
The compiler is always present at runtime. This makes for rapid
development; there's no precompilation or linking needed. This dynamic
nature also allows Python programs to construct and execute other
Python programs at runtime (using eval and exec). This dynamic nature is
useful for product customization; users can modify Python parts of a
system without recompiling everything. In Python, everything happens at
runtime, even creating functions and classes.
Execution Model Variations 🔄
The described execution flow is the standard implementation but not a
requirement of the Python language itself. The execution model can
change over time. There are alternative Python implementations.
Python Implementation Alternatives 🐍
CPython: The standard implementation; written in C. This is what you get
from [Link].
Jython: Executes Python code on the Java Virtual Machine (JVM).
IronPython: Executes Python code on the .NET framework.
Other implementations like Stackless Python exist but are less common.
All implementations use the same Python language but execute programs
differently. Unless you need to work with Java or .NET, use CPython.
Python Implementations and
Optimizations
Jython 🐍
Jython is a Python implementation designed for integration with Java. It
compiles Python source code into Java bytecode, executed by the Java
Virtual Machine (JVM).
Jython allows Python code to interact seamlessly with Java applications,
acting as a scripting language for Java. It enables Python scripts to create
Java-based GUIs, web applets, and servlets. Python code can import and
utilize Java classes as if they were native Python code.
However, Jython is generally slower and less robust than CPython and is
primarily useful for Java developers seeking a scripting front-end for their
Java code.
IronPython 🐍
IronPython is a Python implementation designed for integration with
Microsoft's .NET framework (and Mono for Linux). It allows Python
programs to interact with .NET applications.
IronPython, similar to Jython, replaces the final steps in Python's
execution model (Figure 2-2) with .NET equivalents, enabling Python
programs to function as both clients and servers within the .NET
environment. It's particularly useful for developers integrating Python with
.NET components.
Like Jython, it is primarily of interest to developers who need to integrate
Python with .NET components. Due to Microsoft's development,
IronPython may benefit from performance optimizations.
Execution Optimization Tools ⚙️
CPython, Jython, and IronPython share a similar structure: compiling
source code to bytecode, which is then executed on a virtual machine.
Other systems optimize this process.
Psyco (Just-in-Time Compiler)
Psyco is not a separate Python implementation, but rather an extension
that accelerates program execution. It enhances the Python Virtual
Machine (PVM) by collecting and utilizing type information during program
runtime to translate bytecode into native machine code.
Psyco is a specializing JIT compiler: it generates optimized machine
code based on the specific data types used in your program. This leads to
significant speed improvements, sometimes making Python code as fast
as compiled C code.
Psyco provides 2x to 100x speed improvements, typically 4x.
Significant speedups are seen in algorithmic code written in pure Python,
reducing the need for rewriting code in C for optimization.
Currently supports Intel x86 architecture only. It may eventually be
incorporated into the PyPy project.
Shedskin (C++ Translator)
Shedskin translates Python source code into C++ code, which is then
compiled into machine code. This approach offers platform neutrality.
Shedskin is experimental and imposes static typing constraints not
present in standard Python.
Early results show potential to outperform standard Python and Psyco in
speed.
Frozen Binaries 📦
Generating standalone executable binaries from Python programs is
achieved using third-party tools.
Frozen binaries bundle your program's bytecode, the PVM, and
necessary support files into a single package. This creates a single
executable file for easy distribution.
py2exe (Windows)
PyInstaller (Windows, Linux, Unix; creates self-installing binaries)
freeze (original)
These tools are available separately and are constantly evolving.
Python Execution Models 💻
Frozen Binaries 🧊
Definition: A frozen binary packages a Python program with its runtime
environment (including the Python Virtual Machine) into a single
executable file.
Unlike true compiled programs, frozen binaries still run byte code through
a virtual machine. This means they don't offer a significant speed
improvement over the original source code.
Advantages:
No need to install Python on the target system.
Increased code protection.
Suitable for distributing commercial software as self-contained programs.
Stackless Python 🐍
Definition: A variant of CPython that doesn't rely on the C language call
stack to save program state.
This allows for better portability to systems with small stack architectures,
improved multiprocessing, and support for advanced programming
structures like coroutines.
Cython 混合语言 🧬
Definition: A hybrid language combining Python with C function calls and
C type declarations.
Cython code can be compiled to C, offering potential performance gains.
While not entirely compatible with standard Python, it's valuable for
wrapping C libraries and creating efficient C extensions for Python.
Future Possibilities ✨
Parrot Project: Aims to create a common byte code format and virtual
machine for multiple programming languages. While Python's current PVM
is more efficient, Parrot's future development is uncertain.
PyPy Project: A Python-based reimplementation of the PVM to enable
new implementation techniques, aiming for speed and flexibility.
Unladen Swallow Project: A Google-sponsored project to significantly
speed up standard Python (by a factor of at least 5), aiming for
compatibility with CPython while removing the Global Interpreter Lock
(GIL) to allow for true parallel processing of Python threads. This was a
project focused on Python 2.6 initially, with potential for inclusion in
Python 3.0.
Execution Model Summary 📝
The current Python execution model (using a byte code compiler and
virtual machine) is an implementation detail, not a fundamental aspect of
the language. While future implementations might change some aspects,
the byte code compiler's role and the highly dynamic nature of Python are
likely to remain. Adding static compilation features would go against the
core principles of Python.
Running Python Interactively 💻
Launching an Interactive Session
To launch an interactive Python session:
On handheld devices, click the Python icon.
If the PATH environment variable isn't set, use the full path to the Python
executable:
Unix/Linux: /usr/local/bin/python or /usr/bin/python
Windows: C:\Python30\python You can also use the cd command to
navigate to the Python directory first. For example: cd C:\
Python30 then python
On Windows, you can also use IDLE's main window or the "Python
(command line)" option from the Start menu.
The Interactive Prompt
The Python interactive session starts by printing informational text
(omitted here for brevity) and then prompts for input with >>>. Results are
displayed after you press Enter.
For example:
>>> print('Hello world!')
Hello world!
>>> print(2 ** 8)
256
(Note: 2 ** 8 means 2 raised to the power 8)
In interactive mode:
Each command is executed immediately.
Results of expressions are displayed automatically (you don't always
need print).
To exit: Ctrl-D (Unix) or Ctrl-Z (Windows). In IDLE, you can also close the
window.
Why Use the Interactive Prompt? 🤔
The interactive prompt is excellent for:
Experimenting: Its immediate feedback makes it ideal for testing how
code works.
Testing: You can import modules and test functions or classes from your
files on the fly.
Experimenting with the Interactive Prompt
🧪
Example: Let's say you encounter 'Spam!' * 8 and don't know what it
does. Instead of searching documentation, try it interactively:
>>> 'Spam!' * 8
'Spam!Spam!Spam!Spam!Spam!Spam!Spam!Spam!'
This demonstrates string repetition: * means multiply for numbers, but
repeat for strings.
Handling Errors 🐞
Making mistakes won't crash Python. For example:
>>> X
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'X' is not defined
You'll get a helpful error message indicating the problem.
Testing Code ✅
The interactive prompt lets you test code from files. For example, to test a
function from the os module (which gets the current working directory):
>>> import os
>>> [Link]()
'c:\\Python30'
This is useful for testing components from various sources (your Python
files, C functions, Java classes under Jython, etc.).
Tips for Using the Interactive Prompt 💡
Only type Python commands.
Python Programming:
Interactive Prompt vs. Script
Files 💻
Interactive Prompt Behavior 🤔
Python code only: The Python prompt only accepts Python code, not
system commands. While you can use [Link] to run system commands
within Python, it's less direct than typing them directly.
print statements: print statements are necessary within files but not
interactively. The interpreter automatically prints the results of
expressions interactively.
Indentation: Do not indent at the interactive prompt. Leading spaces in
code files are interpreted as indentation for nested statements, resulting
in a SyntaxError.
Compound statements: The prompt might change (e.g., to ... instead
of >>>) for lines 2 and beyond of a compound statement. In IDLE,
subsequent lines are automatically indented. To terminate a compound
statement, press Enter twice.
One statement at a time: The interactive prompt executes one
statement at a time. For compound statements, press Enter twice to
complete execution before typing another statement.
Running Code in Files 📁
Saving programs: To permanently save programs, write your code in
files (modules). Modules are text files containing Python statements.
Module execution: Python executes code in a module from top to
bottom each time it's run. Modules are often called programs or scripts.
A script is usually a top-level program file.
Running files from command line: The most basic way to run a file is
by listing its name in a python command line at your system prompt.
A First Python Script ✨
Here's the code from [Link]:
# A first Python script
import sys # Load a library module
print([Link])
print(2 ** 100) # Raise 2 to a power
x = 'Spam!'
print(x * 8) # String repetition
This script imports the sys module, prints the system platform, calculates
2 to the power of 100, assigns a string to a variable, and performs string
repetition.
System Command Lines and Files 🖥️
The interactive prompt is useful for testing, but its disadvantage is that
programs typed there disappear after execution. To save programs
permanently, use files (modules).
Chapter 3: How You Run
Programs
Running Files with Command Lines 💻
To run a Python script saved in a file (e.g., [Link]), use the command
line:
% python [Link]
Replace python with the full path if it's not in your system's PATH. The
output of the script's print statements will be displayed.
Example: If your script contains print("Hello, world!"), running the
command will print "Hello, world!" to the console.
Stream Redirection ➡️
You can redirect the output of a script to a file using:
% python [Link] > [Link]
This saves the output to [Link] instead of displaying it on the console.
This is called stream redirection.
Running on Windows 🖥️
On Windows, the command line might look like this:
C:\Python30> python [Link]
Or, on newer Windows systems, you might be able to simply run the script
by typing its name:
D:\temp> [Link]
Remember to use full paths if the script isn't in your current directory.
Common Beginner Traps 🚧
Beware of automatic extensions on Windows: Notepad might add
a .txt extension, preventing the script from running. Use "All Files" when
saving and explicitly add the .py extension.
File extensions and directory paths at system prompts, but not
for imports: At the system prompt, you must include the .py extension
and the full path. However, Python's import statements omit both.
Use print statements in files: Unlike interactive coding, you
need print statements to see output from program files.
Unix Executable Scripts (#!) 🐧
On Unix-like systems, you can create executable scripts. These are text
files with two special properties:
Their first line starts with #! (shebang).
They have execute permissions set (using chmod +x).
A shebang is a special sequence of characters at the beginning of a
script that tells the operating system which interpreter to use to run the
script. The #! is followed by the path to the interpreter
(e.g., #!/usr/bin/env python3).
Running Python Programs 💻
Running Scripts on Unix-like Systems 🐧
Shebang: The line #!/usr/local/bin/python (often called a shebang)
specifies the path to the Python interpreter.
Executable Privileges: Script files usually need executable privileges
(e.g., chmod +x [Link]).
Example:
#!/usr/local/bin/python
print('The Bright Side ' + 'of Life...')
The shebang is a comment for humans but is used by the OS to find the
interpreter. The file name can be without the .py extension if it won't be
imported by other modules.
Running Scripts on Windows 🖥️
Command-line: Typing python [Link] is equivalent to [Link] (due to
Registry settings).
Shebang: The shebang is ignored by the DOS shell.
Portability: Using the basic command-line approach ( python
your_script.py) is more portable between Unix and Windows.
The env Lookup Trick 🔎
Using #!/usr/bin/env python allows the env program to find the interpreter
based on your system's PATH variable.
This improves portability, but requires env to be in a consistent location
across systems.
Clicking File Icons 🖱️
Windows: Python automatically registers itself to open .py files when
clicked. Source code files usually have a white background, bytecode files
have a black background in file explorers.
Non-Windows: May require registering the .py extension, making the
script executable (using the shebang), or associating the file MIME type
with a command.
Note: Clicking a file icon on Windows may result in a quickly disappearing
console window if the script only prints and exits.
The input() Trick 🤔
To keep the console window open after running a script via an icon click
on Windows, add input() at the end of the script.
input() reads a line from standard input, pausing execution until the Enter
key is pressed.
Example:
# A first Python script
import sys
print([Link])
print(2 ** 100)
x = 'Spam!'
print(x * 8)
input()
Launching Scripts with File Icons 🖱️
Adding an input() call to the bottom of your top-level files will launch the
script when you click its file icon, only if all three conditions are met. This
is analogous to using print for output; it's the simplest way to read user
input and is more versatile than this example suggests. input() optionally
accepts a prompt string (e.g., input('Press Enter to exit') ) and returns a
line of text as a string. It also supports input stream redirection.
Note: In Python 2.6 or earlier, use raw_input() instead of input(). Python
3.0's input() (and 2.6's raw_input()) returns entered text as a string,
unevaluated. To simulate 2.6's input() in 3.0, use eval(input()).
Icon-Click Limitations ⚠️
Error messages are written to a pop-up console window that immediately
disappears. Adding an input() call won't help as the script likely aborts
before reaching it.
On Windows, you can suppress the pop-up DOS console window entirely
by using the .pyw extension. .pyw files are .py files with this special
behavior, mostly used for Python-coded UIs. They often use techniques to
save output and errors to files.
It's best to use icon clicks after debugging or instrumenting your script to
write output to a file. For initial development, use system command lines
or IDLE to see error messages and output. Later, you'll learn about
exception handling ( try statement) to prevent the console from closing on
errors.
Module Imports and Reloads 📚
Every .py file is a module. Other files access a module's items
by importing it—this loads the file and grants access to its contents
(attributes). Larger programs consist of multiple module files, importing
tools from each other, with one designated as the main or top-level file.
Importing a file runs its code; therefore, it's another way to launch it. For
example, you can run [Link] with import script1.
This works only once per session (process) by default. Subsequent imports
do nothing, even if you modify the source file. Imports are expensive
operations.
To force Python to rerun the file, use the reload function (from
the imp module in Python 3.0; built-in in Python 2.6):
from imp import reload # Python 3.0
reload(script1)
reload runs the current version of the file's code, reflecting changes
you've made. It takes an already loaded module object; you must import a
module before reloading it.
Note: In Python 3.0, reload is in the imp module; in Python 2.6, it's a built-
in function.
import and from Statements
The example uses from imp import reload. This copies reload from
the imp module. We'll discuss import and from statements in more detail
later.
Module Imports and Reloads 🔄
Namespaces and Attributes
Modules serve as libraries of tools, essentially packages of variable
names (a namespace).
Names within a module are called attributes. An attribute is a variable
attached to a specific object (like a module).
Importers access names assigned at a module's top level (functions,
classes, variables).
A namespace is a way to organize code into logical units, avoiding name
conflicts. Think of it like different rooms in a house; each room has its own
set of items (variables), and you need to specify the room to access a
particular item.
Accessing Module Attributes
You can access a module's attributes in two ways:
1. Using import: Loads the entire module. Access attributes using the dot ( .)
operator: module_name.attribute_name.
2. import myfile
print([Link]) # Output: The Meaning of Life
3. Using from: Copies specific names from the module into the current
namespace. Access attributes directly by their name.
4. from myfile import title
print(title) # Output: The Meaning of Life
The . operator is like specifying the location of an item within a
namespace (module).
import vs. from
import keeps namespaces separate, minimizing name conflicts.
from copies names, potentially overwriting existing names. Use cautiously!
The reload() Function
Names loaded with from are not directly updated by reload, but names
accessed with import are. If your names don't change after a reload,
use import and [Link] references.
Example: [Link]
a = 'dead'
b = 'parrot'
c = 'sketch'
print(a, b, c)
This module defines three attributes ( a, b, c). Importing it:
import threenames
print(threenames.b, threenames.c) # Output: ('parrot', 'sketch')
from threenames import a, b, c
print(b, c) # Output: ('parrot', 'sketch')
dir(threenames) lists the module's attributes (including built-in ones).
Module Files and Namespaces
Modules are the largest program structure in Python.
Each module is a self-contained namespace, preventing name collisions.
Modules facilitate code reusability and organization.
Usage Notes
Remember that import and reload are just one way to run code. Other
methods include icon clicks, IDE menu options, and command lines. Avoid
relying solely on import and reload to launch your programs.
Reloading Modules 🔄
When calling the reload() function, remember to use
parentheses. reload() only reloads the specified module, not any modules
it imports; thus, you might need to reload multiple files. Due to these
complexities (and others discussed later), it's generally advisable to avoid
using reload() and imports initially.
Alternative Methods to Running Files 🚀
IDLE RunRun Module: This offers a simpler approach to running files,
always executing the current version of your code.
System Shell Command Lines: These provide similar benefits to the
IDLE method, eliminating the need for reload().
If you must import modules at this stage, keep all files in your current
working directory to minimize complications. However, using imports and
reloads is a common testing method in Python.
Using exec() to Run Module Files 🐍
The exec(open('[Link]').read()) function call provides another way to
run files from the interactive prompt without importing and reloading.
Each exec() call runs the current version of the file, thus bypassing the
need for reloads.
Exec is similar to importing, but doesn't technically import the module.
Each call runs the file anew, effectively pasting the code into
the exec() location.
However, like the from statement, exec() might silently overwrite existing
variables.
Example:
>>> x = 999
>>> exec(open('[Link]').read()) # Code run in this namespace by default
...same output...
>>> x # Its assignments can overwrite names here
'Spam!'
Python searches for imported modules in directories listed in [Link]. To
import from a directory outside your working directory, that directory
must be in your PYTHONPATH setting (see Chapter 21 for details).
[Link]: A Python list of directory names from the sys module, initialized
from a PYTHONPATH environment variable and standard directories.
In contrast, import runs a file once per process and creates a separate
module namespace, preventing variable overwrites in your scope. The
trade-off is the need for reload() after changes.
Version skew note: Python 2.6 also includes execfile('[Link]'),
equivalent to exec(open('[Link]').read()) . However, execfile() is not
available in Python 3.0, requiring the use
of exec(open('[Link]').read()) . The best practice is often to use shell
commands or IDLE's menu options.
The IDLE User Interface 🖥️
IDLE provides a graphical user interface (GUI) for Python development. It's
an integrated development environment (IDE) that combines editing,
running, browsing, and debugging in a single interface. It uses
the tkinter GUI toolkit (Tkinter in Python 2.6), making it portable across
various platforms.
IDLE: An Integrated Development Environment (IDE) – a GUI for editing,
running, browsing, and debugging Python programs.
To start IDLE on Windows:
Find it in the Start menu under Python.
Right-click on a Python program icon.
On Unix-like systems, you might launch it from a command line or by
clicking the [Link] or [Link] file.
The main window, displaying an interactive session with the >>> prompt, is
used for testing; code is executed immediately. Use the File menu to
create or open files. The text edit window's Run menu executes the code
within that window.
IDLE uses syntax-directed colorization in both the main window and text
edit windows.
Some Linux/Unix systems might require installing tkinter support. Mac OS
X may have it preinstalled.
Running Programs in IDLE 💻
Running Your Code in IDLE
To run a Python file in IDLE:
1. Open the file's text edit window.
2. Go to the Run menu and select Run Module (or use the keyboard shortcut).
3. IDLE will prompt you to save changes if necessary.
4. Output and error messages appear in the main interactive window (Python
shell).
5. The RESTART message separates script output from previous executions.
IDLE Hint: Use Alt-P (or Ctrl-P on some Macs) and Alt-N (or Ctrl-N) to
scroll through command history.
Common IDLE Pitfalls ⚠️
.py Extension: IDLE doesn't automatically add the .py extension when
saving. You must add it manually. Failure to do so prevents importing the
module.
Running Scripts: Use Run > Run Module in the text edit window, not
interactive imports and reloads. This ensures you always run the most
current version.
Reloading Modules: Only reload modules tested interactively; Run > Run
Module handles updates to the main file and its imported modules
automatically.
Clearing the Screen: There's no clear-screen function in IDLE. Press and
hold Enter or print blank lines (though the latter is unnecessary).
GUI and Threaded Programs: IDLE may hang when running complex
tkinter GUI or multithreaded programs. Run these outside IDLE if issues
arise.
Connection Errors: If you experience connection errors, start IDLE in
single-process mode using the command line: [Link] -n.
IDLE-Specific Behavior: IDLE's interactive namespace makes variables
from your code automatically available in the interactive session. This is
convenient but isn't standard Python behavior; remember that variables
must be imported outside of IDLE. IDLE also automatically changes the
directory and adds its directory to the module import search path.
Customizing IDLE ✨
Customize fonts and colors through Options > Configure.
Customize key bindings, indentation, and more via the Help menu.
Advanced IDLE Tools 🛠️
Debugger: Enabled via the Debug menu; allows setting breakpoints,
viewing variable values, and stepping through code.
Object Browser: Accessible through the File menu; allows navigating
the module search path to view files and objects. Clicking on an item
opens its source code.
Error Handling: Right-click on error messages to jump to the offending
code line.
Python IDEs 💻
IDLE
IDLE is Python's built-in IDE.
It's free, portable, and user-friendly, making it ideal for beginners.
Features include automatic indentation, advanced text and file search.
Recommended for this book's exercises unless you prefer command-line
development.
IDLE's intuitive GUI makes it easy to experiment and learn its features.
Alternatives to IDLE
IDE Description
Eclipse +
PyDev Advanced open-source IDE originally for Java, with Python support via PyDev plugin
Komodo Full-featured IDE for Python and other languages.
Powerful open-source IDE with extensive Python support (code completion,
NetBeans refactoring, debugging, etc.). Supports CPython and Jython.
IDE Description
PythonWin Free Windows-only IDE, included in ActiveState's ActivePython distribution.
Other IDEs exist (Wing IDE, PythonCard, etc.), and many text editors
support Python development (Emacs, Vim). See [Link] or
search the web for "Python IDE" or "Python editors".
Running Python Code 🚀
Interactive and File-Based Launching
The text covers running code interactively and from files using various
methods: system command lines, imports, exec, GUIs like IDLE.
Embedding Calls 嵌套调用
Python code can be run automatically by other programs (e.g., games
allowing user modifications).
The Python code might be in a text file, database, HTML page, XML
document, etc.
The embedding system (C, C++, Java with Jython) runs the Python code.
Example (C code embedding Python):
#include <Python.h>
...
Py_Initialize(); // This is C, not Python
PyRun_SimpleString("x = 'brave ' + 'sir robin'"); // But it runs Python
code
In this mode, another system, not the user, may initiate Python program
execution. Python's interpreted nature avoids recompilation for changes.
Frozen Binary Executables 冻结的二进制可执行文件
Combine program bytecode and the Python interpreter into a single
executable.
Launched like any other executable (icon clicks, command lines).
Best for distributing finished products, not development.
Text Editor Launch Options
Many text editors support Python editing and running (built-in or via web
downloads). For example, Emacs can be used for full Python development.
See [Link] or search for "Python editors".
Other Launch Options
Additional ways to start Python programs exist depending on the platform
(e.g., dragging icons on macOS, Windows' Run option). Python's standard
library also provides tools for launching Python programs in separate
processes (e.g., [Link], [Link]), and web pages might invoke scripts
on servers.
Launching Python Programs 🚀
IDLE Interface
Best for beginners.
User-friendly GUI environment.
Hides underlying configuration details.
Includes a platform-neutral text editor.
Standard and free part of the Python system.
Text Editor and Command Line 💻
Suitable for experienced programmers.
Use a text editor in one window and a separate window for launching
programs via system command lines and icon clicks.
Debugging Python Code 🐞
Strategies
Do nothing: Often, Python's error messages are sufficient; read the
message and fix the indicated line and file. This is especially true for your
own code.
Insert print statements: The primary method for debugging.
Add print() statements to display variable values or messages indicating
program flow. Remember to remove or comment them out before
finalizing your code.
Use IDE GUI debuggers: Most Python IDEs (like IDLE, Eclipse, NetBeans,
Komodo, and Wing IDE) offer point-and-click debugging support. IDLE's
debugger is less commonly used, potentially due to the lack of a
command line.
Use the pdb command-line debugger: Offers fine-grained control.
Commands allow stepping through code line by line, inspecting variables,
setting breakpoints, and more. It can be launched interactively or as a
top-level script. It also has a postmortem function for examining errors
after they occur.
Other options: Third-party tools offer debugging support for specialized
situations, like multithreaded programs or embedded code. Winpdb is an
example of a standalone debugger with advanced features and cross-
platform compatibility.
Debugging in Python is significantly easier than in older systems where it
involved manual memory dumps and hex calculations. Python's error
reporting and exception handling make debugging significantly less
painful.
Which Method to Choose 🤔
The best method depends on your experience level and preferences.
Beginners should start with IDLE, while experienced programmers might
prefer a text editor and command line approach.
Chapter Summary 📝
This chapter covered various ways to launch Python programs:
Interactive interpreter sessions
Running scripts from files using system commands
Using file icon clicks
Module imports
exec calls
IDE GUIs (like IDLE)
The goal was to equip you with the knowledge to start writing and running
Python code.
Running Python Code 🏃♂️
Ways to Run Python Code
Python code can be executed in several ways:
System command lines
File icon clicks
Imports and reloads using the exec built-in function
IDE GUI selections (e.g., IDLE's Run Run Module)
Unix executables using the #! trick
Drag-and-drop (on some platforms)
Text editor-specific methods
Standalone frozen binary executables
Embedded mode within other programs (e.g., C, C++, Java)
Potential Issues When Running Python
Code
Scripts that print and exit immediately close the output window,
preventing output viewing. Error messages also vanish quickly. Using
system command lines or IDEs is recommended for development.
Python imports a module only once per process by default. To run a
changed module without restarting Python, you need to reload it (after at
least one initial import). Methods like shell command lines or IDEs
typically handle this automatically.
IDLE's Run Run Module menu option runs the code and displays output in
the interactive shell. However, IDLE can be hung by certain programs,
especially multithreaded GUI applications. Also, some IDLE features may
not behave the same way outside the IDLE environment. For example,
IDLE automatically imports script variables into the interactive scope, but
this isn't standard Python behavior.
Namespaces in Python 📦
A namespace is a collection of variables (names). In Python, it's an
object with attributes. Each module file is automatically a namespace
containing variables from top-level assignments. Namespaces prevent
name collisions because modules are self-contained; files need explicit
imports to use names from other files.
Test Your Knowledge: Part I Exercises 🤓
1. Interaction: Start the Python interactive command line (>>> prompt)
and type "Hello World!". The string should be echoed back. This verifies
your Python environment setup. You might need to use cd, specify the full
Python executable path, or adjust your PATH environment variable (see
Appendix A for help).
2. Programs: Create a simple module file with the statement print('Hello
world!'). Run the file using one of the methods described above.