{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "\n", "*This notebook contains an excerpt from the [Whirlwind Tour of Python](http://www.oreilly.com/programming/free/a-whirlwind-tour-of-python.csp) by Jake VanderPlas; the content is available [on GitHub](https://github.com/jakevdp/WhirlwindTourOfPython).*\n", "\n", "*The text and code are released under the [CC0](https://github.com/jakevdp/WhirlwindTourOfPython/blob/master/LICENSE) license; see also the companion project, the [Python Data Science Handbook](https://github.com/jakevdp/PythonDataScienceHandbook).*\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "< [Basic Python Semantics: Operators](04-Semantics-Operators.ipynb) | [Contents](Index.ipynb) | [Built-In Data Structures](06-Built-in-Data-Structures.ipynb) >" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Built-In Types: Simple Values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "When discussing Python variables and objects, we mentioned the fact that all Python objects have type information attached. Here we'll briefly walk through the built-in simple types offered by Python.\n", "We say \"simple types\" to contrast with several compound types, which will be discussed in the following section.\n", "\n", "Python's simple types are summarized in the following table:\n", "\n", "
**Python Scalar Types**
\n", "\n", "| Type | Example | Description |\n", "|-------------|----------------|--------------------------------------------------------------|\n", "| ``int`` | ``x = 1`` | integers (i.e., whole numbers) |\n", "| ``float`` | ``x = 1.0`` | floating-point numbers (i.e., real numbers) |\n", "| ``complex`` | ``x = 1 + 2j`` | Complex numbers (i.e., numbers with real and imaginary part) |\n", "| ``bool`` | ``x = True`` | Boolean: True/False values |\n", "| ``str`` | ``x = 'abc'`` | String: characters or text |\n", "| ``NoneType``| ``x = None`` | Special object indicating nulls |\n", "\n", "We'll take a quick look at each of these in turn." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Integers\n", "The most basic numerical type is the integer.\n", "Any number without a decimal point is an integer:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "int" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "x = 1\n", "type(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python integers are actually quite a bit more sophisticated than integers in languages like ``C``.\n", "C integers are fixed-precision, and usually overflow at some value (often near $2^{31}$ or $2^{63}$, depending on your system).\n", "Python integers are variable-precision, so you can do computations that would overflow in other languages:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1606938044258990275541962092341162602522202993782792835301376" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "2 ** 200" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Another convenient feature of Python integers is that by default, division up-casts to floating-point type:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2.5" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 / 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that this upcasting is a feature of Python 3; in Python 2, like in many statically-typed languages such as C, integer division truncates any decimal and always returns an integer:\n", "``` python\n", "# Python 2 behavior\n", ">>> 5 / 2\n", "2\n", "```\n", "To recover this behavior in Python 3, you can use the floor-division operator:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "5 // 2" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Finally, note that although Python *2.x* had both an ``int`` and ``long`` type, Python 3 combines the behavior of these two into a single ``int`` type." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Floating-Point Numbers\n", "The floating-point type can store fractional numbers.\n", "They can be defined either in standard decimal notation, or in exponential notation:" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "x = 0.000005\n", "y = 5e-6\n", "print(x == y)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n" ] } ], "source": [ "x = 1400000.00\n", "y = 1.4e6\n", "print(x == y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In the exponential notation, the ``e`` or ``E`` can be read \"...times ten to the...\",\n", "so that ``1.4e6`` is interpreted as $~1.4 \\times 10^6$." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "An integer can be explicitly converted to a float with the ``float`` constructor:" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "1.0" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "float(1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Aside: Floating-point precision\n", "One thing to be aware of with floating point arithmetic is that its precision is limited, which can cause equality tests to be unstable. For example:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 8, "metadata": {}, "output_type": "execute_result" } ], "source": [ "0.1 + 0.2 == 0.3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Why is this the case? It turns out that it is not a behavior unique to Python, but is due to the fixed-precision format of the binary floating-point storage used by most, if not all, scientific computing platforms.\n", "All programming languages using floating-point numbers store them in a fixed number of bits, and this leads some numbers to be represented only approximately.\n", "We can see this by printing the three values to high precision:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0.1 = 0.10000000000000001\n", "0.2 = 0.20000000000000001\n", "0.3 = 0.29999999999999999\n" ] } ], "source": [ "print(\"0.1 = {0:.17f}\".format(0.1))\n", "print(\"0.2 = {0:.17f}\".format(0.2))\n", "print(\"0.3 = {0:.17f}\".format(0.3))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We're accustomed to thinking of numbers in decimal (base-10) notation, so that each fraction must be expressed as a sum of powers of 10:\n", "$$\n", "1 /8 = 1\\cdot 10^{-1} + 2\\cdot 10^{-2} + 5\\cdot 10^{-3}\n", "$$\n", "In the familiar base-10 representation, we represent this in the familiar decimal expression: $0.125$.\n", "\n", "Computers usually store values in binary notation, so that each number is expressed as a sum of powers of 2:\n", "$$\n", "1/8 = 0\\cdot 2^{-1} + 0\\cdot 2^{-2} + 1\\cdot 2^{-3}\n", "$$\n", "In a base-2 representation, we can write this $0.001_2$, where the subscript 2 indicates binary notation.\n", "The value $0.125 = 0.001_2$ happens to be one number which both binary and decimal notation can represent in a finite number of digits.\n", "\n", "In the familiar base-10 representation of numbers, you are probably familiar with numbers that can't be expressed in a finite number of digits.\n", "For example, dividing $1$ by $3$ gives, in standard decimal notation:\n", "$$\n", "1 / 3 = 0.333333333\\cdots\n", "$$\n", "The 3s go on forever: that is, to truly represent this quotient, the number of required digits is infinite!\n", "\n", "Similarly, there are numbers for which binary representations require an infinite number of digits.\n", "For example:\n", "$$\n", "1 / 10 = 0.00011001100110011\\cdots_2\n", "$$\n", "Just as decimal notation requires an infinite number of digits to perfectly represent $1/3$, binary notation requires an infinite number of digits to represent $1/10$.\n", "Python internally truncates these representations at 52 bits beyond the first nonzero bit on most systems.\n", "\n", "This rounding error for floating-point values is a necessary evil of working with floating-point numbers.\n", "The best way to deal with it is to always keep in mind that floating-point arithmetic is approximate, and *never* rely on exact equality tests with floating-point values." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Complex Numbers\n", "Complex numbers are numbers with real and imaginary (floating-point) parts.\n", "We've seen integers and real numbers before; we can use these to construct a complex number:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(1+2j)" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "complex(1, 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Alternatively, we can use the \"``j``\" suffix in expressions to indicate the imaginary part:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(1+2j)" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "1 + 2j" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Complex numbers have a variety of interesting attributes and methods, which we'll briefly demonstrate here:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "collapsed": false }, "outputs": [], "source": [ "c = 3 + 4j" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "3.0" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c.real # real part" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4.0" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c.imag # imaginary part" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "(3-4j)" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "c.conjugate() # complex conjugate" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "5.0" ] }, "execution_count": 16, "metadata": {}, "output_type": "execute_result" } ], "source": [ "abs(c) # magnitude, i.e. sqrt(c.real ** 2 + c.imag ** 2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## String Type\n", "Strings in Python are created with single or double quotes:" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "collapsed": false }, "outputs": [], "source": [ "message = \"what do you like?\"\n", "response = 'spam'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python has many extremely useful string functions and methods; here are a few of them:" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "4" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# length of string\n", "len(response)" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'SPAM'" ] }, "execution_count": 19, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Make upper-case. See also str.lower()\n", "response.upper()" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'What do you like?'" ] }, "execution_count": 20, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Capitalize. See also str.title()\n", "message.capitalize()" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'what do you like?spam'" ] }, "execution_count": 21, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# concatenation with +\n", "message + response" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'spamspamspamspamspam'" ] }, "execution_count": 22, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# multiplication is multiple concatenation\n", "5 * response" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "'w'" ] }, "execution_count": 23, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# Access individual characters (zero-based indexing)\n", "message[0]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For more discussion of indexing in Python, see [\"Lists\"](06-Built-in-Data-Structures.ipynb#Lists)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## None Type\n", "Python includes a special type, the ``NoneType``, which has only a single possible value: ``None``. For example:" ] }, { "cell_type": "code", "execution_count": 24, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "NoneType" ] }, "execution_count": 24, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(None)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You'll see ``None`` used in many places, but perhaps most commonly it is used as the default return value of a function.\n", "For example, the ``print()`` function in Python 3 does not return anything, but we can still catch its value:" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "abc\n" ] } ], "source": [ "return_value = print('abc')" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "None\n" ] } ], "source": [ "print(return_value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Likewise, any function in Python with no return value is, in reality, returning ``None``." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Boolean Type\n", "The Boolean type is a simple type with two possible values: ``True`` and ``False``, and is returned by comparison operators discussed previously:" ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 27, "metadata": {}, "output_type": "execute_result" } ], "source": [ "result = (4 < 5)\n", "result" ] }, { "cell_type": "code", "execution_count": 28, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "bool" ] }, "execution_count": 28, "metadata": {}, "output_type": "execute_result" } ], "source": [ "type(result)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Keep in mind that the Boolean values are case-sensitive: unlike some other languages, ``True`` and ``False`` must be capitalized!" ] }, { "cell_type": "code", "execution_count": 29, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True False\n" ] } ], "source": [ "print(True, False)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Booleans can also be constructed using the ``bool()`` object constructor: values of any other type can be converted to Boolean via predictable rules.\n", "For example, any numeric type is False if equal to zero, and True otherwise:" ] }, { "cell_type": "code", "execution_count": 30, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 30, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(2014)" ] }, { "cell_type": "code", "execution_count": 31, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 31, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(0)" ] }, { "cell_type": "code", "execution_count": 32, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 32, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(3.1415)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The Boolean conversion of ``None`` is always False:" ] }, { "cell_type": "code", "execution_count": 33, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 33, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(None)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For strings, ``bool(s)`` is False for empty strings and True otherwise:" ] }, { "cell_type": "code", "execution_count": 34, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 34, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(\"\")" ] }, { "cell_type": "code", "execution_count": 35, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 35, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool(\"abc\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "For sequences, which we'll see in the next section, the Boolean representation is False for empty sequences and True for any other sequences" ] }, { "cell_type": "code", "execution_count": 36, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "True" ] }, "execution_count": 36, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool([1, 2, 3])" ] }, { "cell_type": "code", "execution_count": 37, "metadata": { "collapsed": false }, "outputs": [ { "data": { "text/plain": [ "False" ] }, "execution_count": 37, "metadata": {}, "output_type": "execute_result" } ], "source": [ "bool([])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "< [Basic Python Semantics: Operators](04-Semantics-Operators.ipynb) | [Contents](Index.ipynb) | [Built-In Data Structures](06-Built-in-Data-Structures.ipynb) >" ] } ], "metadata": { "anaconda-cloud": {}, "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.5.1" } }, "nbformat": 4, "nbformat_minor": 0 }