# Circuit Theory/Filters

!Low pass filter !High
pass filter !Band Pass
filter !Band Stop
filter !Comb
filter Some terms used
to describe and classify linear filters:

## Frequency Response

-   -   Low-pass filter -- low
        frequencies are passed, high frequencies are attenuated.
    -   High-pass filter -- high
        frequencies are passed, low frequencies are attenuated.
    -   Band-pass filter -- only
        frequencies in a frequency band are passed.
    -   Band-stop filter or band-reject
        filter -- only frequencies in a frequency band are attenuated.
    -   Notch filter -- rejects just one
        specific frequency - an extreme band-stop filter.
    -   Comb filter -- has multiple
        regularly spaced narrow passbands giving the bandform the
        appearance of a comb.
    -   All-pass filter -- all
        frequencies are passed, but the phase of the output is modified.

```{=html}
<!-- -->
```
-   Cutoff frequency is the frequency
    beyond which the filter will not pass signals. It is usually
    measured at a specific attenuation such as 3dB.
-   Roll-off is the rate at which attenuation
    increases beyond the cut-off frequency.
-   Transition band, the (usually
    narrow) band of frequencies between a passband and stopband.
-   Ripple#Frequency_domain "wikilink") is the
    variation of the filter\'s insertion
    loss in the passband.
-   The order of a filter is the degree of the approximating
    polynomial and in passive
    filters corresponds to the number of elements required to build it.
    Increasing order increases roll-off and brings the filter closer to
    the ideal response.


# Circuit Theory/Active Filters

Active filters have op amps or amplifiers in them. They usually don\'t
have inductors because they are expensive, heavy and large when compared
to capacitors.

## Minimal Filter Transfer Functions

Each filter type has a characteristic transfer function:

  Filter Type   Transfer Function
  ------------- ---------------------------------
  High Pass     $\frac{s^2}{aS^2 + bs + c}$
  Low Pass      $\frac{1}{aS^2 + bs + c}$
  Band Pass     $\frac{s}{aS^2 + bs + c}$
  Notch         $\frac{s^2 + d}{aS^2 + bs + c}$

First the goal is to build a transfer function from the op-amp circuit
so that a bode diagram can be plotted. This is a simple matter of
substituting s for derivatives in the terminal relations.

## Active Filter Components

Rather than draw an example op amp circuit for each of the above
filters, it is easier to draw four op amp circuits that are more related
to the desired transfer function:

+-------------------------+----------------+-------------------------+
| Circuit                 | Generates      | Transfer Function       |
+=========================+================+=========================+
| ![](Activ               | Complex Pole   | derivation |                | Example90/ "wikilink")\ |
|                         |                | $-\frac{R_              |
|                         |                | 3}{R_1 + (C_2R_1R_2 + C |
|                         |                | _2R_1R_3 + C_2R_2R_3)s  |
|                         |                |  + C_1C_2R_1R_2R_3s^2}$ |
+-------------------------+----------------+-------------------------+
| ![](Acti                | Zero at Origin | $-sRC$                  |
| veFilterOriginZero.png) |                |                         |
+-------------------------+----------------+-------------------------+
| ![](Ac                  | Real Pole      | $\frac{-\frac{1}{R_     |
| tiveFilterRealPole.png) |                | 1C}}{s+\frac{1}{R_2C}}$ |
+-------------------------+----------------+-------------------------+
| ![](Ac                  | Real Zero      | $-R_                    |
| tiveFilterRealZero.png) |                | 2C(s + \frac{1}{R_1C})$ |
+-------------------------+----------------+-------------------------+

Most filter design starts with the desired
transfer function. Then the circuit is built. With the above four
configurations, any transfer function can be created.

Better filters are have stepper slopes and narrower bands in their bode
diagrams. This is measured with a factor called Q for
quality. This is why
there are so many different types of filter designs.

## Under Constrained Design

Suppose you wanted this transfer function:

$$\frac{s+1}{(s+2)(s+3)(s+4)}$$ Then an active filter could be built
like this:

<File:ActiveFilterRealZero.png%7Cstage> A\<br
\\\>$-R_2C(s + \frac{1}{R_1C})$ <File:ActiveFilterRealPole.png%7Cstage>
B\<br \\\>$\frac{-\frac{1}{R_1C}}{s+\frac{1}{R_2C}}$
<File:ActiveFilterRealPole.png%7Cstage> C\<br
\\\>$\frac{-\frac{1}{R_1C}}{s+\frac{1}{R_2C}}$
<File:ActiveFilterRealPole.png%7Cstage> D\<br
\\\>$\frac{-\frac{1}{R_1C}}{s+\frac{1}{R_2C}}$

Choosing values to match the above transfer function results in a table
like this:

  Input Stage Variables        Feedback stage variables
  ---------------------------- --------------------------
  $R_{1_A}C_A = 1$             $R_{2_A}C_A = 1$
  $R_{1_B}C_B = \frac{1}{2}$   $R_{2_B}C_B = 1$
  $R_{1_C}C_C = \frac{1}{3}$   $R_{2_C}C_C = 1$
  $R_{1_D}C_D = \frac{1}{4}$   $R_{2_D}C_D = 1$

There are 12 unknowns and 8 equations. This is called an under
constrained problem. It means that one can apply other design rules. For
example, capacitors are more expensive than resistors. Buying in bulk is
less expensive. So \... choose one value for all the capacitors and then
adjust resistor values. Choose C = 1μF Then all the resistors are 1
M&Ohm; accept R~1B~, R~1C~ and R~1D~.


# Circuit Theory/Source Transformations

## Source Transformations

Independent current sources can be turned into independent voltage
sources, and vice-versa, by methods called \"Source Transformations.\"
These transformations are useful for solving circuits. We will explain
the two most important source transformations, **Thevenin\'s Source**,
and **Norton\'s Source**, and we will explain how to use these
conceptual tools for solving circuits.

## Black Boxes

A circuit (or any system, for that matter) may be considered a **black
box** if we don\'t know what is inside the system. For instance, most
people treat their computers like a black box because they don\'t know
what is inside the computer (most don\'t even care), all they know is
what goes in to the system (keyboard and mouse input), and what comes
out of the system (monitor and printer output).

Black boxes, by definition, are systems whose internals aren\'t known to
an outside observer. The only methods that an outside observer has to
examine a black box is to send input into the systems, and gauge the
output.

## Thevenin\'s Theorem

Let\'s start by drawing a general circuit consisting of a source and a
load, as a block diagram:

![](General_Source-Load_Circuit.svg "General_Source-Load_Circuit.svg")

Let\'s say that the source is a collection of voltage sources, current
sources and resistances, while the load is a collection of resistances
only. Both the source and the load can be arbitrarily complex, but we
can conceptually say that the source is directly equivalent to a single
voltage source and resistance (figure (a) below).

  -------------------------------------------------------- ------------------------------------------------------------------------------
  ![](Thevenin_Equivalent.svg "Thevenin_Equivalent.svg")   ![](Thevenin_Equivalent_Under_Test.svg "Thevenin_Equivalent_Under_Test.svg")
  *(a)*                                                    *(b)*
  -------------------------------------------------------- ------------------------------------------------------------------------------

We can determine the value of the resistance *R~s~* and the voltage
source, *v~s~* by attaching an independent source to the output of the
circuit, as in figure (b) above. In this case we are using a current
source, but a voltage source could also be used. By varying *i* and
measuring *v*, both *v~s~* and *R~s~* can be found using the following
equation:

$$v=v_s+iR_s \,$$

There are two variables, so two values of *i* will be needed. See
Example 1 for more details. We can
easily see from this that if the current source is set to zero
(equivalent to an open circuit), then *v* is equal to the voltage
source, *v~s~*. This is also called the open-circuit voltage, *v~oc~*.

This is an important concept, because it allows us to model what is
inside a unknown (linear) circuit, just by knowing what is coming out of
the circuit. This concept is known as **Thévenin\'s Theorem** after
French telegraph engineer Léon Charles
Thévenin, and the circuit
consisting of the voltage source and resistance is called the **Thévenin
Equivalent Circuit**.

## Norton\'s Theorem

Recall from above that the output voltage, *v*, of a Thévenin equivalent
circuit can be expressed as

$$v=v_s+iR_s \,$$

Now, let\'s rearrange it for the output current, *i*:

$$i=-\frac{v_s}{R_s}+\frac{v}{R_s}$$

This is equivalent to a KCL description of the following circuit. We can
call the constant term *v~s~/R~s~* the source current, *i~s~*.

![](Norton_Equivalent_Under_Test.svg "Norton_Equivalent_Under_Test.svg")

The equivalent current source and the equivalent resistance can be found
with an independent source as before (see Example
2).

When the above circuit (the **Norton Equivalent Circuit**, after Bell
Labs engineer E.L. Norton) is
disconnected from the external load, the current from the source all
flows through the resistor, producing the requisite voltage across the
terminals, *v~oc~*. Also, if we were to short the two terminals of our
circuit, the current would all flow through the wire, and none of it
would flow through the resistor (current divider rule). In this way, the
circuit would produce the short-circuit current *i~sc~* (which is
exactly the same as the source current *i~s~*).

## Circuit Transforms

We have just shown turns out that the Thévenin and Norton circuits are
just different representations of the same black box circuit, with the
same Ohm\'s Law/KCL equations. This means that we cannot distinguish
between Thévenin source and a Norton source from outside the black box,
and that we can directly equate the two as below:

  ---------------------------------------------------- ---------- --------------------------------------------------
  center   $\equiv$   center
  ---------------------------------------------------- ---------- --------------------------------------------------

We can draw up some rules to convert between the two:

-   The values of the resistors in each circuit are conceptually
    identical, and can be called the equivalent resistance, *R~eq~*:

$$R_{s_n}=R_{s_t}=R_s=R_{eq}$$

-   The value of a Thévenin voltage source is the value of the Norton
    current source times the equivalent resistance (Ohm\'s law):

$$v_s=i_sr\,$$

If these rules are followed, the circuits will behave identically. Using
these few rules, we can transform a Norton circuit into a Thévenin
circuit, and vice versa. This method is called **source
transformation**. See Example 3.

## Open Circuit Voltage and Short Circuit Current

The open-circuit voltage, *v~oc~* of a circuit is the voltage across the
terminals when the current is zero, and the short-circuit current
*i~sc~* is the current when the voltage across the terminals is zero:

  ---------------------------------------------------------- ------------------------------------------------------------
  ![](Open_Circuit_Voltage.svg "Open_Circuit_Voltage.svg")   ![](Short_Circuit_Current.svg "Short_Circuit_Current.svg")
  *The open circuit voltage*                                 *The short circuit current*
  ---------------------------------------------------------- ------------------------------------------------------------

We can also observe the following:

-   The value of the Thévenin voltage source is the open-circuit
    voltage:

$$v_s=v_{oc}\,$$

-   The value of the Norton current source is the short-circuit current:

$$i_s=i_{sc}\,$$

We can say that, generally,

$$R_{eq}=\frac{v_{oc}}{i_{sc}}$$

## Why Transform Circuits?

How are Thevenin and Norton transforms useful?

:   Describe a black box characteristics in a way that can predict its
    reaction to any load.
:   Find the current through and voltage across any device by removing
    the device from the circuit! This can instantly make a complex
    circuit much simpler to analyze.
:   Stepwise simplification of a circuit is possible if voltage sources
    have a series impedance and current sources have a parallel
    impedance.


# Circuit Theory/Analysis Methods

## Analysis Methods

When circuits get large and complicated, it is useful to have various
methods for simplifying and analyzing the circuit. There is no perfect
formula for solving a circuit. Depending on the type of circuit, there
are different methods that can be employed to solve the circuit. Some
methods might not work, and some methods may be very difficult in terms
of long math problems. Two of the most important methods for solving
circuits are **Nodal Analysis**, and **Mesh Current Analysis**. These
will be explained below.

## Superposition

One of the most important principals in the field of circuit analysis is
the principal of **superposition**. It is valid only in linear circuits.

What does this mean? In plain English, it means that if we have a
circuit with multiple sources, we can \"turn off\" all but one source at
a time, and then investigate the circuit with only one source active at
a time. We do this with every source, in turn, and then add together the
effects of each source to get the total effect. Before we put this
principle to use, we must be aware of the underlying mathematics.

### Necessary Conditions

Superposition can only be applied to **linear** circuits; that is, all
of a circuit\'s sources hold a linear relationship with the circuit\'s
responses. Using only a few algebraic rules, we can build a mathematical
understanding of superposition. If *f* is taken to be the response, and
*a* and *b* are constant, then:

$$f(ax_1+bx_2)= f(ax_1) + f(bx_2) \,$$

In terms of a circuit, it clearly explains the concept of superposition;
each input can be considered individually and then summed to obtain the
output. With just a few more algebraic properties, we can see that
superposition cannot be applied to non-linear circuits. In this example,
the response *y* is equal to the square of the input x, i.e. y=x^2^. If
*a* and *b* are constant, then:

$$y=(ax_1+bx_2)^2 \ne (ax_1)^2 + (bx_2)^2 = y_1+y_2\,$$

Note that this is only one of an infinite number of counter-examples\...

### Step by Step

Using superposition to find a given output can be broken down into four
steps:

1.  Isolate a source - Select a source, and set all of the remaining
    sources to zero. The consequences of \"turning off\" these sources
    are explained in Open and Closed
    Circuits.
    In summary, turning off a voltage source results in a short circuit,
    and turning off a current source results in an open circuit.
    (Reasoning - no current can flow through a open circuit and there
    can be no voltage drop across a short circuit.)
2.  Find the output from the isolated source - Once a source has been
    isolated, the response from the source in question can be found
    using any of the techniques we\'ve learned thus far.
3.  Repeat steps 1 and 2 for each source - Continue to choose a source,
    set the remaining sources to zero, and find the response. Repeat
    this procedure until every source has been accounted for.
4.  Sum the Outputs - Once the output due to each source has been found,
    add them together to find the total response.

## Impulse Response

An **impulse response** of a circuit can be used to determine the output
of the circuit:

![](System_Block.svg "System_Block.svg"){width="400"}

The output y is the **convolution** h \* x of the input x and the
impulse response:

$$y(t) = (h*x)(t) = \int_{-\infty}^{+\infty} h(t-s)x(s)ds$$.

If the input, x(t), was an **impulse** ($\delta(t)$), the output y(t)
would be equal to h(t).

By knowing the impulse response of a circuit, any source can be
plugged-in to the circuit, and the output can be calculated by
convolution.

## Convolution

The **convolution operation** is a very difficult, involved operation
that combines two equations into a single resulting equation.
Convolution is defined in terms of a definite integral, and as such,
solving convolution equations will require knowledge of integral
calculus. This wikibook will not require a prior knowledge of integral
calculus, and therefore will not go into more depth on this subject then
a simple definition, and some light explanation.

### Definition

The convolution a \* b of two functions a and b is defined as:

$$(a * b)(t) = \int_{-\infty}^\infty a(\tau)b(t - \tau)d\tau$$

The asterisk operator is used to denote convolution. Many computer
systems, and people who frequently write mathematics on a computer will
often use an asterisk to denote simple multiplication (the asterisk is
the multiplication operator in many programming languages), however an
important distinction must be made here: **The asterisk operator means
convolution.**

### Properties

Convolution is commutative, in the sense that $a * b = b * a$.
Convolution is also *distributive* over addition, i.e.
$a * (b + c) = a * b + a * c$, and *associative*, i.e.
$a * (b * c) = (a * b) * c$.

### Systems, and convolution

Let us say that we have the following block-diagram system:

+----------------------------------+----------------------------------+
| ![](System_Block.svg             | -   *x(t)* = **system input**    |
| "System_Block.svg"){width="400"} | -   *h(t)* = **impulse           |
|                                  |     response**                   |
|                                  | -   *y(t)* = **system output**   |
+----------------------------------+----------------------------------+

Where x(t) is the input to the circuit, h(t) is the circuit\'s impulse
response, and y(t) is the output. Here, we can find the output by
convoluting the impulse response with the input to the circuit. Hence we
see that the impulse response of a circuit is not just the ratio of the
output over the input. In the frequency domain however, component in the
output with frequency ω is the product of the input component with the
same frequency and the transition function at that frequency. The moral
of the story is this: *the output to a circuit is the input convolved
with the impulse response.*


# Python Programming/Overview

Python is a high-level,
structured,
open-source programming language that can be
used for a wide variety of programming tasks. Python was created by
Guido Van Rossum in the early 1990s; its following has grown steadily
and interest has increased markedly in the last few years or so. It is
named after Monty Python\'s Flying Circus comedy program.

Python is used extensively for system administration (many vital
components of Linux distributions are written in
it); also, it is a great language to teach programming to novices. NASA
has used Python for its software systems and has adopted it as the
standard scripting language for its Integrated Planning System. Python
is also extensively used by Google to implement many components of its
Web Crawler and Search Engine & Yahoo! for managing its discussion
groups.

Python within itself is an interpreted programming language that is
automatically compiled into bytecode before execution (the bytecode is
then normally saved to disk, just as automatically, so that compilation
need not happen again until and unless the source gets changed). It is
also a dynamically typed language that includes (but does not require
one to use) object-oriented features and constructs.

The most unusual aspect of Python is that whitespace is significant;
instead of block delimiters (braces → \"{}\" in the C family of
languages), indentation is used to indicate where blocks begin and end.

For example, the following Python code can be interactively typed at an
interpreter prompt, display the famous \"Hello World!\" on the user
screen:

``` python
 >>> print ("Hello World!")
Hello World!
```

Another great feature of Python is its availability for all platforms.
Python can run on Microsoft Windows, Macintosh and all Linux
distributions with ease. This makes the programs very portable, as any
program written for one platform can easily be used on another.

Python provides a powerful assortment of built-in types (e.g., lists,
dictionaries and strings), a number of built-in functions, and a few
constructs, mostly statements. For example, loop constructs that can
iterate over items in a collection instead of being limited to a simple
range of integer values. Python also comes with a powerful standard
library, which includes
hundreds of modules to provide routines for a wide variety of services
including regular
expressions and
TCP/IP sessions.

Python is used and supported by a large Python
Community that exists on
the Internet. The mailing lists and news
groups like the tutor
list actively support
and help new python programmers. While they discourage doing homework
for you, they are quite helpful and are populated by the authors of many
of the Python textbooks currently available on the market.

*Python 2 vs. Python 3:* Years ago, the Python developers made the
decision to come up with a major new version of Python, which became the
3.*x* series of versions. The 3.x versions are *backward-incompatible*
with Python 2.*x*: certain old features (like the handling of Unicode
strings) were deemed to be too unwieldy or broken to be worth carrying
forward. Instead, new, cleaner ways of achieving the same results were
added. See also ../Python 2 vs. Python
3/ chapter.


# Python Programming/Getting Python

To program in Python, you need a Python interpreter to run your
code---we will discuss interpreters later. If it\'s not already
installed, or if the version you are using is obsolete, you will need to
obtain and install Python using the methods below. The current Python
versions are 3.x; versions 2.x are discontinued and no longer
maintained.

## Installing Python in Windows

Go to the Python Homepage and get the
proper version for your platform. Download it, read the instructions and
get it installed.

To run Python from the command line, you will need to have the python
directory in your PATH. You can instruct the Python installer to add
Python to the path, but if you do not do that, you can add it manually.
The PATH variable can be modified from the Window\'s System control
panel. To expand the PATH in Windows 7:

1.  Go to Start.
2.  Right click on computer.
3.  Click on properties.
4.  Click on \'Advanced System Settings\'
5.  Click on \'Environmental Variables\'.
6.  In the system variables select Path and edit it, by appending a
    \';\' (without quote) and adding \'C:\\python27\'(without quote).

If you prefer having a temporary environment, you can create a new
command prompt short-cut that automatically executes the following
statement:

`PATH %PATH%;c:\python27`

If you downloaded a different version (such as Python 3.1), change the
\"27\" for the version of Python you have (27 is 2.7.x, the current
version of Python 2.)

### Cygwin

By default, the Cygwin installer for Windows does not include Python in
the downloads. However, it can be selected from the list of packages.

## Installing Python on Mac

Users on Mac OS X will find that it already ships with Python 2.3 (OS X
10.4 Tiger) or Python 2.6.1 (OS X Snow Leopard), but if you want the
more recent version head to Python Download
Page follow the instruction on the
page and in the installers. As a bonus you will also install the Python
IDE.

## Installing Python on Unix environments

Python is available as a package for most Linux distributions. In some
cases, the distribution CD will contain the python package for
installation, while other distributions require downloading the source
code and using the compilation scripts.

### Gentoo Linux

Gentoo includes Python by default---the package management system
*Portage* depends on Python.

### Ubuntu Linux

Users of Ubuntu will notice that Python comes installed by default, only
it sometimes is not the latest version. To check which version of Python
is installed, type

``` bash
python -V
```

into the terminal.

### Arch Linux

Arch Linux does not come with Python pre-installed by default, but it is
easily available for installation through the package manager to pacman.
As root (or using sudo if you\'ve installed and configured it), type:

``` bash
pacman -S python
```

This will be update package databases and install Python 3. Python 2 can
be installed with:

``` bash
pacman -S python2
```

Other versions can be built from source from the Arch User Repository.

### Source code installations

Some platforms do not have a version of Python installed, and do not
have pre-compiled binaries. In these cases, you will need to download
the source code from the official
site. Once the download is complete,
you will need to unpack the compressed archive into a folder.

To build Python, simply run the configure script (requires the Bash
shell) and compile using make.

### Other Distributions

Python, also referred to as CPython to avoid confusion, is written in
the C programming
language "wikilink"), and is the
official reference implementation. CPython can run on various platforms
due to its portability.

Apart from CPython there are also other implementations that run on top
of a virtual machine. For example, on Java\'s JRE (Java Runtime
Environment) or Microsoft\'s .NET CLR (Common Language Runtime). Both
can access and use the libraries available on their platform.
Specifically, they make use of
reflection "wikilink") that allows
complete inspection and use of all classes and objects for their very
technology.

*Python Implementations (Platforms)*

  Environment   Description              Get From
  ------------- ------------------------ -----------------------------------------
  Jython        Java Version of Python   Jython
  IronPython    C# Version of Python     IronPython

### Integrated Development Environments (IDE)

It\'s common to use a simple text editor for writing Python code, but
you may feel the need to upgrade to a more advanced *IDE*. CPython ships
with IDLE; however, IDLE is not considered user-friendly.[^1] For Linux,
KDevelop and Spyder are popular. For Windows, PyScripter is free, quick
to install, and comes included with
PortablePython.

*Some Integrated Development Environments (IDEs) for Python*

  Environment              Description                               Get From
  ------------------------ ----------------------------------------- ----------------------------------------------------
  ActivePython             Highly flexible, Pythonwin IDE            ActivePython
  Anjuta                   IDE Linux/Unix                            Anjuta
  Eclipse (PyDev plugin)   Open-source IDE                           Eclipse
  Eric                     Open-source Linux/Windows IDE.            Eric
  KDevelop                 Cross-language IDE for KDE                KDevelop
  Ninja-IDE                Cross-platform open-source IDE.           Nina-IDE
  PyScripter               Free Windows IDE (portable)               PyScripter
  Pythonwin                Windows-oriented environment              Pythonwin
  Spyder                   Free cross-platform IDE (math-oriented)   Spyder
  VisualWx                 Free GUI Builder                          VisualWx

The Python official wiki has a complete list of
IDEs.

There are several commercial IDEs such as Komodo, BlackAdder, Code
Crusader, Code Forge, and PyCharm. However, for beginners learning to
program, purchasing a commercial IDE is unnecessary.

## Trying Python online

You can try Python online, thereby avoiding the need to install. The
online Python shell at Python\'s
official site provides a web Python REPL (read--eval--print loop).

## Keeping Up to Date

Python has a very active community and the language itself is evolving
continuously. Make sure to check python.org for
recent releases and relevant tools. The website is an invaluable asset.

Public Python-related mailing lists are hosted at
mail.python.org. Two examples of such mailing
lists are the **Python-announce-list** to keep up with newly released
third party-modules or software for Python and the general discussion
list **Python-list**. These lists are mirrored to the Usenet newsgroups
**comp.lang.python.announce** & **comp.lang.python**.

## Notes

[^1]: The Things I Hate About IDLE That I Wish Someone Would
    Fix.


# Python Programming/Interactive mode

Python has two basic modes: script and interactive. The normal mode is
the mode where the scripted and finished `.py` files are run in the
Python interpreter. Interactive mode is a command line shell which gives
immediate feedback for each statement, while running previously fed
statements in active memory. As new lines are fed into the interpreter,
the fed program is evaluated both in part and in whole.

Interactive mode is a good way to play around and try variations on
syntax.

On macOS or linux, open a terminal and simply type \"python\". On
Windows, bring up the command prompt and type \"py\", or start an
interactive Python session by selecting \"Python (command line)\",
\"IDLE\", or similar program from the task bar / app menu. IDLE is a GUI
which includes both an interactive mode and options to edit and run
files.

Python should print something like this:

`$ `**`python`**\
`Python 3.0b3 (r30b3:66303, Sep  8 2008, 14:01:02) [MSC v.1500 32 bit (Intel)] on win32`\
`Type "help", "copyright", "credits" or "license" for more information.`\
`>>>`

(If Python doesn\'t run, make sure it is installed and your path is set
correctly. See Getting
Python.)

The `>>>` is Python\'s way of telling you that you are in interactive
mode. In interactive mode what you type is immediately run. Try typing
`1+1` in. Python will respond with `2`. Interactive mode allows you to
test out and see what Python will do. If you ever feel the need to play
with new Python statements, go into interactive mode and try them out.

A sample interactive session:

`>>> `**`5`**\
`5`\
`>>> `**`print(5*7)`**\
`35`\
`>>> `**`"hello" * 2`**\
`'hellohello'`\
`>>> `**`"hello".__class__`**\
`<type 'str'>`

However, you need to be careful in the interactive environment to avoid
confusion. For example, the following is a valid Python script:

``` python
if 1:
  print("True")
print("Done")
```

If you try to enter this as written in the interactive environment, you
might be surprised by the result:

`>>> `**`if 1:`**\
`...   `**`print("True")`**\
`... `**`print("Done")`**\
`  File "``<stdin>`{=html}`", line 3`\
`    print("Done")`\
`        ^`\
`SyntaxError: invalid syntax`

What the interpreter is saying is that the indentation of the second
print was unexpected. You should have entered a blank line to end the
first (i.e., \"if\") statement, before you started writing the next
print statement. For example, you should have entered the statements as
though they were written:

``` python
if 1:
  print("True")

print("Done")
```

Which would have resulted in the following:

`>>> `**`if 1:`**\
`...   `**`print("True")`**\
`...`\
`True`\
`>>> `**`print("Done")`**\
`Done`\
`>>>`

### Interactive mode

Instead of Python exiting when the program is finished, you can use the
-i flag to start an interactive session. This can be **very** useful for
debugging and prototyping.

`python -i hello.py`


# Python Programming/Self Help

This book is useful for learning Python, but there might be a topic that
the book does not cover. You might want to search for modules in the
standard library, or inspect an unknown object\'s functions, or perhaps
you know there is a function that you have to call inside an object but
you don\'t know its name. This is where the interactive help comes into
play.

## Built-in help overview

Built-in interactive help at a glance:

``` python
help()      # Starts an interactive help
help("topics")  # Outputs the list of help topics
help("OPERATORS") # Shows help on the topic of operators
help("len")    # Shows help on len function
help("re")    # Shows help on re module
help("re.sub")  # Shows help on sub function from re module
help(len)     # Shows help on the object passed, the len function
help([].pop)   # Shows help on the pop function of a list
dir([])      # Outputs a list of attributes of a list, which includes functions
import re
help(re)     # Shows help on the help module
help(re.sub)   # Shows help on the sub function of re module
help(1)      # Shows help on int type
help([])     # Shows help on list type
help(def)     # Fails: def is a keyword that does not refer to an object
help("def")    # Shows help on function definitions
```

## Navigating Help

To start Python\'s interactive help, type \"help()\" at the prompt.

`>>>help()`

You will be presented with a greeting and a quick introduction to the
help system. For Python 2.6, the prompt will look something like this:

`Welcome to Python 2.6! 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".`

Notice also that the prompt will change from \"`>>>`\" (three right
angle brackets) to \"help\>\" You can access the different portions of
help simply by typing in `modules`, `keywords`, or `topics`.

Typing in the name of one of these will print the help page associated
with the item in question. 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\".

You can exit the help system by typing \"quit\" or by entering a blank
line to return to the interpreter.

## Help Parameter

You can obtain information on a specific command without entering
interactive help.

For example, you can obtain help on a given topic simply by adding a
string in quotes, such as `help("object")`. You may also obtain help on
a given object as well, by passing it as a parameter to the help
function.

## External links

-   help in 2.
    Built-in Functions, docs.python.org


# Python Programming/Creating Python programs

Welcome to Python! This tutorial will show you how to start writing
programs.

Python programs are nothing more than text files, and they may be edited
with a standard text editor program.[^1]
What text editor you use will probably depend on your operating system:
any text editor can create Python programs. However, it is easier to use
a text editor that includes Python syntax
highlighting.

## Hello, World

The very first program that beginning programmers usually write or learn
is the \"Hello, World!\"
program. This program simply
outputs the phrase \"Hello, World!\" then terminates itself. Let\'s
write \"Hello, World!\" in Python!

Open up your text editor and create a new file called `hello.py`
containing just this line (you can copy-paste if you want):

``` python
print('Hello, World!')
```

The below line is used for Python 3.x.x

``` python
print("Hello, World!")
```

You can also put the below line to pause the program at the end until
you press anything.

``` python
input()
```

This program uses the `print` function, which simply outputs its
parameters to the terminal. By default, `print` appends a `newline`
character to its output, which simply moves the cursor to the next line.

Now that you\'ve written your first program, let\'s run it in Python!
This process differs slightly depending on your operating system.

### Windows

-   Create a folder on your computer to use for your Python programs,
    such as `C:\pythonpractice`, and save your `hello.py` program in
    that folder.
-   In the Start menu, select \"Run\...\", and type in `cmd`. This will
    cause the Windows terminal to open.
-   Type `cd \pythonpractice` to **c**hange **d**irectory to your
    `pythonpractice` folder, and hit Enter.
-   Type `hello.py` to run your program!

If it didn\'t work, make sure your PATH contains the python directory.
See Getting Python.

### Mac

-   Create a folder on your computer to use for your Python programs. A
    good suggestion would be to name it `pythonpractice` and place it in
    your Home folder (the one that contains folders for Documents,
    Movies, Music, Pictures, etc). Save your `hello.py` program into it.
    Open the Applications folder, go into the Utilities folder, and open
    the Terminal program.
-   Type `cd pythonpractice` to **c**hange **d**irectory to your
    `pythonpractice` folder, and hit Enter.
-   Type `python ./hello.py` to run your program!

### Linux

-   Create a folder on your computer to use for your Python programs,
    such as `~/pythonpractice`, and save your `hello.py` program in that
    folder.
-   Open up the terminal program. In KDE, open the main menu and select
    \"Run Command\...\" to open . In GNOME,
    open the main menu, open the Applications folder, open the
    Accessories folder, and select Terminal.
-   Type `cd ~/pythonpractice` to **c**hange **d**irectory to your
    `pythonpractice` folder, and hit Enter.
-   Don\'t forget to make the script executable by chmod +x.
-   Type `python ./hello.py` to run your program!

### Linux (advanced)

-   Create a folder on your computer to use for your Python programs,
    such as `~/pythonpractice`.

```{=html}
<!-- -->
```
-   Open up your favorite text editor and create a new file called
    `hello.py` containing just the following 2 lines (you can copy-paste
    if you want):`<ref>`{=html}

A Quick Introduction to Unix/My First Shell
Script
explains what a hash bang line does.

```{=html}
</ref>
```
``` python
#! /usr/bin/python
print('Hello, world!')
```

-   save your `hello.py` program in the `~/pythonpractice` folder.
-   Open up the terminal program. In KDE, open the main menu and select
    \"Run Command\...\" to open Konsole. In GNOME, open the main menu,
    open the Applications folder, open the Accessories folder, and
    select Terminal.
-   Type `cd ~/pythonpractice` to **c**hange **d**irectory to your
    `pythonpractice` folder, and hit Enter.
-   Type `chmod a+x hello.py` to tell Linux that it is an executable
    program.
-   Type `./hello.py` to run your program!
-   In addition, you can also use `ln -s hello.py /usr/bin/hello` to
    make a **s**ymbolic **l**i**n**k `hello.py` to `/usr/bin` under the
    name `hello`, then run it by simply executing `hello`.

Note that this mainly should be done for complete, compiled programs, if
you have a script that you made and use frequently, then it might be a
good idea to put it somewhere in your home directory and put a link to
it in /usr/bin. If you want a playground, a good idea is to invoke
`mkdir ~/.local/bin` and then put scripts in there. To make
\~/.local/bin content executable the same way /usr/bin does type
`$PATH = $PATH:~/local/bin` (you can add this line to your shell rc
file, for example \~/.bashrc).

### Result

The program should print:

`Hello, world!`

Congratulations! You\'re well on your way to becoming a Python
programmer.

## Exercises

1.  Modify the `hello.py` program to say hello to someone from your
    family or your friends (or to Ada
    Lovelace).
2.  Change the program so that after the greeting, it asks, \"How did
    you get here?\".
3.  Re-write the original program to use two `print` statements: one for
    \"Hello\" and one for \"world\". The program should still only print
    out on one line.

Solutions

## Notes

```{=html}
<references />
```
\_\_NOTOC\_\_

[^1]: Sometimes, Python programs are distributed in compiled form. We
    won\'t have to worry about that for quite a while.


# Python Programming/Variables and Strings

In this section, you will be introduced to two different kinds of data
in Python: variables and strings. Please follow along by running the
included programs and examining their output.

## Variables

A *variable* is something that holds a value that may change. In
simplest terms, a variable is just a box that you can put stuff in. You
can use variables to store all kinds of stuff, but for now, we are just
going to look at storing numbers in variables.

``` python
lucky = 7
print (lucky)
7
```

This code creates a variable called `lucky`, and assigns to it the
integer number `7`. When we ask Python to tell us what is stored in the
variable `lucky`, it returns that number again.

We can also change what is inside a variable. For example:

``` python

changing = 3
print (changing)
3

changing = 9
print (changing)
9

different = 12
print (different)
12
print (changing)
9

changing = 15
print (changing)
15
```

We declare a variable called `changing`, put the integer `3` in it, and
verify that the assignment was properly done. Then, we assign the
integer `9` to `changing`, and ask again what is stored in `changing`.
Python has thrown away the `3`, and has replaced it with `9`. Next, we
create a second variable, which we call `different`, and put `12` in it.
Now we have two independent variables, `different` and `changing`, that
hold different information, i.e., assigning a new value to one of them
is not affecting the other.

You can also assign the value of a variable to be the value of another
variable. For example:

``` python
red = 5
blue = 10
print (red, blue)
5 10

yellow = red
print (yellow, red, blue)
5 5 10

red = blue
print (yellow, red, blue)
5 10 10
```

To understand this code, keep in mind that the **name** of the variable
is always on the left side of the equals sign (the assignment operator),
and the **value** of the variable is on the right side of the equals
sign. First the name, then the value.

We start out declaring that `red` is `5`, and `blue` is `10`. As you can
see, you can pass several arguments to `print` to tell it to print
multiple items on one line, separating them by spaces. As expected,
Python reports that `red` stores `5`, and `blue` holds `10`.

Now we create a third variable, called `yellow`. To set its value, we
tell Python that we want `yellow` to be whatever `red` is. (Remember:
name to the left, value to the right.) Python knows that `red` is `5`,
so it also sets `yellow` to be `5`.

Now we\'re going to take the `red` variable, and set it to the value of
the `blue` variable. Don\'t get confused --- name on the left, value on
the right. Python looks up the value of `blue`, and finds that it is
`10`. So, Python throws away `red`\'s old value (`5`), and replaces it
with `10`. After this assignment Python reports that `yellow` is `5`,
`red` is `10`, and `blue` is `10`.

But didn\'t we say that `yellow` should be whatever value `red` is? The
reason that `yellow` is still `5` when `red` is `10`, is because we only
said that `yellow` should be whatever `red` is *at the moment of the
assignment.* After Python has figured out what `red` is and assigned
that value to `yellow`, `yellow` doesn\'t care about `red` any more.
`yellow` has a value now, and that value is going to stay the same no
matter what happens to `red`.

For the **name** of the variable, it can only consist of uppercase and
lowercase letters (A-Z, a-z), digits (0-9), and the underscore character
(\_), and the *first* character of the name *cannot* be a digit. For
example, `1abc` and `_#$ad` are *not* valid variable names, while `_123`
and `a__bc` are valid variable names.

## String

A \'string\' is simply a list of characters in order. A *character* is
anything you can type on the keyboard in one keystroke, like a letter, a
number, or a backslash. For example, \"`hello`\" is a string. It is five
characters long --- `h`, `e`, `l`, `l`, `o`. Strings can also have
spaces: \"`hello world`\" contains 11 characters: 10 letters and the
space between \"`hello`\" and \"`world`\". There are no limits to the
number of characters you can have in a string --- you can have anywhere
from one to a million or more. You can even have a string that has 0
characters, which is usually called an \"empty string.\"

There are three ways you can declare a string in Python: single quotes
(`'`), double quotes (`"`), and triple quotes (`"""`). **In all cases,
you start and end the string with your chosen string declaration.** For
example:

``` python
>>> print ('I am a single quoted string')
I am a single quoted string
>>> print ("I am a double quoted string")
I am a double quoted string
>>> print ("""I am a triple quoted string""")
I am a triple quoted string
```

You can use quotation marks within strings by placing a backslash
directly before them, so that Python knows you want to include the
quotation marks in the string, instead of ending the string there.
Placing a backslash directly before another symbol like this is known as
*escaping* the symbol.

``` python
>>> print ("So I said, \"You don't know me! You'll never understand me!\"")
So I said, "You don't know me! You'll never understand me!"
>>> print ('So I said, "You don\'t know me! You\'ll never understand me!"')
So I said, "You don't know me! You'll never understand me!"
>>> print ("""The double quotation mark (\") is used to indicate direct quotations.""")
The double quotation mark (") is used to indicate direct quotations.
```

If you want to include a backslash in a string, you have to escape said
backslash. This tells Python that you want to include the backslash in
the string, instead of using it as an escape character. For example:

``` python
>>> print ("This will result in only three backslashes: \\ \\ \\")
This will result in only three backslashes: \ \ \
```

As you can see from the above examples, only the specific character used
to quote the string needs to be escaped. This makes for more readable
code.

To see how to use strings, let\'s go back for a moment to an old,
familiar program:

``` python
>>> print("Hello, world!")
Hello, world!
```

Look at that! You\'ve been using strings since the very beginning!

You can add two strings together using the `+` operator: this is called
*concatenating* them.

``` python
>>> print ("Hello, " + "world!")
Hello, world!
```

Notice that there is a space at the end of the first string. If you
don\'t put that in, the two words will run together, and you\'ll end up
with `Hello,world!`

You can also repeat strings by using the `*` operator, like so:

``` python
>>> print ("bouncy " * 5)
bouncy bouncy bouncy bouncy bouncy
>>> print ("bouncy " * 10)
bouncy bouncy bouncy bouncy bouncy bouncy bouncy bouncy bouncy bouncy
```

The string `bouncy` gets repeated 5 times in the 1st example and 10
times in the 2nd.

If you want to find out how long a string is, you use the `len()`
function, which simply takes a string and counts the number of
characters in it. (`len` stands for \"length.\") Just put the string
that you want to find the length of *inside* the parentheses of the
function. For example:

``` python
>>> print (len("Hello, world!"))
13
```

## Strings and Variables

Now that you\'ve learned about variables and strings separately, let\'s
see how they work together.

Variables can store much more than just numbers. You can also use them
to store strings! Here\'s how:

``` python
question = "What did you have for lunch?"
print (question)
What did you have for lunch?
```

In this program, we are creating a variable called `question`, and
storing the string \"`What did you have for lunch?`\" in it. Then, we
just tell Python to print out whatever is inside the `question`
variable. Notice that when we tell Python to print out `question`, there
are **no quotation marks** around the word `question`: this tells Python
that we are using a variable, not a string. If we put in quotation marks
around `question`, Python would treat it as a string, as shown below:

``` python
question = "What did you have for lunch?"
print ("question")
question
```

Let\'s try something different. Sure, it\'s all fine and dandy to ask
the user what they had for lunch, but it doesn\'t make much difference
if they can\'t respond! Let\'s edit this program so that the user can
type in what they ate.

``` python
question = "What did you have for lunch?"
print (question)
answer = raw_input() #You should use "input()" in python 3.x, because python 3.x doesn't have a function named "raw_input".

print ("You had " + answer + "! That sounds delicious!")
```

To ask the user to write something, we used a function called
`raw_input()`, which waits until the user writes something and presses
enter, and then returns what the user wrote. Don\'t forget the
parentheses! Even though there\'s nothing inside of them, they\'re still
important, and Python will give you an error if you don\'t put them in.
You can also use a different function called `input()`, which works in
nearly the same way. We will learn the differences between these two
functions later.

In this program, we created a variable called `answer`, and put whatever
the user wrote into it. Then, we print out a new string, which contains
whatever the user wrote. Notice the extra space at the end of the
\"`You had`\" string, and the exclamation mark at the start of the
\"`! That sounds delicious!`\" string. They help format the output and
make it look nice, so that the strings don\'t all run together.

## Combining Numbers and Strings

Take a look at this program, and see if you can figure out what it\'s
supposed to do.

``` python
print ("Please give me a number: ")
number = raw_input()

plusTen = number + 10
print ("If we add 10 to your number, we get " + plusTen)
```

This program should take a number from the user, add 10 to it, and print
out the result. But if you try running it, it won\'t work! You\'ll get
an error that looks like this:

`Traceback (most recent call last):`\
`  File "test.py", line 5, in ``<module>`{=html}\
`    print "If we add 10 to your number, we get " + plusTen`\
`TypeError: cannot concatenate 'str' and 'int' objects`

What\'s going on here? Python is telling us that there is a `TypeError`,
which means there is a problem with the types of information being used.
Specifically, Python can\'t figure out how to reconcile the two types of
data that are being used simultaneously: integers and strings. For
example, Python thinks that the `number` variable is holding a string,
instead of a number. If the user enters `15`, then `number` will contain
a string that is two characters long: a `1`, followed by a `5`. So how
can we tell Python that `15` should be a number, instead of a string?

Also, when printing out the answer, we are telling Python to concatenate
together a string (\"`If we add 10 to your number, we get`\") and a
number (`plusTen`). Python doesn\'t know how to do that \-- it can only
concatenate strings together. How do we tell Python to treat a number as
a string, so that we can print it out with another string?

Luckily, there are two functions that are perfect solutions for these
problems. The `int()` function will take a string and turn it into an
integer, while the `str()` function will take an integer and turn it
into a string. In both cases, we put what we want to change inside the
parentheses. Therefore, our modified program will look like this:

``` python
print ("Please give me a number:",)
response = raw_input()

number = int(response)
plusTen = number + 10

print ("If we add 10 to your number, we get " + str(plusTen))
```

That\'s all you need to know about strings and variables! We\'ll learn
more about types later.

## List of Learned Functions

-   **`print()`**: Print the output information to the user
-   **`input()`** or **`raw_input()`**: asks the user for a response,
    and returns that response. (Note that in version 3.x
    **`raw_input()`** does not exist and has been replaced by
    **`input()`**)
-   **`len()`**: returns the length of a string (number of characters)
-   **`str()`**: returns the string representation of an object
-   **`int()`**: given a string or number, returns an integer

## Exercises

1.  Write a program that asks the user to type in a string, and then
    tells the user how long that string was.
2.  Ask the user for a string, and then for a number. Print out that
    string, that many times. (For example, if the string is `hello` and
    the number is `3` you should print out `hello hello hello`.)
3.  What would happen if a mischievous user typed in a word when you ask
    for a number? Try it.

Solutions

`<span style="font-size: 14pt;">`{=html}Quiz`</span>`{=html}


# Python Programming/Basic syntax

There are five fundamental concepts in
Python.

### Semicolons

Python does not normally use semicolons, but they are allowed to
separate statements on the same line, if your code has semicolons; your
code isn\'t \"Pythonic\"

### Case Sensitivity

All variables are case-sensitive. Python treats \'number\' and
\'Number\' as separate, unrelated entities.

### Spaces and tabs don\'t mix

Instead of block delimiters (braces → \"{}\" in the C family of
languages), indentation is used to indicate where blocks begin and end.
Because whitespace is significant, remember that spaces and tabs don\'t
mix, so use only one or the other when indenting your programs. A common
error is to mix them. While they may look the same in editor, the
interpreter will read them differently and it will result in either an
error or unexpected behavior. Most decent text editors can be configured
to let tab key emit spaces instead.

Python\'s Style Guideline described that the preferred way is using 4
spaces.

Tips: If you invoked python from the command-line, you can give -t or
-tt argument to python to make python issue a warning or error on
inconsistent tab usage.

``` bash
pythonprogrammer@wikibook:~$ python -tt myscript.py
```

This will issue an error if you have mixed spaces and tabs.

### Objects

In Python, like all object-oriented languages, there are aggregations of
code and data called *objects*, which typically represent the pieces in
a conceptual model of a system.

Objects in Python are created (i.e., instantiated) from templates called
*classes* (which are covered
later, as much of the language can be used without understanding
classes). They have *attributes*, which represent the various pieces of
code and data which make up the object. To access attributes, one writes
the name of the object followed by a period (henceforth called a dot),
followed by the name of the attribute.

An example is the \'upper\' attribute of strings, which refers to the
code that returns a copy of the string in which all the letters are
uppercase. To get to this, it is necessary to have a way to refer to the
object (in the following example, the way is the literal string that
constructs the object).

``` python
'bob'.upper
```

Code attributes are called *methods*. So in this example, upper is a
method of \'bob\' (as it is of all strings). To execute the code in a
method, use a matched pair of parentheses surrounding a comma separated
list of whatever arguments the method accepts (upper doesn\'t accept any
arguments). So to find an uppercase version of the string \'bob\', one
could use the following:

``` python
'bob'.upper()
```

### Scope

In a large system, it is important that one piece of code does not
affect another in difficult to predict ways. One of the simplest ways to
further this goal is to prevent one programmer\'s choice of a name from
blocking another\'s use of that name. The concept of scope was invented
to do this. A scope is a \"region\" of code in which a name can be used
and outside of which the name cannot be easily accessed. There are two
ways of delimiting regions in Python: with functions or with modules.
They each have different ways of accessing from outside the scope useful
data that was produced within the scope. With functions, that way is to
return the data. The way to access names from other modules leads us to
another concept.

### Namespaces

It would be possible to teach Python without the concept of namespaces
because they are so similar to attributes, which we have already
mentioned, but the concept of namespaces is one that transcends any
particular programming language, and so it is important to teach. To
begin with, there is a built-in function **`dir()`** that can be used to
help one understand the concept of namespaces. When you first start the
Python interpreter (i.e., in interactive mode), you can list the objects
in the current (or default) namespace using this function.

``` python
Python 2.3.4 (#53, Oct 18 2004, 20:35:07) [MSC v.1200 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> dir()
['__builtins__', '__doc__', '__name__']
```

This function can also be used to show the names available within a
module\'s namespace. To demonstrate this, first we can use the
**`type()`** function to show what kind of object \_\_builtins\_\_ is:

``` python
>>> type(__builtins__)
<type 'module'>
```

Since it is a module, it has a namespace. We can list the names within
the \_\_builtins\_\_ namespace, again using the **`dir()`** function
(note that the complete list of names has been abbreviated):

``` python
>>> dir(__builtins__)
['ArithmeticError', ... 'copyright', 'credits', ... 'help', ... 'license', ... 'zip']
>>>
```

Namespaces are a simple concept. A namespace is a particular place in
which names specific to a module reside. Each name within a namespace is
distinct from names outside of that namespace. This layering of
namespaces is called scope. A name is placed within a namespace when
that name is given a value. For example:

``` python
>>> dir()
['__builtins__', '__doc__', '__name__']
>>> name = "Bob"
>>> import math
>>> dir()
['__builtins__', '__doc__', '__name__', 'math', 'name']
```

Note that I was able to add the \"name\" variable to the namespace using
a simple assignment statement. The import statement was used to add the
\"math\" name to the current namespace. To see what math is, we can
simply:

``` python
>>> math
<module 'math' (built-in)>
```

Since it is a module, it also has a namespace. To display the names
within this namespace, we:

``` python
>>> dir(math)
['__doc__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e',
'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow',
'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh']
>>>
```

If you look closely, you will notice that both the default namespace and
the math module namespace have a \'\_\_name\_\_\' object. The fact that
each layer can contain an object with the same name is what scope is all
about. To access objects inside a namespace, simply use the name of the
module, followed by a dot, followed by the name of the object. This
allows us to differentiate between the `__name__` object within the
current namespace, and that of the object with the same name within the
`math` module. For example:

``` python
>>> print (__name__)
__main__
>>> print (math.__name__)
math
>>> print (math.__doc__)
This module is always available.  It provides access to the
mathematical functions defined by the C standard.
>>> print (math.pi)
3.1415926535897931
```


# Python Programming/Sequences

Sequences allow you to store multiple values in an organized and
efficient fashion. There are seven sequence types: strings, bytes,
lists, tuples, bytearrays, buffers, and range objects. Dictionaries and
sets are containers for sequential data.

## Strings

We already covered strings, but that was before you knew what a sequence
is. In other languages, the elements in arrays and sometimes the
characters in strings may be accessed with the square brackets, or
subscript operator. This works in Python too:

``` python
>>> "Hello, world!"[0]
'H'
>>> "Hello, world!"[1]
'e'
>>> "Hello, world!"[2]
'l'
>>> "Hello, world!"[3]
'l'
>>> "Hello, world!"[4]
'o'
```

Indexes are numbered from 0 to n-1 where n is the number of items (or
characters), and they are given to the characters from the start of the
string:

     H  e  l  l  o  ,     w  o  r  l  d  !
     0  1  2  3  4  5  6  7  8  9 10 11 12

Negative indexes (numbered from -1 to -n) are counted from the end of
the string:

     H   e   l   l   o   ,       w   o   r  l  d  !
    -13 -12 -11 -10 -9  -8  -7  -6  -5  -4 -3 -2 -1

``` python
>>> "Hello, world!"[-2]
'd'
>>> "Hello, world!"[-9]
'o'
>>> "Hello, world!"[-13]
'H'
>>> "Hello, world!"[-1]
'!'
```

If the number given in the bracket is less than -n or greater than n-1,
then we will get an IndexError.

But in Python, the colon : allows the square brackets to take two
numbers. For any sequence which only uses numeric indexes, this will
return the portion which is between the specified indexes. This is known
as \"slicing\" and the result of slicing a string is often called a
\"substring.\"

``` python
>>> "Hello, world!"[3:9]
'lo, wo'
>>> string = "Hello, world!"
>>> string[:5]
'Hello'
>>> string[-6:-1]
'world'
>>> string[-9:]
'o, world!'
>>> string[:-8]
'Hello'
>>> string[:]
'Hello, world!'
```

As demonstrated above, if the first and second number is omitted, then
they take their default values, which are 0 and n-1 respectively,
corresponding to the beginning and end of the sequence respectively (in
this case). Note also that the brackets are inclusive on the left but
*exclusive* on the right: in the first example above with \[3:9\] the
character at index 3, \'l\', is included while the character at index 9,
\'r\', is excluded.

We can add a third number in the bracket, by adding one more colon in
the bracket, which indicates the *increment step* of the slicing:

``` python
>>> s = "Hello, world!"
>>> s[3:9:2] #returns the substring s[3]s[5]s[7]
'l,w'
>>> s[3:6:3] #returns the substring s[3]
'l'
>>> s[:5:2] #returns the substring s[0]s[2]s[4]
'Hlo'
>>> s[::-1] #returns the reverted string
'!dlrow ,olleH'
>>> s[::-2] #returns the substring s[-1]s[-3]s[-5]s[-7]s[-9]s[-11]s[-13]
'!lo olH'
```

The increment step can be positive or negative. For positive increment
step, the slicing is from left to right, and for negative increment
step, the slicing is from right to left. Also, we should aware that

-   the default value of the increment step is 1

```{=html}
<!-- -->
```
-   the default value for the first and second number becomes -1 (or n)
    and -n (or 0) respectively, when the increment step is negative
    (same default value as above when the increment step is positive)
-   the increment step cannot be 0

## Lists

A list is just what it sounds like: a list of values, organized in
order. A list is created using square brackets. For example, an empty
list would be initialized like this:

``` python
spam = []
```

The values of the list are separated by commas. For example:

``` python
spam = ["bacon", "eggs", 42]
```

Lists may contain objects of varying types. It may hold both the strings
\"eggs\" and \"bacon\" as well as the number 42.

Like characters in a string, items in a list can be accessed by indexes
starting at 0. To access a specific item in a list, you refer to it by
the name of the list, followed by the item\'s number in the list inside
brackets. For example:

``` python
>>> spam
['bacon', 'eggs', 42]
>>> spam[0]
'bacon'
>>> spam[1]
'eggs'
>>> spam[2]
42
```

You can also use negative numbers, which count backwards from the end of
the list:

``` python
>>> spam[-1]
42
>>> spam[-2]
'eggs'
>>> spam[-3]
'bacon'
```

The `len()` function also works on lists, returning the number of items
in the array:

``` python
>>> len(spam)
3
```

Note that the `len()` function counts the number of item inside a list,
so the last item in spam (42) has the index (len(spam) - 1).

The items in a list can also be changed, just like the contents of an
ordinary variable:

``` python
>>> spam = ["bacon", "eggs", 42]
>>> spam
['bacon', 'eggs', 42]
>>> spam[1]
'eggs'
>>> spam[1] = "ketchup"
>>> spam
['bacon', 'ketchup', 42]
```

(Strings, being *immutable*, are impossible to modify.) As with strings,
lists may be sliced:

``` python
>>> spam[1:]
['eggs', 42]
>>> spam[:-1]
['bacon', 'eggs']
```

It is also possible to add items to a list. There are many ways to do
it, the easiest way is to use the append() method of list:

``` python
>>> spam.append(10)
>>> spam
['bacon', 'eggs', 42, 10]
```

Note that you cannot manually insert an element by specifying the index
outside of its range. The following code would fail:

``` python
>>> spam[4] = 10
IndexError: list assignment index out of range
```

Instead, you must use the insert() function. If you want to insert an
item inside a list at a certain index, you may use the insert() method
of list, for example:

``` python
>>> spam.insert(1, 'and')
>>> spam
['bacon', 'and', 'eggs', 42, 10]
```

You can also delete items from a list using the `del` statement:

``` python
>>> spam
['bacon', 'and', 'eggs', 42, 10]
>>> del spam[1]
>>> spam
['bacon', 'eggs', 42, 10]
>>> spam[0]
'bacon'
>>> spam[1]
'eggs'
>>> spam[2]
42
>>> spam[3]
10
```

As you can see, the list re-orders itself, so there are no gaps in the
numbering.

Lists have an unusual characteristic. Given two lists a and b, if you
set b to a, and change a, b will also be changed.

``` python
>>> a=[2, 3, 4, 5]
>>> b=a
>>> del a[3]
>>> print(a)
[2, 3, 4]
>>> print(b)
[2, 3, 4]
```

This can easily be worked around by using `b=a[:]` instead.

For further explanation on lists, or to find out how to make 2D arrays,
see Data Structure/Lists

## Tuples

Tuples are similar to lists, except they are immutable. Once you have
set a tuple, there is no way to change it whatsoever: you cannot add,
change, or remove elements of a tuple. Otherwise, tuples work
identically to lists.

To declare a tuple, you use commas:

``` python
unchanging = "rocks", 0, "the universe"
```

It is often necessary to use parentheses to differentiate between
different tuples, such as when doing multiple assignments on the same
line:

``` python
foo, bar = "rocks", 0, "the universe" # 3 elements here
foo, bar = "rocks", (0, "the universe") # 2 elements here because the second element is a tuple
```

Unnecessary parentheses can be used without harm, but nested parentheses
denote nested tuples:

``` python
>>> var = "me", "you", "us", "them"
>>> var = ("me", "you", "us", "them")
```

both produce:

``` python
>>> print(var)
('me', 'you', 'us', 'them')
```

but:

``` python
>>> var = ("me", "you", ("us", "them"))
>>> print(var)
('me', 'you', ('us', 'them')) # A tuple of 3 elements, the last of which is itself a tuple.
```

For further explanation on tuple, see *Data
Structure/Tuples*

## Dictionaries

Dictionaries are also like lists, and they are mutable \-- you can add,
change, and remove elements from a dictionary. However, the elements in
a dictionary are not bound to numbers, the way a list is. Every element
in a dictionary has two parts: a key, and a value. Calling a key of a
dictionary returns the value linked to that key. You could consider a
list to be a special kind of dictionary, in which the key of every
element is a number, in numerical order.

Dictionaries are declared using curly braces, and each element is
declared first by its key, then a colon, and then its value. For
example:

``` python
>>> definitions = {"guava": "a tropical fruit", "python": "a programming language", "the answer": 42}
>>> definitions
{'python': 'a programming language', 'the answer': 42, 'guava': 'a tropical fruit'}
>>> definitions["the answer"]
42
>>> definitions["guava"]
'a tropical fruit'
>>> len(definitions)
3
```

Also, adding an element to a dictionary is much simpler: simply declare
it as you would a variable.

``` python
>>> definitions["new key"] = "new value"
>>> definitions
{'python': 'a programming language', 'the answer': 42, 'guava': 'a tropical fruit', 'new key': 'new value'}
```

For further explanation on dictionary, see *Data
Structure/Dictionaries*

## Sets

Sets are just like lists except that they are **unordered** and they do
not allow duplicate values. Elements of a set are neither bound to a
number (like list and tuple) nor to a key (like dictionary). The reason
for using a set over other data types is that a set is much faster for a
large number of items than a list or tuple and sets provide fast data
insertion, deletion, and membership testing. Sets also support
mathematical set operations such as testing for subsets and finding the
union or intersection of two sets.

``` python
>>> mind = set([42, 'a string', (23, 4)]) #equivalently, we can use {42, 'a string', (23, 4)}
>>> mind
set([(23, 4), 42, 'a string'])
```

``` python
>>> mind = set([42, 'a string', 40, 41])
>>> mind
set([40, 41, 42, 'a string'])
>>> mind = set([42, 'a string', 40, 0])
>>> mind
set([40, 0, 42, 'a string'])
>>> mind.add('hello')
>>> mind
set([40, 0, 42, 'a string', 'hello'])
```

Note that sets are unordered, items you add into sets will end up in an
indeterminable position, and it may also change from time to time.

``` python
>>> mind.add('duplicate value')
>>> mind.add('duplicate value')
>>> mind
set([0, 'a string', 40, 42, 'hello', 'duplicate value'])
```

Sets cannot contain a single value more than once. Unlike lists, which
can contain anything, the types of data that can be included in sets are
restricted. A set can only contain hashable, immutable data types.
Integers, strings, and tuples are hashable; lists, dictionaries, and
other sets (except frozensets, see below) are not.

### Frozenset

The relationship between frozenset and set is like the relationship
between tuple and list. Frozenset is an immutable version of set. An
example:

``` python
>>> frozen=frozenset(['life','universe','everything'])
>>> frozen
frozenset(['universe', 'life', 'everything'])
```

## Other data types

Python also has other types of sequences, though these are used less
frequently and need to be imported from the standard library before
being used. We will only brush over them here.

array: A typed-list, an array may only contain homogeneous values.\
collections.defaultdict: A dictionary that, when an element is not found, returns a default value instead of error.\
collections.deque: A double ended queue, allows fast manipulation on both sides of the queue.\
heapq: A priority queue.\
Queue: A thread-safe multi-producer, multi-consumer queue for use with multi-threaded programs. Note that a list can also be used as queue in a single-threaded code.

For further explanation on set, see *Data
Structure/Sets*

### 3rd party data structure

Some useful data types in Python do not come in the standard library.
Some of these are very specialized in their use. We will mention some of
the more well known 3rd party types.

numpy.array: useful for heavy number crunching =\> see numpy section\
sorteddict: like the name says, a sorted dictionary

## Exercises

1.  Write a program that puts 5, 10, and \"twenty\" into a list. Then
    remove 10 from the list.
2.  Write a program that puts 5, 10, and \"twenty\" into a tuple.
3.  Write a program that puts 5, 10, and \"twenty\" into a set. Put
    \"twenty\", 10, and 5 into another set purposefully in a different
    order. Print both of them out and notice the ordering.
4.  Write a program that constructs a tuple, one element of which is a
    frozenset.
5.  Write a program that creates a dictionary mapping 1 to \"Monday,\" 2
    to \"Tuesday,\" etc.

## External links

-   Sequence Types --- list, tuple,
    range
    in The Python Library Reference, docs.python.org


# Python Programming/Data types

Data types determine whether an object can do something, or whether it
just would not make sense. Other programming languages often determine
whether an operation makes sense for an object by making sure the object
can never be stored somewhere where the operation will be performed on
the object (this type system
is called static typing). Python does not do that. Instead it stores the
type of an object with the object, and checks when the operation is
performed whether that operation makes sense for that object (this is
called dynamic typing).

##### Built-in Data types

Python\'s built-in (or standard) data types can be grouped into several
classes. Sticking to the hierarchy scheme used in the official Python
documentation these are **numeric types, sequences, sets and mappings**
(and a few more not discussed further here). Some of the types are only
available in certain versions of the language as noted below.

-   boolean: the type of the built-in values `True` and `False`. Useful
    in conditional expressions, and anywhere else you want to represent
    the truth or falsity of some condition. Mostly interchangeable with
    the integers 1 and 0. In fact, conditional expressions will accept
    values of any type, treating special ones like boolean `False`,
    integer 0 and the empty string `""` as equivalent to `False`, and
    all other values as equivalent to `True`.

Numeric types:

-   int: Integers; equivalent to C longs in Python 2.x, non-limited
    length in Python 3.x
-   long: Long integers of non-limited length; exists only in Python 2.x
-   float: Floating-Point numbers, equivalent to C doubles
-   complex: Complex Numbers

Sequences:

-   str: String; represented as a sequence of 8-bit characters in Python
    2.x, but as a sequence of Unicode characters (in the range of
    U+0000 - U+10FFFF) in Python 3.x
-   bytes: a sequence of integers in the range of 0-255; only available
    in Python 3.x
-   byte array: like bytes, but mutable (see below); only available in
    Python 3.x
-   list
-   tuple

Sets:

-   set: an unordered collection of unique objects; available as a
    standard type since Python 2.6
-   frozen set: like set, but immutable (see below); available as a
    standard type since Python 2.6

Mappings:

-   dict: Python dictionaries, also called hashmaps or associative
    arrays, which means that an element of the list is associated with a
    definition, rather like a Map in Java\

Some others, such as type and callables

##### Mutable vs Immutable Objects

In general, data types in Python can be distinguished based on whether
objects of the type are mutable or immutable. The content of objects of
immutable types cannot be changed after they are created.

+-------------------------+----------------------+
| Some *immutable* types  | Some *mutable* types |
+=========================+======================+
| -   int, float, complex | -   array            |
| -   str                 | -   bytearray        |
| -   bytes               | -   list             |
| -   tuple               | -   set              |
| -   frozenset           | -   dict             |
| -   bool                |                      |
+-------------------------+----------------------+

Only mutable objects support methods that change the object in place,
such as reassignment of a sequence slice, which will work for lists, but
raise an error for tuples and strings.

It is important to understand that variables in Python are really just
references to objects in memory. If you assign an object to a variable
as below,

``` python
a = 1
s = 'abc'
l = ['a string', 456, ('a', 'tuple', 'inside', 'a', 'list')]
```

all you really do is make this variable (`a`, `s`, or `l`) point to the
object (`1`, `'abc'`,
`['a string', 456, ('a', 'tuple', 'inside', 'a', 'list')]`), which is
kept somewhere in memory, as a convenient way of accessing it. If you
reassign a variable as below

``` python
a = 7
s = 'xyz'
l = ['a simpler list', 99, 10]
```

you make the variable point to a different object (newly created ones in
our examples). As stated above, only mutable objects can be changed in
place (`l[0] = 1` is ok in our example, but `s[0] = 'a'` raises an
error). This becomes tricky, when an operation is not explicitly asking
for a change to happen in place, as is the case for the `+=` (increment)
operator, for example. When used on an immutable object (as in `a += 1`
or in `s += 'qwertz'`), Python will silently create a new object and
make the variable point to it. However, when used on a mutable object
(as in `l += [1,2,3]`), the object pointed to by the variable will be
changed in place. While in most situations, you do not have to know
about this different behavior, it is of relevance when several variables
are pointing to the same object. In our example, assume you set `p = s`
and `m = l`, then `s += 'etc'` and `l += [9,8,7]`. This will change `s`
and leave `p` unaffected, but will change both `m` and `l` since both
point to the same list object. Python\'s built-in `id()` function, which
returns a unique object identifier for a given variable name, can be
used to trace what is happening under the hood.\
Typically, this behavior of Python causes confusion in functions. As an
illustration, consider this code:

``` python
def append_to_sequence (myseq):
    myseq += (9,9,9)
    return myseq

tuple1 = (1,2,3) # tuples are immutable
list1 = [1,2,3] # lists are mutable

tuple2 = append_to_sequence(tuple1)
list2 = append_to_sequence(list1)

print('tuple1 = ', tuple1) # outputs (1, 2, 3)
print('tuple2 = ', tuple2) # outputs (1, 2, 3, 9, 9, 9)
print('list1 = ', list1) # outputs [1, 2, 3, 9, 9, 9]
print('list2 = ', list2) # outputs [1, 2, 3, 9, 9, 9]
```

This will give the above indicated, and usually unintended, output.
`myseq` is a local variable of the `append_to_sequence` function, but
when this function gets called, `myseq` will nevertheless point to the
same object as the variable that we pass in (`t` or `l` in our example).
If that object is immutable (like a tuple), there is no problem. The +=
operator will cause the creation of a new tuple, and `myseq` will be set
to point to it. However, if we pass in a reference to a mutable object,
that object will be manipulated in place (so `myseq` and `l`, in our
case, end up pointing to the same list object).

Links:

-   3.1. Objects, values and
    types,
    The Python Language Reference, docs.python.org
-   5.6.4. Mutable Sequence
    Types,
    The Python Standard Library, docs.python.org

##### Creating Objects of Defined Types

Literal integers can be entered in three ways:

-   decimal numbers can be entered directly
-   hexadecimal numbers can be entered by prepending a 0x or 0X (0xff is
    hex FF, or 255 in decimal)
-   the format of octal literals depends on the version of Python:

:\* Python 2.x: octals can be entered by prepending a 0 (0732 is octal
732, or 474 in decimal)

:\* Python 3.x: octals can be entered by prepending a 0o or 0O (0o732 is
octal 732, or 474 in decimal)

Floating point numbers can be entered directly.

Long integers are entered either directly
(1234567891011121314151617181920 is a long integer) or by appending an L
(0L is a long integer). Computations involving short integers that
overflow are automatically turned into long integers.

Complex numbers are entered by adding a real number and an imaginary
one, which is entered by appending a j (i.e. 10+5j is a complex number.
So is 10j). Note that j by itself does not constitute a number. If this
is desired, use 1j.

Strings can be either single or triple quoted strings. The difference is
in the starting and ending delimiters, and in that single quoted strings
cannot span more than one line. Single quoted strings are entered by
entering either a single quote (\') or a double quote (\") followed by
its match. So therefore

`'foo' works, and`\
`"moo" works as well,`\
`     but`\
`'bar" does not work, and`\
`"baz' does not work either.`\
`"quux'' is right out.`

Triple quoted strings are like single quoted strings, but can span more
than one line. Their starting and ending delimiters must also match.
They are entered with three consecutive single or double quotes, so

`'''foo''' works, and`\
`"""moo""" works as well,`\
`     but`\
`'"'bar'"' does not work, and`\
`"""baz''' does not work either.`\
`'"'quux"'" is right out.`

Tuples are entered in parentheses, with commas between the entries:

``` python
(10, 'Mary had a little lamb')
```

Also, the parenthesis can be left out when it\'s not ambiguous to do so:

``` python
10, 'whose fleece was as white as snow'
```

Note that one-element tuples can be entered by surrounding the entry
with parentheses and adding a comma like so:

``` python
('this is a singleton tuple',)
```

Lists are similar, but with brackets:

``` python
['abc', 1,2,3]
```

Dicts are created by surrounding with curly braces a list of key/value
pairs separated from each other by a colon and from the other entries
with commas:

``` python
{ 'hello': 'world', 'weight': 'African or European?' }
```

Any of these composite types can contain any other, to any depth:

``` python
((((((((('bob',),['Mary', 'had', 'a', 'little', 'lamb']), { 'hello' : 'world' } ),),),),),),)
```

## Null object

The Python analogue of null pointer known from other programming
languages is *None*. *None* is not a null pointer or a null reference
but an actual object of which there is only one instance. One of the
uses of *None* is in default argument values of functions, for which see
../Functions#Default_Argument_Values.
Comparisons to *None* are usually made using *is* rather than ==.

Testing for None and assignment:

``` python
if item is None:
  ...
  another = None

if not item is None:
  ...

if item is not None: # Also possible
  ...
```

Using None in a default argument value:

``` python
def log(message, type = None):
  ...
```

PEP8 states that \"Comparisons to singletons like None should always be
done with is or is not, never the equality operators.\" Therefore, \"if
item == None:\" is inadvisable. A class can redefine the equality
operator (==) such that instances of it will equal None.

You can verify that None is an object by dir(None) or id(None).

See also ../Operators/#Identity
chapter.

Links:

-   4. Built-in
    Constants,
    docs.python.org
-   3.11.7 The Null
    Object,
    docs.python.org
-   Python None comparison: should I use "is" or
    ==?,
    stackoverflow.com
-   PEP 0008 \-- Style Guide for Python
    Code, python.org

## Type conversion

Type conversion in Python by example:

``` Python
v1 = int(2.7) # 2
v2 = int(-3.9) # -3
v3 = int("2") # 2
v4 = int("11", 16) # 17, base 16
v5 = long(2) # Python 2.x only, not Python 3.x
v6 = float(2) # 2.0
v7 = float("2.7") # 2.7
v8 = float("2.7E-2") # 0.027
v9 = float(False) # 0.0
vA = float(True) # 1.0
vB = str(4.5) # "4.5"
vC = str([1, 3, 5]) # "[1, 3, 5]"
vD = bool(0) # False; bool fn since Python 2.2.1
vE = bool(3) # True
vF = bool([]) # False - empty list
vG = bool([False]) # True - non-empty list
vH = bool({}) # False - empty dict; same for empty tuple
vI = bool("") # False - empty string
vJ = bool(" ") # True - non-empty string
vK = bool(None) # False
vL = bool(len) # True
vM = set([1, 2])
vN = set((1, 2)) # Converts any sequence, not just a list
vO = set("abc") # {'c', 'b', 'a'}
vP = set(b"abc") # {97, 98, 99}
vQ = list(vM)
vR = list({1: "a", 2: "b"}) # dict -> list of keys
vS = tuple(vQ)
vT = list("abc") # ['a', 'b', 'c']
print(v1, v2, v3, type(v1), type(v2), type(v3))
```

Implicit type conversion:

``` Python
int1 = 4
float1 = int1 + 2.1 # 4 converted to float
# str1 = "My int:" + int1 # Error: no implicit type conversion from int to string
str1 = "My int:" + str(int1)
int2 = 4 + True # 5: bool is implicitly converted to int
float2 = 4.5 + True # 5.5: True is converted to 1, which is converted to 1.0
```

Keywords: type casting.

Links:

-   2. Built-in Functions \#
    bool,
    docs.python.org
-   2. Built-in Functions \#
    list,
    docs.python.org
-   2. Built-in Functions \#
    float,
    docs.python.org
-   2. Built-in Functions \#
    int,
    docs.python.org
-   2. Built-in Functions \#
    set,
    docs.python.org
-   2. Built-in Functions \#
    str,
    docs.python.org
-   2. Built-in Functions \#
    type,
    docs.python.org
-   2. Built-in Functions \#
    tuple,
    docs.python.org

## Exercises

1.  Write a program that instantiates a single object, adds \[1,2\] to
    the object, and returns the result.
    1.  Find an object that returns an output of the same length (if one
        exists?).
    2.  Find an object that returns an output length 2 greater than it
        started.
    3.  Find an object that causes an error.
2.  Find two data types X and Y such that X = X + Y will cause an error,
    but X += Y will not.


# Python Programming/Numbers

Python 2.x supports 4 built-in numeric types - int, long, float and
complex. Of these, the long type has been dropped in Python 3.x - the
int type is now of unlimited length by default. You don't have to
specify what type of variable you want; Python does that automatically.

-   *Int:* The basic integer type in python, equivalent to the hardware
    \'c long\' for the platform you are using in Python 2.x, unlimited
    in length in Python 3.x.
-   *Long:* Integer type with unlimited length. In python 2.2 and later,
    Ints are automatically turned into long ints when they overflow.
    Dropped since Python 3.0, use int type instead.
-   *Float:* This is a binary floating point number. Longs and Ints are
    automatically converted to floats when a float is used in an
    expression, and with the true-division `/` operator. In CPython,
    floats are usually implemented using the C languages *double*, which
    often yields 52 bits of significand, 11 bits of exponent, and 1 sign
    bit, but this is machine dependent.
-   *Complex:* This is a complex number consisting of two floats.
    Complex literals are written as a + bj where a and b are
    floating-point numbers denoting the real and imaginary parts
    respectively.

In general, the number types are automatically \'up cast\' in this
order:

Int → Long → Float → Complex. The farther to the right you go, the
higher the precedence.

``` python
>>> x = 5
>>> type(x)
<type 'int'>
>>> x = 187687654564658970978909869576453
>>> type(x)
<type 'long'>
>>> x = 1.34763
>>> type(x)
<type 'float'>
>>> x = 5 + 2j
>>> type(x)
<type 'complex'>
```

The result of divisions is somewhat confusing. In Python 2.x, using the
/ operator on two integers will return another integer, using floor
division. For example, `5/2` will give you 2. You have to specify one of
the operands as a float to get true division, e.g. `5/2.` or `5./2` (the
dot specifies you want to work with float) will yield 2.5. Starting with
Python 2.2 this behavior can be changed to true division by the future
division statement `from __future__ import division`. In Python 3.x, the
result of using the / operator is always true division (you can ask for
floor division explicitly by using the // operator since Python 2.2).

This illustrates the behavior of the / operator in Python 2.2+:

``` python
>>> 5/2
2
>>> 5/2.
2.5
>>> 5./2
2.5
>>> from __future__ import division
>>> 5/2
2.5
>>> 5//2
2
```

For operations on numbers, see chapters ../Basic
Math/ and ../Math/.

## Links

-   5.4. Numeric Types --- int, float, long,
    complex,
    docs.python.org