{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Data I/O, Strings, Dictionary" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Data I/O" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this lecture we shall concentrate on a few more programming tools which might be useful to you later. Let us try to write a simple interpreter today. In the process we shall learn how to write to a file and recall reading from a file." ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Reading data from the screen" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This you already do using `input`. Some of you already use `raw_input`, though I did not do it in class. Today I'll formally introduce it. Raw input directly stores the input in a string. You can later process the string in any way you want." ] }, { "cell_type": "code", "collapsed": false, "input": [ "s = raw_input(\"Input anything : \")\n", "print type(s)\n", "print s\n", "slst = s.split()\n", "varname = slst[0]\n", "varvalue = float(slst[1])\n", "print \"%s has value %f.\" % (varname, varvalue)" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Input anything : a 7\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "a 7\n", "a has value 7.000000.\n" ] } ], "prompt_number": 1 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Command line input" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sometimes one runs a program where the input to the program is passed via the command line. It is easy to do that in python. For that one has to import a package called `sys`." ] }, { "cell_type": "code", "collapsed": false, "input": [ "program = \\\n", "\"\"\"\n", "import sys\n", "\n", "x = float(sys.argv[1])\n", "print x*x\n", "\"\"\"\n", "\n", "progfile = open(\"files/myprogfile.py\", 'w')\n", "progfile.write(program)\n", "progfile.close()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "To see that it works, we can print the file" ] }, { "cell_type": "code", "collapsed": false, "input": [ "progfile = open(\"files/myprogfile.py\", 'r')\n", "print progfile.read()\n", "progfile.close()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n", "import sys\n", "\n", "x = float(sys.argv[1])\n", "print x*x\n", "\n" ] } ], "prompt_number": 3 }, { "cell_type": "code", "collapsed": false, "input": [ "#%run \"files/myprogfile.py\"" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "code", "collapsed": false, "input": [ "%run \"files/myprogfile.py\" 1.5" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "2.25\n" ] } ], "prompt_number": 5 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Raising errors" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Till now we had been trying to deal with errors using conditionals. However to make the program more readable, one is encouraged to use the `try..except` mechanism provided in python." ] }, { "cell_type": "code", "collapsed": false, "input": [ "xstr = raw_input(\"Test :\")\n", "x = float(xstr)" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Test :34.3\n" ] } ], "prompt_number": 6 }, { "cell_type": "code", "collapsed": false, "input": [ "def read_number() :\n", " xstr = raw_input(\"Input a number : \")\n", " try :\n", " x = float(xstr)\n", " except ValueError :\n", " raise ValueError('Cannot understand the number %s.' % xstr)\n", " return x" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 7 }, { "cell_type": "code", "collapsed": false, "input": [ "try :\n", " x = read_number()\n", "except ValueError, e :\n", " print e\n", " sys.exit(1)\n", " \n", "print x*x" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Input a number : 23.4\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "547.56\n" ] } ], "prompt_number": 8 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Strings" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some examples of what you can do with strings." ] }, { "cell_type": "code", "collapsed": false, "input": [ "eg_str = \"This is a sentence. This is another sentence.\\nThis is the second line. This is the second\\nsentence \\\n", "which started in the second line but\\nended in the fourth line.\"\n", "print eg_str" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This is a sentence. This is another sentence.\n", "This is the second line. This is the second\n", "sentence which started in the second line but\n", "ended in the fourth line.\n" ] } ], "prompt_number": 9 }, { "cell_type": "code", "collapsed": false, "input": [ "# Substrings\n", "eg_str[10:20]" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 10, "text": [ "'sentence. '" ] } ], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [ "print \"The word 'sentence' begins at %d, whereas the word 'sentience' \\\n", "starts at %d.\" % (eg_str.find('sentence'), eg_str.find('sentience'))" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "The word 'sentence' begins at 10, whereas the word 'sentience' starts at -1.\n" ] } ], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "# Also in works\n", "print ('sentence' in eg_str)\n", "print ('starts' in eg_str)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "True\n", "False\n" ] } ], "prompt_number": 12 }, { "cell_type": "code", "collapsed": false, "input": [ "print 'health'.startswith('heal')\n", "print 'Python'.endswith('tail')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "True\n", "False\n" ] } ], "prompt_number": 13 }, { "cell_type": "code", "collapsed": false, "input": [ "# Replace\n", "print eg_str.replace('sentence', 'verdict')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "This is a verdict. This is another verdict.\n", "This is the second line. This is the second\n", "verdict which started in the second line but\n", "ended in the fourth line.\n" ] } ], "prompt_number": 14 }, { "cell_type": "code", "collapsed": false, "input": [ "print eg_str.split()\n", "print eg_str.splitlines()\n", "print eg_str.split('a')\n", "print eg_str.split('.')\n", "for str in eg_str.split('.') :\n", " print str" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['This', 'is', 'a', 'sentence.', 'This', 'is', 'another', 'sentence.', 'This', 'is', 'the', 'second', 'line.', 'This', 'is', 'the', 'second', 'sentence', 'which', 'started', 'in', 'the', 'second', 'line', 'but', 'ended', 'in', 'the', 'fourth', 'line.']\n", "['This is a sentence. This is another sentence.', 'This is the second line. This is the second', 'sentence which started in the second line but', 'ended in the fourth line.']\n", "['This is ', ' sentence. This is ', 'nother sentence.\\nThis is the second line. This is the second\\nsentence which st', 'rted in the second line but\\nended in the fourth line.']\n", "['This is a sentence', ' This is another sentence', '\\nThis is the second line', ' This is the second\\nsentence which started in the second line but\\nended in the fourth line', '']\n", "This is a sentence\n", " This is another sentence\n", "\n", "This is the second line\n", " This is the second\n", "sentence which started in the second line but\n", "ended in the fourth line\n", "\n" ] } ], "prompt_number": 15 }, { "cell_type": "code", "collapsed": false, "input": [ "# Checking type of characters in a string\n", "print \"'2334' contains only digits : %s\" % '2334'.isdigit()\n", "print \"'a123' contains only digits : %s\" % 'a123'.isdigit()\n", "print \"Space ' \\n \\t ' : %s\" % ' \\n \\t '.isspace()\n", "print \"'' is a space : %s\" % ''.isspace()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "'2334' contains only digits : True\n", "'a123' contains only digits : False\n", "Space ' \n", " \t ' : True\n", "'' is a space : False\n" ] } ], "prompt_number": 16 }, { "cell_type": "code", "collapsed": false, "input": [ "# Removing initial and trailing characters\n", "print \"+\" + ' This is a stupid sentence. \\n'.strip() + \"+\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "+This is a stupid sentence.+\n" ] } ], "prompt_number": 17 }, { "cell_type": "code", "collapsed": false, "input": [ "# delimiter.join(list of strings) \n", "\n", "list_of_sentences = [\"Sky is blue\", \"Classes are boring\", \"Examples are stupid\"]\n", "print '. '.join(list_of_sentences) + '.'\n", "print \"-\"*50\n", "print \".\\n\".join(list_of_sentences) + '.'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Sky is blue. Classes are boring. Examples are stupid.\n", "--------------------------------------------------\n", "Sky is blue.\n", "Classes are boring.\n", "Examples are stupid.\n" ] } ], "prompt_number": 18 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Dictionary" ] }, { "cell_type": "code", "collapsed": false, "input": [ "names = ['Eric', 'Ila', 'Emma', 'John', 'Umesh', 'Asha', 'Akash', 'Kate', 'Uma', 'Sam']\n", "scores = [7,8,6,9,10,6,8,7,7,9]\n", "\n", "score_dict={'Eric' : 7, 'Ila' : 8}\n", "print \"Ila scored %d.\" % score_dict['Ila']\n", "\n", "# One can add.\n", "score_dict={}\n", "print score_dict\n", "\n", "for i in range(len(names)) :\n", " score_dict[names[i]] = scores[i]\n", "\n", "print score_dict" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Ila scored 8.\n", "{}\n", "{'Emma': 6, 'Akash': 8, 'Sam': 9, 'Ila': 8, 'Asha': 6, 'Kate': 7, 'Umesh': 10, 'Uma': 7, 'John': 9, 'Eric': 7}\n" ] } ], "prompt_number": 19 }, { "cell_type": "code", "collapsed": false, "input": [ "for name in score_dict :\n", " print \"%s scored %d\" % (name, score_dict[name])" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Emma scored 6\n", "Akash scored 8\n", "Sam scored 9\n", "Ila scored 8\n", "Asha scored 6\n", "Kate scored 7\n", "Umesh scored 10\n", "Uma scored 7\n", "John scored 9\n", "Eric scored 7\n" ] } ], "prompt_number": 20 }, { "cell_type": "code", "collapsed": false, "input": [ "def print_score(n) :\n", " if n in score_dict :\n", " print \"%s scored %d.\" %(n, score_dict[n])\n", " else :\n", " print \"%s is not on list.\" % n" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 21 }, { "cell_type": "code", "collapsed": false, "input": [ "print_score('Peter')\n", "print_score('Asha')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Peter is not on list.\n", "Asha scored 6.\n" ] } ], "prompt_number": 22 }, { "cell_type": "code", "collapsed": false, "input": [ "def tabulate_scores(sd) :\n", " print \"Name : Score\"\n", " for name in sorted(sd) :\n", " print \"%5s :%9d\" % (name, sd[name])\n", " return None" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 23 }, { "cell_type": "code", "collapsed": false, "input": [ "tabulate_scores(score_dict)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Name : Score\n", "Akash : 8\n", " Asha : 6\n", " Emma : 6\n", " Eric : 7\n", " Ila : 8\n", " John : 9\n", " Kate : 7\n", " Sam : 9\n", " Uma : 7\n", "Umesh : 10\n" ] } ], "prompt_number": 24 } ], "metadata": {} } ] }