{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Basic Programming Using Python: Files and Lists" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Objectives" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- FIXME" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Strings From Files" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In our [previous lesson](python-3-conditionals-defensive.ipynb),\n", "we saw how to set the colors in a grid based on the characters in a string.\n", "The time has come to see how to get those strings (and other things) out of files." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As a refresher,\n", "here's our coloring function:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def color_from_string(grid, data):\n", " \"Color grid cells red and green according to 'R' and 'G' in data.\"\n", " assert grid.width == len(data), \\\n", " 'Grid and string lengths do not match: {0} != {1}'.format(grid.width, len(data))\n", " for x in range(grid.width):\n", " assert data[x] in 'GR', \\\n", " 'Unknown character in data string: \"{0}\"'.format(data[x])\n", " if data[x] == 'R':\n", " grid[x, 0] = colors['Red']\n", " else:\n", " grid[x, 0] = colors['Green']" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "And here's how we use it:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "from ipythonblocks import ImageGrid, colors\n", "\n", "row = ImageGrid(5, 1)\n", "color_from_string(row, 'RRGRR')\n", "row.show()" ], "language": "python", "metadata": {}, "outputs": [ { "html": [ "