{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## What is a programming language?\n", "\n", "A programing language is a bundle of keywords, syntax and rules that can specify instructions to create a desired output using a computer: think about it like a cooking recipe of sorts, rather than a human language.\n", "\n", "*Python* is one type of programming languages (others include Perl, javascript, C, Java). It doesn't need to be compiled into machine code, it emphasizes readability and is often less wordy than other languages. Python is good for visualizing data, scraping websites, and building software.\n", "\n", "To start writing code, you just need a text editor. For today, most of the work will be done in this jupyter notebook." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Why do we like Python?" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python's documentation is good.\n", "\n", "You can find the official documentation here: https://docs.python.org/2/ \n", "There are a variety of NICAR Python-related tipsheets here: https://ire.org/resource-center/tipsheets/?q=python \n", "StackOverflow is a great place to get help with Python and other programming languages: https://stackoverflow.com/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## How to run a python script using your command line.\n", "\n", "On your machine, open up the command line: Start --> All programs --> Accessories --> Command Prompt (Windows) or the Terminal (Mac). The command line is how you can send commands to your computer to do various things. This is where we'll run a sample Python script we've included called `sample.py`.\n", "\n", "First, we'll go to the correct directory: `cd Desktop/nicar-2018-python`\n", "\n", "Then, we'll run the script: `python sample.py`" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What is a jupyter notebook?\n", "\n", "Jupyter Notebook is a relatively easy way to test, comment and display Python, R and Julia code. We're going to use it today to demonstrate some Python basics. \n", "\n", "In your command line, you should already be in this class' directory. If you're not, type `cd Desktop/nicar-2018-python` to get there. Then type `jupyter notebook` to open up a local notebook. This should open up a tab in a web browser and from there, you can click on `nicar_python_class.ipynb` to get to this notebook.\n", "\n", "*Hitting shift + enter will run a code block.*" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Doing basic math in the command line, jupyter notebooks, or IDLE.\n", "\n", "Python can be used as a really powerful calculator. Use the command line (type `python` to enter a python shell), this notebook or IDLE to do some math:" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "10" ] }, "execution_count": 14, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# This is a comment. Any line without a # before it is code.\n", "# Remember, hit shift + enter to run this code block and get an answer.\n", "6 + 4" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "31.208333333333332" ] }, "execution_count": 15, "metadata": {}, "output_type": "execute_result" } ], "source": [ "749 / 24" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "6235.0" ] }, "execution_count": 18, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# You don't have to worry about PEMDAS! Yay!\n", "67 * 93 + 32 / 8" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "2" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "# % is a symbol that indicates remainder after division.\n", "\n", "6 % 4" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Spaces and keywords matter.\n", "\n", "The Python interpreter reads spaces and certain words in order to understand what to do. So, indentation matters a lot and some words are out-of-bounds to use as variables: def, import, from, in, while, for, if, elif, else, print, input, and many more." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## You can install packages at the top of your script.\n", "\n", "Packages are typically specified to a certain function and allow you to use Python to do different things. Some examples:\n", "\n", "pandas for data analysis \n", "beautifulsoup for scraping \n", "regex for regular expressions and matching \n", "numpy for advanced math " ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# This is how you install a package.\n", "import pandas\n", "\n", "# If you only want to import a specific capability from a package, do it like this:\n", "from package import module\n", "\n", "# So, here's an example:\n", "from datetime import timedelta" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Some uses of python for us..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* A scraper: https://gist.github.com/kcecireyes/07db9ca13b8ab5cce83e4d567b2c1251\n", "* A geocoder: https://gist.github.com/rakeshsukla53/3662c574433699294d76\n", "* Fixing the output of a pdf converter: https://gist.github.com/jmunsch/bab4d88080d4a0198240" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic code block " ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Hi, friend.\n" ] } ], "source": [ "# This is a simple script with variables and printing.\n", "# Replace the 'name' input with your name and hit shift + enter.\n", "\n", "welcome = 'Hi, '\n", "name = 'friend.'\n", "print (welcome + name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# \"Fun!\"damentals" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What number is Rogers Park? It is 1.\n", "What number is Edgewater? It is 77.\n", "What number is Uptown? It is 3.\n", "What number is Forest Glen? It is 12.\n", "What number is Rogers Park? It is 1.\n", "What number is Edgewater? It is 77.\n", "What number is Uptown? It is 3.\n", "What number is Forest Glen? It is 12.\n" ] } ], "source": [ "# Variables are names assigned to a value, string or set of values or strings.\n", "# You should try to be specific in how you name your variables, so the person reading them can get\n", "# a sense of what is stored within them.\n", "\n", "# You're doing a story on Chicago's far north community areas. \n", "# Which variable names are better?\n", "\n", "communityareas = ['Rogers Park', 'Edgewater', 'Uptown', 'Forest Glen']\n", "numbers = [1, 77, 3, 12]\n", "for q, a in zip(communityareas, numbers):\n", " print('What number is {0}? It is {1}.'.format(q, a))\n", "\n", "foo = ['Rogers Park', 'Edgewater', 'Uptown', 'Forest Glen']\n", "bar = [1, 77, 3, 12]\n", "for q, a in zip(foo, bar):\n", " print('What number is {0}? It is {1}.'.format(q, a))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n" ] } ], "source": [ "# Types: integers, floats, strings, duples\n", "# Naming conventions exist for having variables of a certain type. For example, booleans (which can be true or false)\n", "# are often named with an \"if\" in front of them.\n", "\n", "# Uncomment each of the lines, one by one, and hit shift + enter to see what kind of value is assigned to each variable.\n", "\n", "counter = 100\n", "miles = 1000.0\n", "name = \"100\"\n", "\n", "print (type(counter))\n", "print (type(miles))\n", "print (type(name))" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What's your name?\n" ] } ], "source": [ "# Functions\n", "# What do you think this function does?\n", "\n", "def greet(name):\n", " print(\"Hello, {0}!\".format(name))\n", "print(\"What's your name?\")\n", "name = input()\n", "greet(name)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Control flow" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "5\n", "4\n", "3\n", "2\n", "1\n", "Blastoff!\n" ] } ], "source": [ "# While loop: \"while a certain condition is met, do a certain thing.\"\n", "\n", "time = 5\n", "while time > 0:\n", "\tprint (time)\n", "\ttime = time - 1\n", "\n", "print(\"Blastoff!\")\n", "\n", "# FUN FACT: This can create an infinite loop that never stops running until your computer hypothetically explodes*.\n", "\n", "# *This is an exaggeration. Still pretty cool." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Python is a programming language.\n", "R is a programming language.\n", "JavaScript is a programming language.\n", "Ruby is a programming language.\n" ] } ], "source": [ "# For loop: \"for each of these things, run the script in the indented area.\"\n", "\n", "\n", "languages = ['Python', 'R', 'JavaScript', 'Ruby']\n", "for language in languages:\n", " print (language + \" is a programming language.\")" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "0\n", "1\n", "2\n", "3\n", "95th\n", "4\n", "5\n", "6\n", "devon\n", "7\n", "8\n", "9\n", "10\n" ] } ], "source": [ "# If, elif, else: \"if a certain condition is met, do a certain thing; if a certain other condition is met, do something\n", "# else; or, last resort, do a certain other thing.\"\n", "\n", "chicago_streets = ['wacker', 'lasalle', 'state', 'michigan', '95th', 'garfield', 'midway plaisance', 'broadway', 'devon', 'cicero', 'kedzie', 'fullerton', 'oak']\n", "counter = 0\n", "for street in chicago_streets:\n", " if street == 'devon':\n", " print (street)\n", " elif 'th' in street:\n", " print (street)\n", " else:\n", " print (counter)\n", " counter = counter + 1" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Thank you!\n", "Thank you!\n", "Thank you!\n", "Thank you!\n", "4\n" ] } ], "source": [ "# Write your own loop!\n", "\n", "# Your counter is at 0.\n", "# You have a list of sources. (given)\n", "# For each source in the list,\n", "# print \"thank you\"\n", "# and add one to the counter.\n", "# When the loop is complete, print the counter.\n", "\n", "counter = 0\n", "sources = ['Emanuel', 'Duckworth', 'Pritzker', 'Preckwinkle']\n", "for source in sources:\n", " print (\"Thank you!\")\n", " counter = counter + 1\n", "print (counter)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data structures" ] }, { "cell_type": "code", "execution_count": 34, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "['ct', 606, 3.14, 'juan', 20.1]\n", "[606, 3.14]\n", "[3.14, 'juan', 20.1]\n", "[0, 'jamila', 0, 'jamila']\n", "['ct', 606, 3.14, 'juan', 20.1, 0, 'jamila']\n" ] } ], "source": [ "# Lists\n", "\n", "list = [ 'ct', 606 , 3.14, 'juan', 20.1 ]\n", "tinylist = [000, 'jamila']\n", "\n", "print (list) # Prints complete list\n", "print (list[1:3]) # Prints elements starting from 2nd till 3rd \n", "print (list[2:]) # Prints elements starting from 3rd element\n", "print (tinylist * 2) # Prints list two times\n", "print (list + tinylist) # Prints concatenated lists" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4139\n", "dict_keys(['Kori', 'Chad', 'Ryan'])\n", "False\n" ] } ], "source": [ "# Dicts\n", "\n", "phone_numbers = {'Kori': 4098, 'Chad': 4139, 'Ryan': 4265}\n", "\n", "print(phone_numbers['Chad'])\n", "print(phone_numbers.keys())\n", "print('Cecilia' in phone_numbers)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Troubleshooting" ] }, { "cell_type": "code", "execution_count": 41, "metadata": {}, "outputs": [ { "ename": "IndentationError", "evalue": "expected an indented block (, line 5)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m5\u001b[0m\n\u001b[0;31m print(x)\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mIndentationError\u001b[0m\u001b[0;31m:\u001b[0m expected an indented block\n" ] } ], "source": [ "# Indentation error\n", "\n", "foods = ['pizza', 'naan', 'tacos']\n", "for x in foods:\n", "print(x)\n", "\n", "# \"print(x)\" should be indented because it's within a for block." ] }, { "cell_type": "code", "execution_count": 43, "metadata": {}, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 4)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m4\u001b[0m\n\u001b[0;31m for x in foods\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "# Syntax error\n", "\n", "foods = ['pizza', 'naan', 'tacos']\n", "for x in foods\n", " print(x)\n", " \n", "# There should be a colon after \"for x in foods\" because syntax." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "collapsed": true }, "outputs": [], "source": [ "# Scope errors\n", "\n", "foods = ['pizza', 'naan', 'tacos']\n", "\n", "def print_foods():\n", " foods = foods + ['paczki']\n", " print (foods)\n", "\n", "print_foods()\n", "\n", "# The variable \"foods\" should be defined within the function \"print_foods\"." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "ename": "TypeError", "evalue": "cannot concatenate 'str' and 'int' objects", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\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[0;31m# Type errors\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mis_this_right\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"Probably not\"\u001b[0m\u001b[0;34m+\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", "\u001b[0;31mTypeError\u001b[0m: cannot concatenate 'str' and 'int' objects" ] } ], "source": [ "# Type errors\n", "\n", "is_this_right = \"Probably not\"+1\n", "\n", "# You can't concatenate a string and an integer." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }