{ "metadata": { "name": "", "signature": "sha256:9022b72f2fc24432e92fa44cdfeb3da1fa5525a0485bb76b898e97e55f78a4d8" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Chapter 9: Variable scope and functions" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Example 9.1, Page number: 160" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\n", "def func() :\n", " if not hasattr(func, \"permanent\") :\n", " func.permanent = 1\n", " result = func.permanent\n", " func.permanent += 1\n", " return result\n", "\n", "for counter in range (0, 3) :\n", " temporary = 1\n", " print ('Temporary %d Permanent %d' % (temporary, func()))\n", " temporary += 1" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Temporary 1 Permanent 1\n", "Temporary 1 Permanent 2\n", "Temporary 1 Permanent 3\n" ] } ], "prompt_number": 1 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Example 9.3, Page number: 164" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\n", "def triangle (width, height) :\n", " area = width * height / 2.0\n", " return area\n", "\n", "print ('Triangle #1 %f' % (triangle (1.3, 8.3)))\n", "print ('Triangle #2 %f' % (triangle (4.8, 9.8)))\n", "print ('Triangle #3 %f' % (triangle (1.2, 2.0)))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Triangle #1 5.395000\n", "Triangle #2 23.520000\n", "Triangle #3 1.200000\n" ] } ], "prompt_number": 2 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Example 9.4, Page number: 166" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\n", "def length (string) :\n", " return len(string)\n", "\n", "line = 'hello world' \n", "\n", "print ('Length is: %d' % length(line))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Length is: 11\n" ] } ], "prompt_number": 4 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Example 9.6, Page number: 170" ] }, { "cell_type": "code", "collapsed": false, "input": [ "\n", "\n", "def length (string) :\n", " return len(string)\n", "\n", "line = 'Steve Oualline'\n", "\n", "print ('Length is: %d' % length(line))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Length is: 14\n" ] } ], "prompt_number": 5 } ], "metadata": {} } ] }