Skip to content

Instantly share code, notes, and snippets.

@jonathanmorgan
Last active November 14, 2016 18:02
Show Gist options
  • Save jonathanmorgan/8cf8c1c37705430629a5 to your computer and use it in GitHub Desktop.
Save jonathanmorgan/8cf8c1c37705430629a5 to your computer and use it in GitHub Desktop.
class4-Intro_to_python.ipynb
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Introduction to Python\n",
"\n",
"With substantial material borrowed from:\n",
"\n",
"- [http://introtopython.org](http://introtopython.org)\n",
"- [http://ibug-um.github.io/2014-summer-camp/slides/ICOS-python-lecture.html](http://ibug-um.github.io/2014-summer-camp/slides/ICOS-python-lecture.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Table of Contents\n",
"\n",
"- [Setup](#Setup)\n",
"- [Intro to Python](#Intro-to-Python)\n",
"\n",
" - [Comments](#Comments)\n",
" - [Variables and Assignment](#Variables-and-Assignment)\n",
" - [Types of Values](#Types-of-Values)\n",
" \n",
" - [`None`](#None)\n",
" - [Boolean](#Boolean)\n",
" - [Numbers](#Numbers)\n",
" - [Strings](#Strings)\n",
" - [Lists](#Lists)\n",
" - [Dictionaries](#Dictionaries)\n",
" \n",
" - [Flow of Control](#Flow-of-Control)\n",
" \n",
" - [`if...elif...else`](#if...elif...else)\n",
" - [Loops](#Loops)\n",
" - [Nested control structures](#Nested-control-structures)\n",
" \n",
" - [Reading from a File](#Reading-from-a-File)\n",
" \n",
"- [Odds and Ends](#Odds-and-Ends)\n",
"\n",
" - [Create folder in git repo](#Create-folder-in-git-repo)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Setup\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"To start, you should download this IPython Notebook to your own computer, so you can play with and run the examples yourself, as we progress. There are two ways to download this IPython notebook:\n",
"\n",
"- if you are viewing this on http://nbviewer.ipython.org, you can:\n",
" - scroll all the way to the top so the header appears, then click the button in the upper right hand corner of the pate that looks like a down arrow pointing at a bar with two dots. This will open the ipython notebook in your browser window as a JSON file.\n",
" - save that file to your computer as \"Intro_to_python.ipynb\".\n",
" \n",
"- by cloning the gist from github.com:\n",
" - in a command shell, cd to the directory where you want to pull down the gist.\n",
" - use the git client to clone the git repository for this file:\n",
" \n",
" git clone https://gist.github.com/8cf8c1c37705430629a5.git\n",
" \n",
" The file will be inside a folder named 8cf8c1c37705430629a5.\n",
"\n",
"Once you have the file downloaded:\n",
"- open up IPython Notebook.\n",
"- navigate to the folder where you downloaded the file.\n",
"- open the notebook."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Intro to Python\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Comments\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Comments are lines in your program that are ignored by the Python interpreter when the program is run. You can use comments to describe what is going on in your program. You can also use comments to stop python commands that you comment out from running, but leave them in the file.\n",
"\n",
"There are two ways to comment - single-line (\"#\") and multi-line (\"'''\")\n",
"\n",
"- single-line - put a pound sign ( \"#\" ) at the beginning of any line in your program that you want python to ignore:"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"DEBUG: 3\n"
]
}
],
"source": [
"test_var = 3\n",
"\n",
"# output debug to see what is in test_var\n",
"print( \"DEBUG: \" + str( test_var ) )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- multi-line comment - any number of lines, preceded by and followed by three single-quotes ('''). Example:"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"print() outside the multi-line comment.\n"
]
}
],
"source": [
"'''\n",
"print( \"==> At start of multi-line comment.\" )\n",
"\n",
"This is a multi-line comment.\n",
"Very nice, eh?\n",
"\n",
"# print( \"==> At end of multi-line comment.\" )\n",
"'''\n",
"print( \"print() outside the multi-line comment.\" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In general, comment by placing the single-line \"#\" in front of individual lines, so you can wrap whole sections in ''' ''' later.\n",
"\n",
"And, ALWAYS comment your code.\n",
"\n",
"#### What makes a good comment?\n",
"\n",
"- It is short and to the point, but a complete thought. Most comments should be written in complete sentences.\n",
"- It explains your thinking, so that when you return to the code later you will understand how you were approaching the problem.\n",
"- It explains your thinking, so that others who work with your code will understand your overall approach to a problem.\n",
"- It explains particularly difficult sections of code in detail.\n",
"\n",
"#### When should you write a comment?\n",
"\n",
"- When you have to think about code before writing it.\n",
"- When you are likely to forget later exactly how you were approaching a problem.\n",
"- When there is more than one way to solve a problem.\n",
"- When others are unlikely to anticipate your way of thinking about a problem.\n",
"\n",
"<hr />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Variables and Assignment\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Variables are names to which you assign values. You use the \"=\" operator to assign a value to a variable. Example:"
]
},
{
"cell_type": "code",
"execution_count": 27,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"A string: \"This is a string\"\n"
]
}
],
"source": [
"a_string = \"This is a string\"\n",
"print( \"A string: \\\"\" + a_string + \"\\\"\" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can change the value referenced by a variable at any time:"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"This is a string\n",
"Same variable, but different string value\n"
]
}
],
"source": [
"# set the string\n",
"a_string = \"This is a string\"\n",
"print( a_string )\n",
"\n",
"# change the value\n",
"a_string = \"Same variable, but different string value\"\n",
"print( a_string )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Naming rules\n",
"\n",
"- Variables can only contain letters, numbers, and underscores. Variable names can start with a letter or an underscore, but can not start with a number.\n",
"- Spaces are not allowed in variable names, so we use underscores instead of spaces. For example, use student_name instead of \"student name\".\n",
"- You cannot use Python keywords as variable names.\n",
"- Variable names should be descriptive, without being too long. For example mc_wheels is better than just \"wheels\", and number_of_wheels_on_a_motorycle.\n",
"- Be careful about using the lowercase letter l and the uppercase letter O in places where they could be confused with the numbers 1 and 0.\n",
"\n",
"<hr />"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Types of Values\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Python doesn't require you to declare the type of a given variable when you declare it, but all values you place in a variable are typed.\n",
"\n",
"There are a small number of different core value types built-in to python. These types are referred to as \"scalars\" or \"atomic types\", because they are the most basic data types in the language (like atoms are to matter, ignoring quarks, etc.).\n",
"\n",
"You can use the type() function to check the type of a given variable:"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<type 'NoneType'>\n",
"<type 'str'>\n"
]
}
],
"source": [
"test_var = None\n",
"print( type( test_var ) )\n",
"\n",
"test_var = \"a string\"\n",
"print( type( test_var ) )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### `None`\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"The value _`None`_ is a special object in python that is used to show that a variable was declared, but was explicitly set to contain nothing. It can be used to initialize a variable that will eventually hold an object, or used to signal that something went wrong. Example:"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"ERROR - missing thing!\n"
]
}
],
"source": [
"super_important_thing = None\n",
"if ( super_important_thing is None ):\n",
" \n",
" # ERROR - missing thing!\n",
" print( \"ERROR - missing thing!\" )\n",
" \n",
"#-- END check to see if we have super_important_thing --#"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Boolean\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"The two boolean values _`True`_ and _`False`_ are another set of special objects in Python, used to represent the data type _`bool`_ (for boolean), where there are only two possible values - _`True`_ and _`False`_. In some languages, these values are sometimes represented by 1 (true) and 0 (false). They are often used in variables that control branching logic. Example:"
]
},
{
"cell_type": "code",
"execution_count": 31,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I guess I'll stop...\n"
]
}
],
"source": [
"is_OK_to_go_on = False\n",
"\n",
"# OK to go on?\n",
"if ( is_OK_to_go_on is True ):\n",
" \n",
" # yes - OK to go on.\n",
" print( \"Go on!\" )\n",
" \n",
"else:\n",
" \n",
" # no - What is the use...\n",
" print( \"I guess I'll stop...\" )\n",
" \n",
"#-- END check to see if OK to go on... --#"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Numbers\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"There are two basic types of numbers in Python: integers (int and long) and decimals (float).\n",
"\n",
"Integers are whole numbers with no decimal component:"
]
},
{
"cell_type": "code",
"execution_count": 32,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"an_int = 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"floats can also have a decimal component:"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"a_float = 2.394"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"When you set a variable to a number, you don't place the numeric value in quotes.\n",
"\n",
"Operators: Numbers have all of the basic mathematical operators you'd expect, and a few you might not. The expected ones:\n",
"\n",
"- \\+ : addition\n",
"- \\- : subtraction\n",
"- \\* : multiplication\n",
"- / : division (in python 2.7, integer division returns only the integer part of the quotient. To get remainder, you need to use the modulo operator).\n",
"- % : modulo operator - returns the remainder of division that is not even.\n",
"- \\*\\* : exponent operator (a \\*\\* b = a to the b)\n",
"- \\+= : takes the value in the variable on the left of the operator, adds the value on the right to it, then stores the result back in the variable on the left (see example below).\n",
"\n",
"Examples:"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"10 divided by 3 is 3.33333333333 or 3 with a remainder of 1.\n",
"8 / 3 = 3 (the whole number part of the quotient )\n",
"8 % 3 = 1 (the remainder)\n",
"record_counter = 3\n"
]
}
],
"source": [
"an_int = 10\n",
"another_int = 3\n",
"\n",
"# integer division\n",
"int_div = an_int / another_int\n",
"\n",
"# integer modulo\n",
"int_mod = an_int % another_int\n",
"\n",
"# calculate decimal quotient\n",
"float_quotient = float( an_int ) / float( another_int )\n",
"\n",
"# print summary\n",
"print( str( an_int ) + \" divided by \" + str( another_int ) + \" is \" + str( float_quotient ) + \" or \" + str( int_div ) + \" with a remainder of \" + str( int_mod ) + \".\" )\n",
"\n",
"# print results of integer division and modulo.\n",
"print( \"8 / 3 = \" + str( int_div ) + \" (the whole number part of the quotient )\" )\n",
"print( \"8 % 3 = \" + str( int_mod ) + \" (the remainder)\" )\n",
"\n",
"# and the += operator\n",
"record_counter = 2\n",
"\n",
"# add 1 to record_counter\n",
"record_counter += 1\n",
"\n",
"# alternate: record_counter = record_counter + 1\n",
"\n",
"print( \"record_counter = \" + str( record_counter ) )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Strings\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Strings are collections of one or more text characters. They can be defined with either single- or double-quotes:"
]
},
{
"cell_type": "code",
"execution_count": 34,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"single_quote_string = 'My single-quote string'\n",
"double_quote_string = \"My double-quote string\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"In Python, there is no difference in declaring a string with single- or double-quotes. Using one allows you to easily include the other in the string:"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"single_quote_string = 'My \"single-quote\" string'\n",
"double_quote_string = \"My 'double-quote' string\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"The plus operator \"+\" lets you combine, or \"concatenate\" multiple strings into one string. When you concatenate, you can combine both strings and variables that contain strings:"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"My \"single-quote\" string AND My 'double-quote' string\n"
]
}
],
"source": [
"single_quote_string = 'My \"single-quote\" string'\n",
"double_quote_string = \"My 'double-quote' string\"\n",
"combined_string = single_quote_string + \" AND \" + double_quote_string\n",
"print( combined_string )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can also use the += operator to add on to the end of an existing string stored in a variable, just like you can use it to add to a number stored in a variable (takes string on the left of operator, appends string on the right to it, then stores the result in the variable on the left side of the operator). Example:"
]
},
{
"cell_type": "code",
"execution_count": 15,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"My \"single-quote\" string AND My 'double-quote' string\n"
]
}
],
"source": [
"single_quote_string = 'My \"single-quote\" string'\n",
"double_quote_string = \"My 'double-quote' string\"\n",
"\n",
"# building up a string using +=\n",
"\n",
"# put the first string in your combined_string variable.\n",
"combined_string = single_quote_string\n",
"\n",
"# then add the other strings using the += operator\n",
"combined_string += \" AND \"\n",
"combined_string += double_quote_string\n",
"\n",
"# prints the same as the example above.\n",
"print( combined_string )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Other string operators:\n",
"\n",
"_Note: operators can have different type-specific behaviors when used on variables that contain values of different types - the plus ( \"+\" ) operator, for example, does addition on numbers, concatenation on Strings._\n",
"\n",
"- [] - Slice - Gives the character from the given index (A negative number starts from the end)\n",
"- [ : ] - Range Slice - Gives the characters from the given range \n",
"- in - Membership - Returns true if a character exists in the given string \n",
"- not in - Membership - Returns true if a character does not exist in the given string \n",
"\n",
"In addition, strings are objects with many helpful methods. Methods are functions that are bound to a certain type of data. You invoke a method on an object using the dot operator - a period \".\". Some examples:"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"lower(): \"\t\tgoofy case string, with lots of, extra white space! \"\n",
"strip(): \"GoOfY Case stRing, wItH LOTS of, extra wHiTe space!\"\n",
"replace(): \"\t\tGoOfY Case stRing wItH LOTS of extra wHiTe space! \"\n",
"['GoOfY', 'Case', 'stRing,', 'wItH', 'LOTS', 'of,', 'extra', 'wHiTe', 'space!']\n"
]
}
],
"source": [
"test_string = \"\\t\\tGoOfY Case stRing, wItH LOTS of, extra wHiTe space! \"\n",
"\n",
"# convert to lower case\n",
"lower_string = test_string.lower()\n",
"print( \"lower(): \\\"\" + lower_string + \"\\\"\" )\n",
"\n",
"# strip extra white space from either end of the string.\n",
"stripped_string = test_string.strip()\n",
"print( \"strip(): \\\"\" + stripped_string + \"\\\"\" )\n",
"\n",
"# remove commas\n",
"no_commas = test_string.replace( \",\", \"\" )\n",
"print( \"replace(): \\\"\" + no_commas + \"\\\"\" )\n",
"\n",
"# split string on spaces into a list of strings.\n",
"word_list = test_string.split()\n",
"print( word_list )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For a complete list of string methods, see the String Methods section of the official Python 2 documentation: [https://docs.python.org/2/library/stdtypes.html#string-methods](https://docs.python.org/2/library/stdtypes.html#string-methods)\n",
"\n",
"Also note the \"_`\\t`_\" and \"_`\\\"`_\" in the above example. Python has special escape characters that let you add white space, quotation marks, and other special characters to strings. Examples:\n",
"\n",
"- `\\t` - inserts a tab\n",
"- `\\n` - inserts a newline\n",
"- `\\\"` - inserts a double-quote in a double-quoted string"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Lists\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Lists and dictionaries are two of the most versatile data types available in Python. A list is a sequence of values in a set order. They are declared by entering a comma-separated list of values enclosed by square brackets. Items in a list do not have to be of the same type. Example:"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['one', 'two', 'three']\n"
]
}
],
"source": [
"# list of strings\n",
"string_list = [ \"one\", \"two\", \"three\" ]\n",
"print( string_list )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can access a given item in a list using its index. Lists are 0-indexed, so to get the first thing you ask for index 0, the second thing is at index 1, etc. (it is related to the C language and how that language dealt with memory pointers - if you want to know more, let me know):"
]
},
{
"cell_type": "code",
"execution_count": 49,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"first = one\n",
"second = two\n",
"last item in list = three\n",
"['zero', 'two', 'three']\n"
]
}
],
"source": [
"# list of strings\n",
"string_list = [ \"one\", \"two\", \"three\" ]\n",
"print( \"first = \" + string_list[ 0 ] )\n",
"print( \"second = \" + string_list[ 1 ] )\n",
"\n",
"# you can also add a minus sign \"-\" to start from the right - this IS NOT zero-indexed.\n",
"print( \"last item in list = \" + string_list[ -1 ] )\n",
"\n",
"# and you can use this syntax to modify an element in a list\n",
"string_list[ 0 ] = \"zero\"\n",
"print( string_list )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Lists have a number of functions and methods associated with them.\n",
"\n",
"Some functions include: cmp(list1, list2) len(list) max(list) min(list) list(seq)\n",
"\n",
"Some of the methods are: count(), index(obj)\n",
"\n",
"Some list methods are in-place. This means that the lists are changed, but the methods don't \"return\" anything. These include sort(), reverse(), insert(), append(), and remove.\n",
"\n",
"The full list of list methods: [https://docs.python.org/2/tutorial/datastructures.html#more-on-lists](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists)\n",
"\n",
"Examples:"
]
},
{
"cell_type": "code",
"execution_count": 50,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"['one', 'two', 'three', 'four', 'five']\n",
"['zero', 'one', 'two', 'three', 'four', 'five']\n",
"6\n"
]
}
],
"source": [
"string_list = [ \"one\", \"two\", \"three\", \"four\" ]\n",
"\n",
"# append an item to the list\n",
"string_list.append( \"five\" )\n",
"print( string_list )\n",
"\n",
"# insert something at the first position\n",
"string_list.insert( 0, \"zero\" )\n",
"print( string_list )\n",
"\n",
"# length of list?\n",
"print( str( len( string_list ) ) )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"More information on lists:\n",
"- [http://introtopython.org/lists_tuples.html](http://introtopython.org/lists_tuples.html)\n",
"- [https://docs.python.org/2/tutorial/datastructures.html#more-on-lists](https://docs.python.org/2/tutorial/datastructures.html#more-on-lists)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Dictionaries\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Dictionaries store information in key-value pairs, so that any one piece of information in a dictionary is connected to at least one other piece of information. Keys and values can be of any type.\n",
"\n",
"Dictionaries do not store their information in any particular order, so you may not get your information back in the same order you entered it.\n",
"\n",
"Examples of making dictionaries:"
]
},
{
"cell_type": "code",
"execution_count": 13,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'name2': 'value2', 'name3': 'value3', 'name1': 'value1'}\n",
"{'name2': 'value2', 'name3': 'value3', 'name1': 'value1'}\n"
]
}
],
"source": [
"# make a dictionary on one line:\n",
"test_dict = { \"name1\" : \"value1\", \"name2\" : \"value2\", \"name3\" : \"value3\" }\n",
"print( test_dict )\n",
"\n",
"# or, one item per line:\n",
"test_dict2 = {\n",
" \"name1\" : \"value1\",\n",
" \"name2\" : \"value2\",\n",
" \"name3\" : \"value3\"\n",
"}\n",
"print( test_dict2 )\n",
"\n",
"# create an empty dictionary (preferred):\n",
"empty_dict = {}\n",
"\n",
"# OR (though it is supposedly much slower)\n",
"another_empty_dict = dict()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"You can access a given value in or add a new value to a dictionary using its name and the same square-bracket syntax used to get a particular item in a list. You can use the `del()` function to remove an item from the dictionary. You can also use the \"in\" operator to see if a name is present in a dictionary."
]
},
{
"cell_type": "code",
"execution_count": 56,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"{'name4': 'value4', 'name2': 'value2', 'name3': 'value3', 'name1': 'value1'}\n",
"Value for name2 = \"value2\"\n",
"==> removed name2:\n",
"{'name4': 'value4', 'name3': 'value3', 'name1': 'value1'}\n",
"Value for name3 = \"value3\"\n"
]
}
],
"source": [
"# make a dictionary:\n",
"test_dict = { \"name1\" : \"value1\", \"name2\" : \"value2\", \"name3\" : \"value3\" }\n",
"\n",
"# add a fourth name and value\n",
"test_dict[ \"name4\" ] = \"value4\"\n",
"print( test_dict )\n",
"\n",
"# note that the items are not in order.\n",
"\n",
"# get value for name2\n",
"value_2 = test_dict[ \"name2\" ]\n",
"print( \"Value for name2 = \\\"\" + value_2 + \"\\\"\" )\n",
"\n",
"# remove name and value for name 2\n",
"del( test_dict[ \"name2\" ] )\n",
"print( \"==> removed name2:\" )\n",
"print( test_dict )\n",
"\n",
"# get the value for name3, but a little fancier.\n",
"desired_name = \"name3\"\n",
"if ( desired_name in test_dict ):\n",
"\n",
" # name is in the dictionary, get its value.\n",
" desired_value = test_dict[ desired_name ]\n",
" print( \"Value for \" + desired_name + \" = \\\"\" + desired_value + \"\\\"\" )\n",
" \n",
"else:\n",
" \n",
" # name not present.\n",
" print( \"name \\\"\" + desired_name + \"\\\" not present in dictionary.\" )\n",
"\n",
"#-- END check to see if name in dict --#"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Dictionaries have their own set of functions and methods just like lists do, and since values can be of any type, you can create substantially complex data structures using dictionaries, including dictionaries where each name references a dictionary or a list. This is advanced so we'll leave that for another time, but the link below goes into more detail if you are interested.\n",
"\n",
"More information on dictionaries:\n",
"\n",
"- [http://introtopython.org/dictionaries.html](http://introtopython.org/dictionaries.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Flow of Control\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"The real power of computing is selection and repetition. Selection is when you use comparison operators to direct which path the program should take (`if...elif..else...`). Repetition is when code is executed multiple times (`for`, `while` loops).\n",
"\n",
"_NOTE: Python uses indentation to keep track of where a given statement belongs in nested constructs like those below. In Python, it is VERY important to be consistent in your indentation. It is standard to use spaces, not tabs, for indentation, and to indent 4 spaces per level._"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### if...elif...else\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"An if statement tests for a condition, and then responds to that condition. If the condition is true, then whatever action is listed next gets carried out. You can test for multiple conditions at the same time, and respond appropriately to each condition.\n",
"\n",
"Example:"
]
},
{
"cell_type": "code",
"execution_count": 57,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I like ice cream\n",
"I like chocolate\n",
"apple crisp is my favorite dessert!\n",
"I like cookies\n"
]
}
],
"source": [
"# A list of desserts I like.\n",
"desserts = [ 'ice cream', 'chocolate', 'apple crisp', 'cookies' ]\n",
"favorite_dessert = 'apple crisp'\n",
"\n",
"# Print the desserts out, but let everyone know my favorite dessert.\n",
"for dessert in desserts:\n",
"\n",
" # is this dessert my favorite?\n",
" if dessert == favorite_dessert:\n",
"\n",
" # This dessert is my favorite, let's let everyone know!\n",
" print( dessert + \" is my favorite dessert!\" )\n",
"\n",
" # Use else to deal with case where condition is false.\n",
" else:\n",
"\n",
" # I like these desserts, but they are not my favorite.\n",
" print( \"I like \" + dessert )\n",
" \n",
" #-- END check to see if favorite dessert --#\n",
" \n",
"#-- END loop over desserts --#\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Every `if` statement evaluates to `True` or `False` (Python's `bool` keywords). You can test for the following conditions in your `if` statements:\n",
"\n",
"- equality (==)\n",
"- inequality (!=)\n",
"- greater than (>)\n",
"- greater than or equal to (>=)\n",
"- less than (<)\n",
"- less than or equal to (<=)\n",
"- You can test if an item is `in` a list.\n",
"\n",
"You can also chain together a series of conditions using the `elif` operator:"
]
},
{
"cell_type": "code",
"execution_count": 59,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Holy mackerel 6 dogs! We might as well start a dog hostel!\n"
]
}
],
"source": [
"# make list of dogs\n",
"dogs = ['willie', 'hootz', 'peso', 'monty', 'juno', 'turkey']\n",
"\n",
"# get dog count\n",
"dog_count = len( dogs )\n",
"\n",
"# do different things based on different numbers of dogs.\n",
"if dog_count >= 5:\n",
" print(\"Holy mackerel \" + str( dog_count ) + \" dogs! We might as well start a dog hostel!\")\n",
"elif dog_count >= 3:\n",
" print(\"Wow, we have a lot of dogs here!\")\n",
"else:\n",
" print( \"Okay, this is a reasonable number of dogs.\" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Loops\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Python has two looping constructs that allow you to repeat a chunk of code until either you iterate through a list (`for` loop) or a criteria is met (`while` loop).\n",
"\n",
"The `for` statement in Python iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended), from above:"
]
},
{
"cell_type": "code",
"execution_count": 60,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"I like ice cream\n",
"I like chocolate\n",
"apple crisp is my favorite dessert!\n",
"I like cookies\n"
]
}
],
"source": [
"# A list of desserts I like.\n",
"desserts = [ 'ice cream', 'chocolate', 'apple crisp', 'cookies' ]\n",
"favorite_dessert = 'apple crisp'\n",
"\n",
"# Print the desserts out, but let everyone know my favorite dessert.\n",
"for dessert in desserts:\n",
"\n",
" # is this dessert my favorite?\n",
" if dessert == favorite_dessert:\n",
"\n",
" # This dessert is my favorite, let's let everyone know!\n",
" print( dessert + \" is my favorite dessert!\" )\n",
"\n",
" # Use else to deal with case where condition is false.\n",
" else:\n",
"\n",
" # I like these desserts, but they are not my favorite.\n",
" print( \"I like \" + dessert )\n",
" \n",
" #-- END check to see if favorite dessert --#\n",
" \n",
"#-- END loop over desserts --#\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"`for` loops can also be used to loop over dictionaries using the `.items()` dictionary method to iterate over each name-value pair:"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"name = \"name2\"; value = \"value2\"\n",
"name = \"name3\"; value = \"value3\"\n",
"name = \"name1\"; value = \"value1\"\n"
]
}
],
"source": [
"# make a dictionary:\n",
"test_dict = { \"name1\" : \"value1\", \"name2\" : \"value2\", \"name3\" : \"value3\" }\n",
"\n",
"# loop!\n",
"for current_name, current_value in test_dict.items():\n",
"\n",
" print( \"name = \\\"\" + current_name + \"\\\"; value = \\\"\" + current_value + \"\\\"\" )\n",
" \n",
"#-- END loop over test_dict --#"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"A `while` loop tests an initial condition. If that condition is true, the loop starts executing. Every time the loop finishes, the condition is reevaluated. As long as the condition remains true, the loop keeps executing. As soon as the condition becomes false, the loop stops executing. Example:"
]
},
{
"cell_type": "code",
"execution_count": 63,
"metadata": {
"collapsed": false
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 - Go on!\n",
"1 - Go on!\n",
"2 - Go on!\n",
"3 - Go on!\n",
"4 - Go on!\n",
"5 - Go on!\n",
"I guess I'll stop...\n"
]
}
],
"source": [
"is_OK_to_go_on = True\n",
"\n",
"# OK to go on?\n",
"my_counter = 0\n",
"while is_OK_to_go_on is True:\n",
" \n",
" # yes - OK to go on.\n",
" print( str( my_counter ) + \" - Go on!\" )\n",
" \n",
" # increment counter\n",
" my_counter += 1\n",
" \n",
" # if counter greater than 5, don't go on.\n",
" if my_counter > 5:\n",
" \n",
" # don't go on.\n",
" is_OK_to_go_on = False\n",
" \n",
" #-- END check to see if counter is too high. --#\n",
"\n",
"#-- END check to see if OK to go on... --# \n",
"\n",
"# no - What is the use...\n",
"print( \"I guess I'll stop...\" )"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"With while loops, you need to be careful to initialize variables and code your boundary logic properly so you don't accidentally make your loop go on forever.\n",
"\n",
"For example, if you wanted to make the code above loop forever, change the comparison operator in `if my_counter > 5:` to `==`: `if my_counter == 5:`, then initialize my_counter to 6 before entering the loop. It is good to note here that if you try this, you can stop the running program by hitting the big black square button above. Or you might also just crash Firefox and have to kill it and the ipython server, and restart everything (as I just did while creating this)."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Nested control structures\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"As you can see from the examples above, you can nest conditionals and loops inside other conditionals and loops, and you can do this nesting as many levels deep as you need to (though it is polite to break up different levels of deeply nested code into functions, to make the code more modular and readable). To place a loop or conditional inside another parent loop or conditional, start the \"for\" or \"if\" statement of the second, nested control structure at the same indentation level as the rest of the code inside the outer loop or conditional branch, then indent the code inside the nested block 4 more spaces past the indentation of the nested statement itself."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For more information on control flow in Python, see:\n",
"\n",
"- [https://docs.python.org/2/tutorial/controlflow.html](https://docs.python.org/2/tutorial/controlflow.html)\n",
"- [http://introtopython.org/while_input.html](http://introtopython.org/while_input.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Reading from a File\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Reading from a file in Python is very straight forward. You use the `open()` function to open a file and store a reference to the file in a variable. Once a file is open, you can loop over the lines in a file just like you would a list, store the entire contents of the file in a variable, or read each line of the file into a list that you can iterate over later. Then, once you are done reading, you call the `.close()` method on the file variable to close out the file.\n",
"\n",
"The `open()` function accepts two arguments:\n",
"\n",
"- filename - the name or path of the file you want to open. If you just pass a file name, Python will look in the current working directory for a file with that name. If you pass a full path, Python will try to access that path to open the file.\n",
"- mode - a string that tells the open command how you intend to interact with the file you are opening. Values:\n",
"\n",
" - \"r\" - read-only access.\n",
" - \"w\" - write-only, and if file already exists, it will be overwritten.\n",
" - \"a\" - write-only, but appends to end of file if it already exists.\n",
" - \"r+\" - read and write.\n",
"\n",
"For now, we are just going to cover reading files:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"# store file name.\n",
"file_name = \"pg1513.txt\"\n",
"\n",
"# open the file.\n",
"my_file = open( \"pg1513.txt\", \"r\")\n",
"\n",
"# loop over lines in file.\n",
"for current_line in my_file:\n",
"\n",
" # print the line\n",
" print( current_line )\n",
"\n",
"#-- END loop over lines of file --#\n",
" \n",
"f.close()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"For more information on reading from and writing to files in Python:\n",
"\n",
"- [https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files)\n",
"- [http://www.diveintopython.net/file_handling/file_objects.html](http://www.diveintopython.net/file_handling/file_objects.html)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Odds and Ends\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Create folder in git repo\n",
"\n",
"- back to [Table of Contents](#Table-of-Contents)\n",
"\n",
"Creating a folder inside a git repository _(and intro to using git command line!)_\n",
"\n",
"- open command shell.\n",
"- cd to git repository (using tab completion!)\n",
"- Make directory (mkdir)\n",
"\n",
" mkdir notes\n",
"\n",
"- Put a file there (I'll briefly make one with vi - :q!)\n",
"\n",
" cd notes\n",
" vi note-class4.txt\n",
"\n",
"- Change directories back to repository root.\n",
"\n",
" cd ..\n",
"\n",
"- Check to see what has been changed since last commmit:\n",
"\n",
" git status\n",
"\n",
"- Tell git you want to add the new folder and its contents.\n",
"\n",
" git add notes\n",
" git status\n",
"\n",
"- Commit your changes\n",
"\n",
" git commit\n",
"\n",
" - enter message and save\n",
"\n",
"- Before sending changes to server, see if anything has changed on the server since last time you checked.\n",
"\n",
" git pull\n",
"\n",
"- Then, send the changes in your commit up to the server.\n",
"\n",
" git push"
]
}
],
"metadata": {
"anaconda-cloud": {},
"kernelspec": {
"display_name": "Python [default]",
"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.5.2"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment