{ "metadata": { "name": "", "signature": "sha256:788d450282aca14510b4fbb415c974ba9a033b999a6b00b6289ec70286d56a52" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "An Introduction to Python for new Programmers" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Welcome to _An Introduction to Python for new Programmers_! This iPython notebook serves as an instructor-led guide to the Python programming language, particularly for those who are new to programming or have very limited programming experience. iPython notebooks are a novel form of communicating about programming; creating an environment where both text and live code can be executed in an explanatory fashion. Parts of this document will contain live Python code that is interpreted by the notebook and whose output will be rendered directly to the screen. If you would like to follow along on your laptop, you can install iPython and **download this workbook from** [github/DistrictDataLabs/intro-to-python](https://github.com/DistrictDataLabs/intro-to-python)." ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Before we get Started...." ] }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Prerequisites:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Although this is an introductory course, some prerequisites are required. \n", "\n", "1. The student must have Python installed \n", "2. Must be familiar with using Python on his or her operating system. \n", "3. They must also have familiarity with the command line. \n", "\n", "The following are suggested tasks to perform before this course:\n", "\n", "* [Using the terminal](http://cli.learncodethehardway.org/book/)\n", "* [Install Python](https://wiki.python.org/moin/BeginnersGuide/Download)\n", "* [Python Basics](http://www.codecademy.com/tracks/python)\n", "* [Python Hello World](http://www.learnpython.org/en/Hello,_World!)\n", "\n", "Installations:\n", "\n", "* [Install virtualenv and virtualenvwrapper](http://docs.python-guide.org/en/latest/dev/virtualenvs/) A *virtualenv* is an isolated working copy of Python which allows you to work on a specific project without worry of affecting other projects. *Virtualenvwrapper* provides a set of commands which makes working with virtual environments much more pleasant. It also places all your virtual environments in one place. \n", "* [Get a Text editor, Sublime] (http://www.sublimetext.com/)\n", "* [Get a Github account](https://github.com/)\n", "\n", "For Windows Users:\n", "\n", "* [Install Pip, Virtualenv and Virtualenv Wrapper on Windows] (http://www.tylerbutler.com/2012/05/how-to-install-python-pip-and-virtualenv-on-windows-with-powershell/)\n" ] }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Download the course materials from GitHub" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* The presentation is on github. [Github: Intro to Python] (https://github.com/DistrictDataLabs/intro-to-python)\n", "\n", "* The `Workshop.pynb` can be viewed on the iPython nbviewer application by using the following link: [nbviewer Intro to Python](http://nbviewer.ipython.org/github/DistrictDataLabs/intro-to-python/blob/master/Workshop.ipynb)\n", "\n" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Learning how to Learn how to Code" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So, let's be clear- what can we accomplish in a two to three hour session? Obviously we're not going to make you an expert programmer in this time, nor are we going to impart a comprehensive theory of programming. \n", "\n", "However, there is one fundamental concept about programming that I would like ensure you all take away: **programming isn't about knowing syntax it's about learning**. Therefore, what were going to try to enable you to do today is help you **learn how to learn how to code**. \n", "\n", "In order to continually improve his or her craft, a programmer must constantly be in a state of education. From reading about new programming paradigms, languages, or frameworks to experimental approaches to reading other's code- programming is is a community activity that encourages the sharing of ideas. \n", "\n", "In particular we'll focus on clear expression of code and readability. **By ensuring you can write code in a readable form, it will help you to read other's code as well**!" ] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "Getting Started" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's start by using the interactive interpreter to run the most basic of programs, \"Hello World!\" This interactive interpreter is also called the **\"REPL\" or the Read Evaluate Print Loop**. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "print \"Hello World!\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The REPL is often used during program development. Let's try running this same basic program from a file. This is called a script or a program that is run from the command line (terminal). That first line is called the \"hash bang.\" Put simply, it indicates that the file can be run as a script. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#!/usr/bin/env python\n", "\n", "print \"Hello World!\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Output and Input" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# This is writing to standard out:\n", "\n", "print \"Python is awesome!\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Python is awesome!\n" ] } ], "prompt_number": 17 }, { "cell_type": "code", "collapsed": false, "input": [ "# Basic input (These values will always be interpreted as strings)\n", "\n", "name = raw_input(\"What is your name?\")\n", "print name" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "What is your name?sarah\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "sarah\n" ] } ], "prompt_number": 19 }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "What is Programming?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Programming is the act of creating **a set of instructions to transform input data to some kind of output**. \n", "\n", "Yeh- it's that simple. We're **making recipes of ingredients and instructions**.\n", "\n", "However, instead of food, we cook with numbers and strings. The instructions are defined as a formal language.\n", "\n", "The instructions are interpreted and executed from top to bottom, and when the interpreter runs out of instructions, the program is done!\n", "\n", "The **interpreter** is what takes your code instructions and translates them into something that your computer understands.\n", "\n", "Because of this python is called an **interpreted language** or a **scripting language**. \n" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Variables" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Variables should follow some simple rules.\n", "\n", "* be lowercase\n", "* use underscores for word separation\n", "* not start with numbers\n", "\n", "In fact Python has it's own language style guide called PEP8.\n", "\n", "* [PEP8 Guide](http://legacy.python.org/dev/peps/pep-0008/)\n", "\n", "Consider the following simple program. This small program for computing the area of a triangle includes quite a few components:\n", "\n", "* Comments (`#`)\n", "* Assignment (`a = 2`)\n", "* Variables (`base`)\n", "* Multiplication (`*`)\n", "* Output \n", "(`print`)" ] }, { "cell_type": "code", "collapsed": true, "input": [ "# Compute the area of a triangle\n", "\n", "# Ingredients (aka: variables)\n", "base = 4 \n", "height = 7\n", "\n", "# Instructions (aka: an algorithm)\n", "area = 0.5 * base * height\n", "print area" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "14.0\n" ] } ], "prompt_number": 4 }, { "cell_type": "raw", "metadata": {}, "source": [ "Interactivity is a powerful idea. It allows variables to be variable. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "# The area of a circle\n", "# Must input a number or a decimal\n", "radius = input(\"Enter radius: \")\n", "area = 3.14 * radius * radius\n", "print area" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "Enter radius: 10\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "314.0\n" ] } ], "prompt_number": 20 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here we create a variable called radius. Note that **the name of the variable is expressive** (much better than x or y). The value of variable is assigned using the `=` operator. In this case it is assigned the value of the return value from the `input` function. **We can run this program over and over again and by changing the input we have changed the ouput- thus making our program dynamic.** We can then use the variable throughout the program and even modify its value through code during runtime. And through this very simple concept, very complex programs from web servers to self-driving cars are built from just a few simple building blocks!" ] }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Your Turn!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Write code with variables to print the area of a rectangle" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "# Write code with variables to print the parameter of a rectangle" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Answers:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Area of a rectangle\n", "\n", "width = input(\"What is the width?\")\n", "height = input(\"What is the hight?\")\n", "\n", "area_rectangle = width * height\n", "\n", "print area_rectangle\n", " " ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "What is the width?5\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "What is the hight?10\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "50\n" ] } ], "prompt_number": 2 }, { "cell_type": "code", "collapsed": false, "input": [ "# Parameter of a rectangle\n", "\n", "width = input(\"What is the width?\")\n", "height = input(\"What is the hight?\")\n", "\n", "parameter_rectangle = 2 * width + 2 * height\n", "\n", "print area_rectangle" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "What is the width?5\n" ] }, { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "What is the hight?10\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "50\n" ] } ], "prompt_number": 7 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Calculation" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "So let's look at what computers do best- compute things!" ] }, { "cell_type": "code", "collapsed": false, "input": [ "print 2 + 5 # Addition\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "7\n" ] } ], "prompt_number": 21 }, { "cell_type": "code", "collapsed": false, "input": [ "print 10 - 3 # Subtraction\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "7\n" ] } ], "prompt_number": 22 }, { "cell_type": "code", "collapsed": false, "input": [ "print 5 * 5 # Multiplication\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "25\n" ] } ], "prompt_number": 23 }, { "cell_type": "code", "collapsed": false, "input": [ "print 2 ** 2 # Power operator\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "4\n" ] } ], "prompt_number": 24 }, { "cell_type": "code", "collapsed": false, "input": [ "print 5 % 2 # Modulus (aka: remainder)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1\n" ] } ], "prompt_number": 25 }, { "cell_type": "code", "collapsed": false, "input": [ "print 11 / 2 # Division with an integer\n", "print 11 / 2.0 # Division with a float" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "5\n", "5.5\n" ] } ], "prompt_number": 26 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Comparison" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**True and False are booleans** in Python and are used to express truth. Let's explore some comparision operators. \n", "\n", "**Note:** Don't confuse assignment `=` with is equal to `==`; this is one of the most common programmer errors." ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = 10 #ASSIGNMENT\n", "b = 20\n", "\n", "print a > b # Greater than\n", "print b >= a # Greater than or equal to\n", "print a == b # EQUALITY symbol\n", "print b < a # Less than\n", "print a <= b # Less than or equal to" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "False\n", "True\n", "False\n", "False\n", "True\n" ] } ], "prompt_number": 27 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Simple Data Types" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "We have already seen three data types:\n", "\n", "1. Strings\n", "2. Integers\n", "3. Floats\n", "4. Booleans\n", "\n", "These are all objects in Python. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "#String\n", "a = \"apple\"\n", "print type(a)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 28 }, { "cell_type": "code", "collapsed": false, "input": [ "#Integer (whole number)\n", "b = 1\n", "print type(b)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 29 }, { "cell_type": "code", "collapsed": false, "input": [ "#Float (real numbers with decimal places)\n", "c = 2.2\n", "print type(c)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 30 }, { "cell_type": "code", "collapsed": false, "input": [ "#Boolean\n", "d = True\n", "print type(d)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 31 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Strings" ] }, { "cell_type": "code", "collapsed": false, "input": [ "a = \"Hello\" # String\n", "b = \" World\" # Another string\n", "print a + b # Concatenation" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello World\n" ] } ], "prompt_number": 32 }, { "cell_type": "code", "collapsed": false, "input": [ "a = \"World\"\n", "# Slicing\n", "print a[0]\n", "print a[-1]\n", "print \"World\"[0:4]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "W\n", "d\n", "Worl\n" ] } ], "prompt_number": 34 }, { "cell_type": "code", "collapsed": false, "input": [ "name = \"Jonesey\"\n", "print \"Hello, %s!\" % name # Simple string formatting" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello, Jonesey!\n" ] } ], "prompt_number": 35 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Strings are an example of an **imutable** data type. Once you instantiate a string you cannot change any characters in it's set. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "string = \"string\"\n", "string[1] = \"y\" #Here we attempt to assign the last character in the string to \"y\"" ], "language": "python", "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "'str' object does not support item assignment", "output_type": "pyerr", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m\n\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0mstring\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"string\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mstring\u001b[0m\u001b[0;34m[\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m]\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"y\"\u001b[0m \u001b[0;31m#Here we attempt to assign the last character in the string to \"y\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: 'str' object does not support item assignment" ] } ], "prompt_number": 36 }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Formatting Strings" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# String Concatination\n", "\n", "first_name = \"Bob\"\n", "last_name = \"Roberts\"\n", "\n", "print first_name + \" is my first name. \" + last_name + \" is my last name.\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Bob is my first name. Roberts is my last name.\n" ] } ], "prompt_number": 37 }, { "cell_type": "code", "collapsed": false, "input": [ "# String Formatting\n", "\n", "food = \"pizzas\"\n", "number = 20\n", "\n", "print \"I'm so hungry I'm going to eat %i %s.\" % (number, food)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "I'm so hungry I'm going to eat 20 pizzas.\n" ] } ], "prompt_number": 13 }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "String Methods" ] }, { "cell_type": "code", "collapsed": false, "input": [ "name = \"matt\"\n", "name.capitalize() # Capitalizes the first letter of the string" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 38, "text": [ "'Matt'" ] } ], "prompt_number": 38 }, { "cell_type": "code", "collapsed": false, "input": [ "name = \"matt\"\n", "last = \"jones\"\n", "\" \".join([name, last]) # Creates a new string by concatenating each item in the list" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 39, "text": [ "'matt jones'" ] } ], "prompt_number": 39 }, { "cell_type": "code", "collapsed": false, "input": [ "# What other methods do strings have?\n", "# You can use \"dir\" on any object to find out it's methods\n", "dir(str)" ], "language": "python", "metadata": {}, "outputs": [ { "metadata": {}, "output_type": "pyout", "prompt_number": 40, "text": [ "['__add__',\n", " '__class__',\n", " '__contains__',\n", " '__delattr__',\n", " '__doc__',\n", " '__eq__',\n", " '__format__',\n", " '__ge__',\n", " '__getattribute__',\n", " '__getitem__',\n", " '__getnewargs__',\n", " '__getslice__',\n", " '__gt__',\n", " '__hash__',\n", " '__init__',\n", " '__le__',\n", " '__len__',\n", " '__lt__',\n", " '__mod__',\n", " '__mul__',\n", " '__ne__',\n", " '__new__',\n", " '__reduce__',\n", " '__reduce_ex__',\n", " '__repr__',\n", " '__rmod__',\n", " '__rmul__',\n", " '__setattr__',\n", " '__sizeof__',\n", " '__str__',\n", " '__subclasshook__',\n", " '_formatter_field_name_split',\n", " '_formatter_parser',\n", " 'capitalize',\n", " 'center',\n", " 'count',\n", " 'decode',\n", " 'encode',\n", " 'endswith',\n", " 'expandtabs',\n", " 'find',\n", " 'format',\n", " 'index',\n", " 'isalnum',\n", " 'isalpha',\n", " 'isdigit',\n", " 'islower',\n", " 'isspace',\n", " 'istitle',\n", " 'isupper',\n", " 'join',\n", " 'ljust',\n", " 'lower',\n", " 'lstrip',\n", " 'partition',\n", " 'replace',\n", " 'rfind',\n", " 'rindex',\n", " 'rjust',\n", " 'rpartition',\n", " 'rsplit',\n", " 'rstrip',\n", " 'split',\n", " 'splitlines',\n", " 'startswith',\n", " 'strip',\n", " 'swapcase',\n", " 'title',\n", " 'translate',\n", " 'upper',\n", " 'zfill']" ] } ], "prompt_number": 40 }, { "cell_type": "code", "collapsed": false, "input": [ "# What if you don't know how to use one of the methods?\n", "\n", "help(' matt '.strip)\n", "\n", "# Now that you know what it does, try it out!\n", "' matt '.strip()\n", "\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Help on built-in function strip:\n", "\n", "strip(...)\n", " S.strip([chars]) -> string or unicode\n", " \n", " Return a copy of the string S with leading and trailing\n", " whitespace removed.\n", " If chars is given and not None, remove characters in chars instead.\n", " If chars is unicode, S will be converted to unicode before stripping\n", "\n" ] }, { "metadata": {}, "output_type": "pyout", "prompt_number": 41, "text": [ "'matt'" ] } ], "prompt_number": 41 }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Quick Stretch" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Conditionality: \"If Else\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Programs can make choices based on particular values of variables using conditional execution. Conditionality forks the flow of execution so that **some parts of the program may be executed but others will not**.\n", "\n", "This brings up a crucial point about Python in particular- **blocks of code are grouped by indentation**. Every time you get to a place where you have to define a contiguous block of code (usually following a `:`) then everything under must be indented with the same amount of space (usually 4 spaces). Dedented code does not belong to the indented block.\n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Simple Conditionality\n", "if 2 + 2 == 4:\n", " print \"All is right in the world!\"\n", "else:\n", " print \"Pigs must be flying!\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "All is right in the world!\n" ] } ], "prompt_number": 42 }, { "cell_type": "code", "collapsed": false, "input": [ "# Evaluate Temperature\n", "temperature = input(\"What is today's temperature? \")\n", "\n", "if temperature > 82:\n", " print \"It's too hot, %i degrees will melt you.\" % temperature\n", "elif temperature < 45:\n", " print \"Are you crazy? You'll freeze at %i degrees\" % temperature\n", "else:\n", " print \"Perfect weather! Let's go for a picnic!\"" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "What is today's temperature? 30\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "Are you crazy? You'll freeze at 30 degrees\n" ] } ], "prompt_number": 43 }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Your Turn:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Use conditionality to determine if a number is even or odd" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Answer" ] }, { "cell_type": "code", "collapsed": false, "input": [ "number = input(\"What number should I test?\")\n", "\n", "if number % 2 == 0:\n", " print \"The number is even!\"\n", "else:\n", " print \"The number is odd!\"" ], "language": "python", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "stream": "stdout", "text": [ "What number should I test?10\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "The number is even!\n" ] } ], "prompt_number": 44 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Logic with Booleans" ] }, { "cell_type": "code", "collapsed": false, "input": [ "#Both a and b are True\n", "\n", "a = True\n", "b = True\n", "\n", "if a and b: \n", " print \"a and b == True\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "a and b == True\n" ] } ], "prompt_number": 10 }, { "cell_type": "code", "collapsed": false, "input": [ "#Either a or c is True\n", "\n", "b = True\n", "c = False\n", "\n", "if b or c: \n", " print \"b and c == True\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "b and c == True\n" ] } ], "prompt_number": 11 }, { "cell_type": "code", "collapsed": false, "input": [ "#If d is not true\n", "\n", "d = False\n", "\n", "if d is not True: \n", " print \"d == False\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "d == False\n" ] } ], "prompt_number": 49 }, { "cell_type": "code", "collapsed": false, "input": [ "# None denotes lack of value but it is not equal to false\n", "\n", "a = None\n", "b = 0\n", "\n", "if a is None:\n", " print \"None\"\n", "\n", "if b is not None: \n", " print \"Not None\"\n", "\n", "print None == False" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "None\n", "Not None\n", "False\n" ] } ], "prompt_number": 50 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Repetition: For and While Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**The power of computers is their ability to do a repetitive task over and over again** without tiring. Most programs don't just shut down on you have executing their instructions- they wait for input from the user and respond. In order to accomplish this some mechanism is required to continually execute a chunk of code." ] }, { "cell_type": "code", "collapsed": false, "input": [ "for letter in \"a\", \"b\", \"c\", \"d\", \"e\":\n", " print letter" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "code", "collapsed": false, "input": [ "for number in range(1,10):\n", " print number" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n" ] } ], "prompt_number": 37 }, { "cell_type": "code", "collapsed": false, "input": [ "# You are importing the sleep function from the time module\n", "from time import sleep\n", "\n", "print \"Cooking the bacon.\"\n", "\n", "hot_enough = 180\n", "temperature = 62\n", "\n", "while temperature < hot_enough:\n", " print \"Not hot enough...\"\n", " sleep(1)\n", " temperature = temperature + 15\n", "\n", "print \"Bacon is done!\"" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Spam is done!" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "Cooking the spam.\n", "Not hot enough...\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Spam is done!" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 52 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Functions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Functions allow you to define proceedures that happen over and over again in your code, almost like mini-programs that take input and `return` an output. Let's start by looking at a very simple function." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# This function takes no arguments\n", "# Every function starts with a definition, this is where \"def\" comes from\n", "def hello():\n", " # This is a docstring\n", " '''say hi'''\n", " print \"Hello!\"\n", "\n", "# Invoke the function\n", "hello()\n", "\n", "# Help prints the docstring of the function\n", "help(hello)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Hello!\n", "Help on function hello in module __main__:\n", "\n", "hello()\n", " say hi\n", "\n" ] } ], "prompt_number": 53 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's refactor (aka: rewrite) the bacon code into a cooking function." ] }, { "cell_type": "code", "collapsed": false, "input": [ "from time import sleep\n", "\n", "def cook(hot_enough, temperature, food):\n", " print \"Cooking the %s.\" % food\n", " while temperature < hot_enough:\n", " print \"Not hot enough...\"\n", " sleep(1)\n", " temperature = temperature + 15\n", " print \"The %s are done!\" % food\n", "\n", "cook(100, 50, \"coconuts\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Cooking the coconuts.\n", "Not hot enough...\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "Not hot enough..." ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n", "The coconuts are done!" ] }, { "output_type": "stream", "stream": "stdout", "text": [ "\n" ] } ], "prompt_number": 54 }, { "cell_type": "markdown", "metadata": {}, "source": [ "* **Arguments** to functions are named buckets that can have defaults associated with them. \n", "\n", "* So far we have only seen **Positional** arguments. Positional arguments (arguments without a default) must be specified in the order of the arguments. \n", "\n", "* **Keyword** arguments (those with a default) can be specified in any order, so long as they come after the positional arguments." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# postional and keyword arguments\n", "# positional arguments must go before keyword (default) arguments\n", "def writer(name, color=\"blue\"):\n", " print name + \"'s favorite color is \" + color\n", " \n", "writer(\"Samantha\")\n", "writer(\"Sarah\", \"red\")\n", "writer(\"Susan\", color=\"green\")" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Samantha's favorite color is blue\n", "Sarah's favorite color is red\n", "Susan's favorite color is green\n" ] } ], "prompt_number": 55 }, { "cell_type": "code", "collapsed": false, "input": [ "# A stub function that does nothing\n", "def stub():\n", " pass\n", "\n", "stub()" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 56 }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Your Turn:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Write a function that checks if a number is evenly divisible by 5" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Answer:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "def by_4(number = 4):\n", " '''Check if a number is evenly divisible by 4'''\n", " if not number % 4:\n", " print \"Yes\"\n", " else:\n", " print \"No\"\n", "\n", "by_4(10)\n", "by_4()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "No\n", "Yes\n" ] } ], "prompt_number": 58 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Lists, Tuples, Sets and Dictionaries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Programmers can't live on numbers and strings alone. The currency of programming is data (information), therefore we need more significant structures to represent information.\n", "\n", "* Unlike integers, floats and strings these data types can hold multiple values" ] }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Lists: " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Lists are **mutable** or able to be altered. Lists are a collection of data and that data can be of differing types." ] }, { "cell_type": "code", "collapsed": false, "input": [ " # A new list\n", " groceries = []\n", "\n", " # Add to list\n", " groceries.append(\"Snails\") \n", " groceries.append(\"Nutella\")\n", " groceries.append(\"Cactus\")\n", "\n", " # Access by index\n", " print groceries[2]\n", " print groceries[0]\n", "\n", " # Find number of things in list\n", " print len(groceries)\n", "\n", " # Sort the items in the list\n", " groceries.sort()\n", " print groceries\n", "\n", " # Remove from list\n", " groceries.remove(\"Cactus\")\n", "\n", " #The list is mutable\n", " groceries[0] = 2\n", " print groceries" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Cactus\n", "Snails\n", "3\n", "['Cactus', 'Nutella', 'Snails']\n", "[2, 'Snails']\n" ] } ], "prompt_number": 57 }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Tuples" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Tuples are an **immutable** type. Like strings, once you create them, you cannot change them. It is their immutability that allows you to use them as keys in dictionaries. However, they are similar to lists in that they are a collection of data and that data can be of differing types. " ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Tuple grocery list\n", "\n", "groceries = ('Cactus', 'Nutella', 'Snails')\n", "\n", "print groceries" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "('Cactus', 'Nutella', 'Snails')\n" ] } ], "prompt_number": 58 }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Sets:" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A set is a sequence of items that cannot contain duplicates. They handle operations like sets in mathmatics." ] }, { "cell_type": "code", "collapsed": false, "input": [ "numbers = range(10)\n", "evens = [2, 4, 6, 8]\n", "\n", "evens = set(evens)\n", "numbers = set(numbers)\n", "\n", "# Use difference to find the odds\n", "odds = numbers - evens\n", "\n", "print odds\n", "\n", "# Note: Set also allows for use of union (|), and intersection (&)\n", "\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "set([0, 1, 3, 5, 7, 9])\n" ] } ], "prompt_number": 61 }, { "cell_type": "heading", "level": 4, "metadata": {}, "source": [ "Dictionaries" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A dictionary is a map of keys to values. Keys must be unique." ] }, { "cell_type": "code", "collapsed": false, "input": [ "# A simple dictionary\n", "\n", "obvious = {'sky': 'blue'}\n", "\n", "# Access by key\n", "print obvious['sky']" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "blue\n" ] } ], "prompt_number": 62 }, { "cell_type": "code", "collapsed": false, "input": [ "\n", "# A longer dictionary\n", "obvious = {\n", " 'sky': 'blue',\n", " 'dog': 'woof'\n", "}\n", "\n", "# Check if item is in dictionary\n", "print 'two plus two' in obvious\n", "\n", "# Add new item\n", "obvious['two plus two'] = 4\n", "print obvious['two plus two']\n", "\n", "# Print just the keys\n", "print obvious.keys()\n", "\n", "# Print just the values\n", "print obvious.values()\n", "\n", "# Print dictionary pairs another way\n", "for key, value in obvious.items():\n", " print key, value" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "False\n", "4\n", "['two plus two', 'sky', 'dog']\n", "[4, 'blue', 'woof']\n", "two plus two 4\n", "sky blue\n", "dog woof\n" ] } ], "prompt_number": 63 }, { "cell_type": "code", "collapsed": false, "input": [ "# Complex Data structures\n", "# Dictionaries inside a dictionary!\n", "\n", "employees = {\n", " \"eid0001\": {\n", " \"name\": \"Bob Jones\",\n", " \"department\": \"Marketing\",\n", " \"interests\": [\"fishing\", \"deep breathing\", \"gatorade\",]\n", " },\n", " \"eid0002\": {\n", " \"name\": \"Sherry Lorenzo\",\n", " \"department\": \"Human Resources\",\n", " \"interests\": [\"cooking\", \"steganography\", \"cycling\",],\n", " }\n", "}\n", "\n", "for employee in employees:\n", " print employees[employee][\"name\"]" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Bob Jones\n", "Sherry Lorenzo\n" ] } ], "prompt_number": 64 }, { "cell_type": "heading", "level": 1, "metadata": {}, "source": [ "Quick Stretch" ] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "File I/O" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Writing to a file\n", "with open(\"example.txt\", \"w\") as f:\n", " f.write(\"Hello World! \\n\")\n", " f.write(\"How are you? \\n\")\n", " f.write(\"I'm fine.\")" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 66 }, { "cell_type": "code", "collapsed": false, "input": [ "# Reading from a file\n", "with open(\"example.txt\", \"r\") as f:\n", " data = f.readlines()\n", " for line in data:\n", " words = line.split()\n", " print words" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "['Hello', 'World!']\n", "['How', 'are', 'you?']\n", "[\"I'm\", 'fine.']\n" ] } ], "prompt_number": 67 }, { "cell_type": "code", "collapsed": false, "input": [ "# Count lines and words in a file\n", "lines = 0\n", "words = 0\n", "the_file = \"example.txt\"\n", "\n", "with open(the_file, 'r') as f:\n", " for line in f:\n", " lines += 1\n", " words += len(line.split())\n", "print \"There are %i lines and %i words in the %s file.\" % (lines, words, the_file)\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "There are 3 lines and 7 words in the example.txt file.\n" ] } ], "prompt_number": 68 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "APIs" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Getting data from an API\n", "\n", "import requests\n", "\n", "width = '500'\n", "height = '500'\n", "response = requests.get('http://placekitten.com/g/' + width + '/' + height)\n", "\n", "print response\n", "\n", "with open('kitteh.jpg', 'wb') as f:\n", " f.write(response.content)" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Object Oriented Programming" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now that we have covered the basic building blocks of a Python program, let's discuss a programming paradigm called Object-Oriented Programming (OOP). **OOP gives programmers a framework for modeling the real world by using classes - templates that describe an object's methods and attributes.** Methods can be thought of as the functions of the class while attributes are it's variables. Using this methodology, a programmer simply has to imagine the component interactions of the structure they're trying to model, then translate that into the executional components described above. \n", "\n", "* The names of classes should be \"camel cased.\" For example, \"FrogPrincess.\" \n", "* The __init__ method constructs the class when it is instantiated, it takes self as it's first parameter. \n" ] }, { "cell_type": "code", "collapsed": false, "input": [ "class Person(object):\n", " \"\"\"\n", " Base class for all people\n", " \"\"\"\n", " \n", " #An attribute of the class\n", " population = 0\n", " \n", " def __init__(self, name, age):\n", " self.name = name\n", " self.age = age\n", " Person.population += 1\n", " \n", " def displayCount(self):\n", " print \"Total people: %d\" % Person.population\n", " \n", " def displayPerson(self):\n", " print \"My name is %s and I am %i years old.\" % (self.name, self.age)\n", "\n", "## INHERITENCE ##\n", "# Rude inherits from person\n", "class Rude(Person):\n", " \n", " def displayPerson(self):\n", " print \"I don't have to tell you anything!\"\n", "\n", "\n", "# Create Person instance\n", "bob = Person(\"Bob\", 35)\n", "bob.displayPerson()\n", "bob.displayCount()\n", "\n", "# Create Rude Person Instance\n", "rude = Rude(\"None of your business\", None)\n", "rude.displayPerson()\n", "rude.displayCount()" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "My name is Bob and I am 35 years old.\n", "Total people: 1\n", "I don't have to tell you anything!\n", "Total people: 2\n" ] } ], "prompt_number": 77 }, { "cell_type": "heading", "level": 3, "metadata": {}, "source": [ "Your Turn:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Create a base class called animal with at least one attribute and one method.\n", "# Then create two more classes that inherit from the animal class \n", "# For example \"Mammal\" and \"Reptile.\"" ], "language": "python", "metadata": {}, "outputs": [] }, { "cell_type": "heading", "level": 2, "metadata": {}, "source": [ "A Time Formatter" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In order to get a feel for how simple programs can be constructed, let's take a look at simple program that I wrote and use every single day. We'll walk through each line of code together and discover how this code works. This exercise will be common as you continue to learn how to program." ] }, { "cell_type": "code", "collapsed": false, "input": [ "#!/usr/bin/env python\n", "# clock\n", "# Prints out the time specially formatted\n", "\n", "\"\"\"\n", "Prints out the time specially formatted\n", "\"\"\"\n", "\n", "##########################################################################\n", "## Imports\n", "##########################################################################\n", "\n", "import sys\n", "from datetime import datetime\n", "from dateutil.tz import tzlocal\n", "\n", "##########################################################################\n", "## A Clock Printer Object\n", "##########################################################################\n", "\n", "class Clock(object):\n", "\n", " # The \"default\" formats. Add more formats via subclasses or in the\n", " # instantation of a Clock object (or just add more here).\n", "\n", " # These formats are more complicated string formatting\n", " FORMATS = {\n", " \"code\":\"%a %b %d %H:%M:%S %Y %z\",\n", " \"json\":\"%Y-%m-%dT%H:%M:%S.%fZ\",\n", " \"cute\":\"%b %d, %Y\",\n", " }\n", "\n", " # class method - bound to the class\n", " # Get the current time\n", " # tzlocal will get the local timezone\n", " @classmethod\n", " def local_now(klass):\n", " return datetime.now(tzlocal())\n", "\n", " def __init__(self, formats={}):\n", " self.formats = self.FORMATS.copy()\n", " self.formats.update(formats)\n", "\n", " # strftime takes a format and returns a string representing the date\n", " def _local_format(self, fmt):\n", " return Clock.local_now().strftime(fmt)\n", "\n", " def get_stamp(self, name):\n", " # strips \"-\" from beginning and end of string\n", " # the string is \"-code\", \"-json\" or \"-cute\"\n", " name = name.strip(\"-\")\n", "\n", " if name in self.formats:\n", " return self._local_format(self.formats[name])\n", "\n", " return None\n", "\n", " def print_stamp(self, name):\n", " stamp = self.get_stamp(name)\n", " if stamp:\n", " print stamp\n", " else:\n", " print \"No stamp format for name %s\" % name\n", "\n", "##########################################################################\n", "## Main Method, handle inputs to program from command line\n", "##########################################################################\n", "\n", "# print __name__ in the python shell to see how this works\n", "if __name__ == \"__main__\":\n", "\n", " args = sys.argv[1:]\n", " clock = Clock()\n", " for arg in args:\n", " clock.print_stamp(arg)\n", "\n" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "No stamp format for name -f\n", "No stamp format for name /Users/SarahKelley/.ipython/profile_default/security/kernel-4d56b37b-9d68-482e-958c-317352f340c7.json\n", "No stamp format for name --IPKernelApp.parent_appname='ipython-notebook'\n", "No stamp format for name --profile-dir\n", "No stamp format for name /Users/SarahKelley/.ipython/profile_default\n", "No stamp format for name --parent=1\n" ] } ], "prompt_number": 102 }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [] } ], "metadata": {} } ] }