REVISED: Sunday, March 3, 2013
In this tutorial, you will learn how to download and install, IPython.
I. IPYTHON INTRODUCTION
Creating a comprehensive environment for interactive and exploratory computing is the goal of IPython. IPython is more than mathematical software for mathematicians, scientists, and engineers. To start using IPython, you do not need to know anything beyond Python, just type commands as you would at a standard Python prompt.
II. DOWNLOADING AND INSTALLING IPYTHON
Microsoft Windows users frequently have a problem downloading and installing IPython. Before performing downloads and installations read each download site's information very carefully .
A. distribute
Distribute is the standard method for working with Python module distributions.
To download "distribute" click on the following link:
I downloaded and executed distribute_setup.py, which can be executed using any Python interpreter.
B. pyreadline
Windows does not come with a readline module. The pyreadline package is a python implementation of the GNU readline functionality. The IPython shell will work without readline.
To download "pyreadline" click on the following link:
pyreadline.
I downloaded and installed pyreadline-1.7.1.win32.exe (md5).
C. IPython
Click on the following link to download IPython:
IPython.
Select the appropriate download for your computer; and during the download, select the option which places an IPython icon on your desktop.
My computer uses Microsoft Windows; therefore, I used "MS Windows installer" for ipython-0.13.py3-win32.exe (md5). The IPython download was to the following default hard drive path: C:\Python27\ipython-0.13.
Check your hard drive and write down the hard drive default path your computer used for your IPython download. You will need to know this default information when you are writing and reading IPython files.
"Double left mouse click" the IPython icon on your desktop to start the IPython interpreter shell. A IPython interpreter shell window will open as shown below:
When you see the above message, you have successfully downloaded and installed IPython.
A. LOG
To start a log to record your IPython session type logstart -o ipythonLogTest.py and press enter as shown below:
In [2]:
B. DIRECTORY
To view your current directory type ls and press enter as shown below:
Volume in drive C is HP_PAVILION
Volume Serial Number is F436-D0EA
Directory of C:\Python32\ipython-0.13
09/21/2012 02:00 AM <DIR> .
09/21/2012 02:00 AM <DIR> ..
09/13/2012 02:21 AM <DIR> docs
09/13/2012 02:27 AM <DIR> IPython
09/13/2012 02:20 AM <DIR> ipython.egg-info
12/16/2011 11:38 PM 813 ipython.py
09/20/2012 05:59 AM 263 ipython_log.py
09/21/2012 02:00 AM 22 ipythonLogTest.txt
09/21/2012 01:58 AM 57 ipythonLogTest.txt~
06/29/2012 02:46 PM 812 MANIFEST.in
06/30/2012 01:45 AM 3,910 PKG-INFO
04/29/2012 11:53 PM 1,016 README.rst
09/13/2012 02:20 AM <DIR> scripts
06/30/2012 01:45 AM 59 setup.cfg
04/21/2012 11:07 PM 9,561 setup.py
06/30/2012 12:55 AM 13,778 setupbase.py
09/13/2012 02:26 AM 11,204 setupbase.pyc
06/29/2012 03:06 PM 156 setupegg.py
09/13/2012 02:26 AM <DIR> setupext
12 File(s) 41,651 bytes
7 Dir(s) 183,948,582,912 bytes free
In [3]:
To obtain high level information on a "magic function" type the "magic function" name followed by a single question mark; i.e., lsmagic? and press enter as shown below:
In [4]:
To obtain detailed information on a "magic function", including source code, type the "magic function" name followed by a double question mark; i.e., lsmagic?? and press enter as shown below:
V. IPYTHON "MAGIC FUNCTIONS"
In [6]: help()
Welcome to Python 2.7! This is the online help utility.
If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam".
help>
To find out what help topics are available, type topics, and press enter, as shown below:
help> topics
Here is a list of available topics. Enter any topic name to get more help.
help>
Press Enter to return to the IPython interpreter prompt:
You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt.
In [7]:
To obtain information on a keyword type help('keyword') and press enter as shown below:
Function definitions
********************
A function definition defines a user-defined function object (see
section *The standard type hierarchy*):
decorated ::= decorators (classdef | funcdef)
decorators ::= decorator+
decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite
dotted_name ::= identifier ("." identifier)*
parameter_list ::= (defparameter ",")*
( "*" identifier [, "**" identifier]
| "**" identifier
| defparameter [","] )
defparameter ::= parameter ["=" expression]
sublist ::= parameter ("," parameter)* [","]
parameter ::= identifier | "(" sublist ")"
funcname ::= identifier
A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.
The function definition does not execute the function body; this gets executed only when the function is called. [3]
A function definition may be wrapped by one or more *decorator* expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code:
@f1(arg)
@f2
def func(): pass
is equivalent to:
def func( ): pass
func = f1(arg)(f2(func))
When one or more top-level parameters have the form *parameter* ``=`` *expression*, the function is said to have "default parameter values." For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter's default value is substituted. If a parameter has a default value, all following parameters must also have a default value --- this is a syntactic restriction that is not expressed by the grammar.
**Default parameter values are evaluated when the function definition is executed.** This means that the expression is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use ``None`` as the default, and explicitly test for it in the body of the function, e.g.:
def whats_on_the_telly(penguin=None):
if penguin is None:
penguin = [ ]
penguin.append("property of the zoo")
return penguin
Function call semantics are described in more detail in section
*Calls*. A function call always assigns values to all parameters
mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form "``*identifier``" is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form "``**identifier``" is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.
It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda forms, described in section *Lambdas*. Note that the lambda form is merely a shorthand for a simplified function definition; a function defined in a "``def``" statement can be passed around or assigned to another name just like a function defined by a lambda form. The "``def``" form is actually more powerful since it allows the execution of multiple statements.
**Programmer's note:** Functions are first-class objects. A "``def``" form executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section *Naming and binding* for details.
In [8]:
In [8]: from sympy import *
In [9]:
In [9]: from sympy.matrices import Matrix
In [10]:
To turn off your log recording your IPython session type logoff and press enter as shown below:
In [10]: logoff
Switching loging OFF
In [11]:
In [11]: A = Matrix([[1,2],[3,4]])
In [12]:
In [12]: logon
Switching loging ON
In [13]:
In [13]: A_inverse = A.inv( )
In [14]:
In [14]: A_identity = A_inverse * A
In [15]:
To print a table with details about all variable identifiers in the interactive namespace type whos and press enter as shown below:
In [16]:
In [16]: psearch A*
A
A_identity
A_inverse
Abs
Add
AlgebraicNumber
And
AppliedPredicate
ArithmeticError
AssertionError
AssumptionsContext
Atom
AtomicExpr
AttributeError
In [17]:
In [17]: logstate
Filename : ipythonLogTest.py
Mode : rotate
Output logging : False
Raw input log : False
Timestamping : False
State : active
In [18]:
Open ipythonLogTest.py with any text editor to see the logged record of your IPython session.
In this tutorial, you have learned how to download and install, IPython.
Elcric Otto Circle
-->
-->
-->
It will appear on your website as:
"Link to: ELCRIC OTTO CIRCLE's Home Page"
III. IPYTHON DOWNLOAD AND INSTALLATION VAIDATION
"Double left mouse click" the IPython icon on your desktop to start the IPython interpreter shell. A IPython interpreter shell window will open as shown below:
Python 2.7.3 (default, Apr 10 2012, 23:31:26) [MSC v.1500 32 bit (Intel)]
Type "copyright", "credits" or "license" for more information.
IPython 0.13 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:
Type "copyright", "credits" or "license" for more information.
IPython 0.13 -- An enhanced Interactive Python.
? -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help -> Python's own help system.
object? -> Details about 'object', use 'object??' for extra details.
In [1]:
When you see the above message, you have successfully downloaded and installed IPython.
IV. IPYTHON SESSION
A. LOG
To start a log to record your IPython session type logstart -o ipythonLogTest.py and press enter as shown below:
In [1]: logstart -o ipythonLogTest.py
Activating auto-logging. Current session state plus future input saved.
Filename : ipythonLogTest.py
Mode : backup
Output logging : True
Raw input log : False
Timestamping : False
State : active
Activating auto-logging. Current session state plus future input saved.
Filename : ipythonLogTest.py
Mode : backup
Output logging : True
Raw input log : False
Timestamping : False
State : active
In [2]:
Notice -o is the letter o and not a numeric zero. The file name shown above is ipythonLogTest.py; however, you can use any file name and any file type you prefer.
B. DIRECTORY
To view your current directory type ls and press enter as shown below:
In [2]: ls
Volume in drive C is HP_PAVILION
Volume Serial Number is F436-D0EA
Directory of C:\Python32\ipython-0.13
09/21/2012 02:00 AM <DIR> .
09/21/2012 02:00 AM <DIR> ..
09/13/2012 02:21 AM <DIR> docs
09/13/2012 02:27 AM <DIR> IPython
09/13/2012 02:20 AM <DIR> ipython.egg-info
12/16/2011 11:38 PM 813 ipython.py
09/20/2012 05:59 AM 263 ipython_log.py
09/21/2012 02:00 AM 22 ipythonLogTest.txt
09/21/2012 01:58 AM 57 ipythonLogTest.txt~
06/29/2012 02:46 PM 812 MANIFEST.in
06/30/2012 01:45 AM 3,910 PKG-INFO
04/29/2012 11:53 PM 1,016 README.rst
09/13/2012 02:20 AM <DIR> scripts
06/30/2012 01:45 AM 59 setup.cfg
04/21/2012 11:07 PM 9,561 setup.py
06/30/2012 12:55 AM 13,778 setupbase.py
09/13/2012 02:26 AM 11,204 setupbase.pyc
06/29/2012 03:06 PM 156 setupegg.py
09/13/2012 02:26 AM <DIR> setupext
12 File(s) 41,651 bytes
7 Dir(s) 183,948,582,912 bytes free
In [3]:
C. ? VERSUS ??
To obtain high level information on a "magic function" type the "magic function" name followed by a single question mark; i.e., lsmagic? and press enter as shown below:
In [3]: lsmagic?
Type: Magic function
String Form: <bound method BasicMagics.lsmagic of <IPython.core.magics.basic.BasicMagics object at 0x017244F0>>
Namespace: IPython internal
File: c:\python32\ipython-0.13\ipython\core\magics\basic.py
Definition: lsmagic(self, parameter_s='')
Docstring: List currently available magic functions.
In [4]:
To obtain detailed information on a "magic function", including source code, type the "magic function" name followed by a double question mark; i.e., lsmagic?? and press enter as shown below:
In [4]: lsmagic??
Type: Magic function
String Form: <bound method BasicMagics.lsmagic of <IPython.core.magics.basic.BasicMagics object at 0x017244F0>>
Namespace: IPython internal
File: c:\python32\ipython-0.13\ipython\core\magics\basic.py
Definition: lsmagic(self, parameter_s='')
Source:
@line_magic
def lsmagic(self, parameter_s=''):
"""List currently available magic functions."""
print(self._lsmagic())
In [5]:
To help you get started, IPython has a set of predefined "magic functions" that can be called with a command line style syntax. "Magic functions" can be called with or without a % prefix. If you have a variable identifier with the same name as a "magic function" you should use a % prefix so IPython can tell them apart.
To view all of the predefined "magic functions" type lsmagic and press enter as shown below:
Available line magics:
Available cell magics:
Automagic is ON, % prefix IS NOT needed for line magics.
In [6]:
There are two types of "magic functions": "line-oriented" and "cell-oriented".
To view all of the predefined "magic functions" type lsmagic and press enter as shown below:
In [5]: lsmagic
Available line magics:
%alias %history %pdb %reload_ext %xmode
%alias_magic %install_default_config %pdef %rep
%autocall %install_ext %pdoc %rerun
%autoindent %install_profiles %pfile %reset
%automagic %killbgscripts %pinfo %reset_selective
%bookmark %load %pinfo2 %run
%cd %load_ext %popd %save
%cls %loadpy %pprint %sc
%colors %logoff %precision %store
%config %logon %profile %sx
%cpaste %logstart %prun %system
%debug %logstate %psearch %tb
%dhist %logstop %psource %time
%dirs %lsmagic %pushd %timeit
%doctest_mode %macro %pwd %unalias
%ed %magic %pycat %unload_ext
%edit %notebook %pylab %who
%env %page %quickref %who_ls
%gui %paste %recall %whos
%hist %pastebin %rehashx %xdel
Available cell magics:%alias_magic %install_default_config %pdef %rep
%autocall %install_ext %pdoc %rerun
%autoindent %install_profiles %pfile %reset
%automagic %killbgscripts %pinfo %reset_selective
%bookmark %load %pinfo2 %run
%cd %load_ext %popd %save
%cls %loadpy %pprint %sc
%colors %logoff %precision %store
%config %logon %profile %sx
%cpaste %logstart %prun %system
%debug %logstate %psearch %tb
%dhist %logstop %psource %time
%dirs %lsmagic %pushd %timeit
%doctest_mode %macro %pwd %unalias
%ed %magic %pycat %unload_ext
%edit %notebook %pylab %who
%env %page %quickref %who_ls
%gui %paste %recall %whos
%hist %pastebin %rehashx %xdel
%%! %%file %%sx
%%capture %%prun %%system
%%cmd %%script %%timeit
Automagic is ON, % prefix IS NOT needed for line magics.%%capture %%prun %%system
%%cmd %%script %%timeit
In [6]:
There are two types of "magic functions": "line-oriented" and "cell-oriented".
A. IPYTHON "LINE MAGICS"
"Line magics" are prefixed with the % character and work like OS command-line calls. IPython will treat any line whose first character is a % as a special call to a "magic function". IPython will scan its internal list of "magic functions" and call one if it exists. "Line magics" get as an argument the rest of the line, where arguments are passed without parentheses or quotes.
B. IPYTHON "CELL MAGICS"
"Cell magics" are prefixed with a double %%. Cell magics are functions that get as an argument not only the rest of the line, but also the lines below the cell magic in a separate argument.
VI. IPYTHON HELP
To gain access to the standard Python scrolling help, type help(), and press enter, as shown below:
In [6]: help()
Welcome to Python 2.7! This is the online help utility.
If this is your first time using Python, you should definitely check out the tutorial on the Internet at http://docs.python.org/tutorial/.
Enter the name of any module, keyword, or topic to get help on writing Python programs and using Python modules. To quit this help utility and return to the interpreter, just type "quit".
To get a list of available modules, keywords, or topics, type "modules", "keywords", or "topics". Each module also comes with a one-line summary of what it does; to list the modules whose summaries contain a given word such as "spam", type "modules spam".
help>
To find out what help topics are available, type topics, and press enter, as shown below:
help> topics
Here is a list of available topics. Enter any topic name to get more help.
ASSERTION DEBUGGING LITERALS SEQUENCEMETHODS2
ASSIGNMENT DELETION LOOPING SEQUENCES
ATTRIBUTEMETHODS DICTIONARIES MAPPINGMETHODS SHIFTING
ATTRIBUTES DICTIONARYLITERALS MAPPINGS SLICINGS
AUGMENTEDASSIGNMENT DYNAMICFEATURES METHODS SPECIALATTRIBUTES
BACKQUOTES ELLIPSIS MODULES SPECIALIDENTIFIERS
BASICMETHODS EXCEPTIONS NAMESPACES SPECIALMETHODS
BINARY EXECUTION NONE STRINGMETHODS
BITWISE EXPRESSIONS NUMBERMETHODS STRINGS
BOOLEAN FILES NUMBERS SUBSCRIPTS
CALLABLEMETHODS FLOAT OBJECTS TRACEBACKS
CALLS FORMATTING OPERATORS TRUTHVALUE
CLASSES FRAMEOBJECTS PACKAGES TUPLELITERALS
CODEOBJECTS FRAMES POWER TUPLES
COERCIONS FUNCTIONS RECEDENCE TYPEOBJECTS
COMPARISON IDENTIFIERS PRINTING TYPES
COMPLEX IMPORTING PRIVATENAMES UNARY
CONDITIONAL INTEGER RETURNING UNICODE
CONTEXTMANAGERS LISTLITERALS SCOPING
CONVERSIONS LISTS SEQUENCEMETHODS1
help>You are now leaving help and returning to the Python interpreter. If you want to ask for help on a particular object directly from the interpreter, you can type "help(object)". Executing "help('string')" has the same effect as typing a particular string at the help> prompt.
In [7]:
To obtain information on a keyword type help('keyword') and press enter as shown below:
In [7]: help('def')
Function definitions
********************
A function definition defines a user-defined function object (see
section *The standard type hierarchy*):
decorated ::= decorators (classdef | funcdef)
decorators ::= decorator+
decorator ::= "@" dotted_name ["(" [argument_list [","]] ")"] NEWLINE
funcdef ::= "def" funcname "(" [parameter_list] ")" ":" suite
dotted_name ::= identifier ("." identifier)*
parameter_list ::= (defparameter ",")*
( "*" identifier [, "**" identifier]
| "**" identifier
| defparameter [","] )
defparameter ::= parameter ["=" expression]
sublist ::= parameter ("," parameter)* [","]
parameter ::= identifier | "(" sublist ")"
funcname ::= identifier
A function definition is an executable statement. Its execution binds the function name in the current local namespace to a function object (a wrapper around the executable code for the function). This function object contains a reference to the current global namespace as the global namespace to be used when the function is called.
The function definition does not execute the function body; this gets executed only when the function is called. [3]
A function definition may be wrapped by one or more *decorator* expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion. For example, the following code:
@f1(arg)
@f2
def func(): pass
is equivalent to:
def func( ): pass
func = f1(arg)(f2(func))
When one or more top-level parameters have the form *parameter* ``=`` *expression*, the function is said to have "default parameter values." For a parameter with a default value, the corresponding argument may be omitted from a call, in which case the parameter's default value is substituted. If a parameter has a default value, all following parameters must also have a default value --- this is a syntactic restriction that is not expressed by the grammar.
**Default parameter values are evaluated when the function definition is executed.** This means that the expression is evaluated once, when the function is defined, and that the same "pre-computed" value is used for each call. This is especially important to understand when a default parameter is a mutable object, such as a list or a dictionary: if the function modifies the object (e.g. by appending an item to a list), the default value is in effect modified. This is generally not what was intended. A way around this is to use ``None`` as the default, and explicitly test for it in the body of the function, e.g.:
def whats_on_the_telly(penguin=None):
if penguin is None:
penguin = [ ]
penguin.append("property of the zoo")
return penguin
Function call semantics are described in more detail in section
*Calls*. A function call always assigns values to all parameters
mentioned in the parameter list, either from position arguments, from keyword arguments, or from default values. If the form "``*identifier``" is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form "``**identifier``" is present, it is initialized to a new dictionary receiving any excess keyword arguments, defaulting to a new empty dictionary.
It is also possible to create anonymous functions (functions not bound to a name), for immediate use in expressions. This uses lambda forms, described in section *Lambdas*. Note that the lambda form is merely a shorthand for a simplified function definition; a function defined in a "``def``" statement can be passed around or assigned to another name just like a function defined by a lambda form. The "``def``" form is actually more powerful since it allows the execution of multiple statements.
**Programmer's note:** Functions are first-class objects. A "``def``" form executed inside a function definition defines a local function that can be returned or passed around. Free variables used in the nested function can access the local variables of the function containing the def. See section *Naming and binding* for details.
In [8]:
The following steps are performed to create variable identifiers for discussion purposes:
In [9]:
In [9]: from sympy.matrices import Matrix
In [10]:
To turn off your log recording your IPython session type logoff and press enter as shown below:
Switching loging OFF
In [11]:
In [11]: A = Matrix([[1,2],[3,4]])
In [12]:
To turn on your log recording your IPython session type logon and press enter as shown below:
Switching loging ON
In [13]:
In [13]: A_inverse = A.inv( )
In [14]:
In [14]: A_identity = A_inverse * A
In [15]:
VII. IPYTHON NAMESPACE MANAGEMENT
To print a table with details about all variable identifiers in the interactive namespace type whos and press enter as shown below:
In [15]: whos
In [16]:
To search for a namespace variable identifier type psearch followed by the variable identifier name and press enter as shown below:
In [16]: psearch A*
A
A_identity
A_inverse
Abs
Add
AlgebraicNumber
And
AppliedPredicate
ArithmeticError
AssertionError
AssumptionsContext
Atom
AtomicExpr
AttributeError
In [17]:
To determine the status of the log which is recording your IPython session, type logstate and press enter, as shown below:
In [17]: logstate
Filename : ipythonLogTest.py
Mode : rotate
Output logging : False
Raw input log : False
Timestamping : False
State : active
In [18]:
To exit IPython type quit and press enter as shown below:
In [18]: quit
Open ipythonLogTest.py with any text editor to see the logged record of your IPython session.
VIII. REFERENCES
Elcric Otto Circle
-->
-->
-->
How to Link to My Home Page
"Link to: ELCRIC OTTO CIRCLE's Home Page"