{ "metadata": { "name": "types" }, "nbformat": 2, "worksheets": [ { "cells": [ { "cell_type": "markdown", "source": [ "Types", "====", "All values in programming have types:", "", "* Integer: -1, 0, 1, 2, 3, 4, 5...", "* Float: -12.3, 0.001, 3.14159, 5.0", "* String: 'Helloooo Newman'", "* List: [1, 2, 3, 4, 5]", "", "These types are important, because they tell the program how to act.", "", "For example, the plus sign does different things to strings and numbers." ] }, { "cell_type": "code", "collapsed": false, "input": [ "'Brad' + 'Pitt'" ], "language": "python", "outputs": [ { "output_type": "pyout", "prompt_number": 1, "text": [ "'BradPitt'" ] } ], "prompt_number": 1 }, { "cell_type": "code", "collapsed": false, "input": [ "75 + 2" ], "language": "python", "outputs": [ { "output_type": "pyout", "prompt_number": 2, "text": [ "77" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "source": [ "Types can also cause confusion." ] }, { "cell_type": "code", "collapsed": false, "input": [ "15.0 / 2" ], "language": "python", "outputs": [ { "output_type": "pyout", "prompt_number": 3, "text": [ "7.5" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "15 / 2" ], "language": "python", "outputs": [ { "output_type": "pyout", "prompt_number": 4, "text": [ "7" ] } ], "prompt_number": 4 }, { "cell_type": "markdown", "source": [ "The surprising result that 15 / 2 = 7 happens because computer folks like commands that involve two objects of the same type to result in another object of that type, but in science we really want 15 / 2 = 7.5. The easy way to make sure that this happens is to add a special line to the beginning of any program that will do math." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from __future__ import division", "15 / 2" ], "language": "python", "outputs": [ { "output_type": "pyout", "prompt_number": 5, "text": [ "7.5" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "source": [ "This line will make a little more sense once you learn about modules, but basically it tells Python to use the kind of division that the newest version of Python uses, which is that one that makes sense to everyone but computer scientists.", "", "A full list of Python's built-in types is available at:", "http://docs.python.org/library/types.html" ] } ] } ] }