{ "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": [ "- Learn how to open a file and read in data.\n", "- Understand how to interpret and remove newlines in python.\n", "- Use `ipythonblocks` library to create grids of colored cells based on characters in a file.\n", "- Introduce the list data structure and learn how to manipulate lists in python.\n", "- Use lists to store lines from a data file in order to generate multi-dimensional color grids.\n" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "File I/O: Reading in Data From Files" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In our [previous lesson](python-3-conditionals-defensive.ipynb),\n", "we learned how to set the colors in a grid based on the characters in a string.\n", "However, what happens if we want to set the colors based on the characters contained in a file? Here we will learn out to open files and read in lines of data for use in setting the colors of a grid. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As a refresher, here's our coloring function that takes in an an ImageGrid object, grid, and colors it based on the characters in the string, data:" ] }, { "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": 2 }, { "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": [ "