Commit 2820c217 authored by Arucas Chacon's avatar Arucas Chacon

Empty notebooks

parent 665dbfe4
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Data Types and Type Conversion\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Every value has a type."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Every value in a program has a specific type.\n",
"* For instance: integer,float, string\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use the built-in function type to find the type of a value.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Types control what operations (or methods) can be performed on a given value.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## You can use the “+” and “*” operators on strings.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Strings have a length (but numbers don’t)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Must convert numbers to strings or vice versa when operating on them.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Can mix integers and floats freely in operations.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Complex numbers"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Python provides complex numbers, which are written as <span class=\"label label-default\">1.0+2.0j</span>. If val is an imaginary number, its real and imaginary parts can be accessed using dot notation as <span class=\"label label-default\">val.real</span> and <span class=\"label label-default\">val.imag</span>."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Types</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" What type of value is 3.4?<br>\n",
" What type of value is 3.25 + 4?<br>\n",
" What type of value is 4/2?<br>\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Division Types</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"In Python 3, the // operator performs integer (whole-number) floor division, the / operator performs floating-point division, and the ‘%’ (or modulo) operator calculates and returns the remainder from integer division.<br>\n",
"\n",
"However in Python2 (and other languages), the / operator between two integer types perform a floor (//) division. To perform a float division, we have to convert one of the integers to float\n",
" </div>\n",
"</div>\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"print('5 // 3 =', 5//3)\n",
"print('5 / 3 =', 5/3)\n",
"print('5 % 3 =', 5%3)\n",
"print('float(5)/3 =', float(5) / 3 )\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"\n",
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Arithmetic with Different Types</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" Which of the following will print 2.0? Note: there may be more than one right answer.<br>\n",
" first = 1.0<br>\n",
"second = \"1\"<br>\n",
"third = \"1.1\"<br>\n",
"<br> \n",
"<br> \n",
"1. first + float(second)<br>\n",
"2. float(second) + float(third)<br>\n",
"3. first + int(third)<br>\n",
"4. first + int(float(third))<br>\n",
"5. int(first) + int(float(third))<br>\n",
"6. 2.0 * second\n",
" </div>\n",
"</div>\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>Every value has a type.</li>\n",
" <li>Use the built-in function <span class=\"label label-default\">type()</span> to find the type of a value.</li>\n",
" <li>Types control what operations can be done on values.</li>\n",
" <li>Strings can be added and multiplied.</li>\n",
" <li>Strings have a length (but numbers don’t).</li>\n",
" <li>Must convert numbers to strings or vice versa when operating on them.</li>\n",
" <li>Must convert numbers to strings or vice versa when operating on them.</li>\n",
" <li>Can mix integers and floats freely in operations.</li>\n",
" </ul> \n",
"</div>\n",
"</div>\n"
]
}
],
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Built-in Functions and Help"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"## Use comments to add documentation to programs."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A function may take zero or more arguments.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* We've already seen some built-in functions\n",
"* print(), len(), int(), float(), str()\n",
"* Always with parenthesis, even if empty"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Commonly-used built-in functions"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* max() , min()\n",
"* round(), will round off a floating-point number.By default, rounds to zero decimal places."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use the built-in function <span class=\"label label-default\">help</span> to get help for a function."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Every built-in function has online documentation."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Jupyter Notebook has two ways to get help.\n",
"* Place the cursor inside the parenthesis of the function, hold down shift, and press tab.\n",
"* Or type a function name with a question mark after it."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Every function returns something.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Every function call produces some result.\n",
"* If the function doesn’t have a useful result to return, it usually returns the special value None."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>Use comments to add documentation to programs.</li>\n",
" <li>A function may take zero or more arguments.</li>\n",
" <li>Commonly-used built-in functions include max, min, and round.</li>\n",
" <li>Functions may have default values for some arguments.</li>\n",
" <li>Use the built-in function help to get help for a function.</li>\n",
" <li>The Jupyter Notebook has two ways more to get help.</li>\n",
" <li>Every function returns something.</li>\n",
" </ul> \n",
"</div>\n",
"</div>"
]
}
],
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Lists"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A list stores many values in a single structure.\n",
"* Use a list to store many values together.\n",
"* Contained within square brackets [...].\n",
"* Values separated by commas ,.\n",
"* Use <span class=\"label label-default\">len</span> to find out how many values are in a list."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use an item’s index to fetch it from a list."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Lists’ values can be replaced by assigning to them."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Appending items\n",
"* Use <span class=\"label label-default\">list_name.append</span> to add items to the end of a list.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* <span class=\"label label-default\">append</span> is a method of lists.\n",
" * Like a function, but tied to a particular object.\n",
"* Use <span class=\"label label-default\">object_name.method_name</span> to call methods.\n",
"* Use <span class=\"label label-default\">help(list)</span> for a preview.\n",
"* <span class=\"label label-default\">extend</span> is similar to append, but it allows you to combine two lists. For example:"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Note that while `extend` maintains the \"flat\" structure of the list, appending a list to a list makes the result two-dimensional.\n",
"\n",
"## Use `del` to remove items from a list entirely.\n",
"\n",
"* `del list_name[index]` removes an item from a list and shortens the list.\n",
"* Not a function or a method, but a statement in the language.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print('primes before removing last item:', primes) \n",
"del primes[4] \n",
"print(\"primes after removing last item:\", primes)\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The empty list contains no values.\n",
"\n",
"* Use `[]` on its own to represent a list that doesn't contain any values.\n",
" * \"The zero of lists.\"\n",
"* Helpful as a starting point for collecting values\n",
" (which we will see in the next episode)\n",
"\n",
"## Lists may contain values of different types.\n",
"\n",
"* A single list may contain numbers, strings, and anything else."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Character strings can be indexed like lists.\n",
"\n",
"* Get single characters from a character string using indexes in square brackets.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Character strings are immutable.\n",
"\n",
"* Cannot change the characters in a string after it has been created.\n",
" * *Immutable*: can't be changed after creation.\n",
" * In contrast, lists are *mutable*: they can be modified in place.\n",
"* Python considers the string to be a single value with parts,\n",
" not a collection of values.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
" Lists and character strings are both *collections*.\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Indexing beyond the end of the collection is an error.\n",
"\n",
"* Python reports an `IndexError` if we attempt to access a value that doesn't exist.\n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": false
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Strides"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* If we write a slice as [low:high:stride], what does stride do?"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Fill in the Blanks</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"values = ____\n",
"values.____(1)\n",
"values.____(3)\n",
"values.____(5)\n",
"print('first time:', values)\n",
"values = values[____]\n",
"print('second time:', values)\n",
"\n",
"---RESULT---\n",
"first time: [1, 3, 5]\n",
"second time: [3, 5]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - How Large is a Slice?</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"If ‘low’ and ‘high’ are both non-negative integers, how long is the list values[low:high]?\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Nested Lists</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"x = [['pepper', 'zucchini', 'onion'],\n",
" ['cabbage', 'lettuce', 'garlic'],\n",
" ['apple', 'pear', 'banana']]"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![Nested_lists](images/indexing_lists_python.png)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(x)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print([x[0]])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(x[0])"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(x[0][0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>A list stores many values in a single structure..</li>\n",
" <li>Use an item’s index to fetch it from a list.</li>\n",
" <li>Lists’ values can be replaced by assigning to them. </li>\n",
" <li>Appending items to a list lengthens it.</li>\n",
" <li>Use <span class=\"label label-default\">del</span> to remove items from a list entirely.</li>\n",
" <li>The empty list contains no values.</li>\n",
" <li>Lists may contain values of different types.</li>\n",
" <li>Character strings can be indexed like lists.</li>\n",
"<li>Character strings are <span class=\"label label-default\">immutable</span>.</li>\n",
"<li>Indexing beyond the end of the collection is an error.</li>\n",
" </ul> \n",
"</div>\n",
"</div>\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
}
],
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# For loops"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A for loop run commands once for each value in a collection.\n",
"* Doing calculations on the values in a list one by one is painful, imaging with 1000 items!!! UNFEASIBLE!!! :(\n",
"* A for loop tells Python to execute some statements once for each value in a list, a character string, or some other collection.\n",
"* “for each thing in this group, do these operations”\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![For loop](images/loops_image.png)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A for loop is made up of a collection, a loop variable, and a body."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* The loop variable, number, is what changes for each iteration of the loop and can be called anything.\n",
"\n",
"* The collection, [2, 3, 5], is what the loop is being run on.\n",
"* The body, print(number), specifies what to do for each value in the collection and can contain many statements.\n",
"* The first line of the for loop must end with a <span class=\"label label-default\">colon</span>, and the body must be <span class=\"label label-default\">indented</span>.\n",
"* The colon at the end of the first line signals the start of a block of statements.\n",
"* Python uses indentation (typically 4 spaces) rather than {} or begin/end to show nesting.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use <span class=\"label label-default\">range</span> to iterate over a sequence of numbers.\n",
"* The built-in function range produces a sequence of numbers.\n",
"* range(N) is the numbers 0..N-1, the length N"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## The Accumulator pattern turns many values into one.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* A common pattern in programs is to:\n",
" * Initialize an accumulator variable to zero, the empty string, or the empty list.\n",
" * Update the variable with values from a collection."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Squared and cubed prime numbers</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" We have a list of prime numbers, and we want to calculate the squared and cubed numbers for every prime number.\n",
" <br>\n",
"\n",
" </div>\n",
"</div>\n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Reverse a string</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" Fill in the blanks in the program below so that it prints “nit” (the reverse of the original character string “tin”).<br><br>\n",
" </div>\n",
"</div>\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"original = \"theoretical physics\"\n",
"result = ____\n",
"for char in original:\n",
" result = ____\n",
"print(result)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Practice Accumulating</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" Fill in the blanks in each of the programs below to produce the indicated result.<br><br>\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"# Total length of the strings in the list: [\"red\", \"green\", \"blue\"] => 12\n",
"total = 0\n",
"for word in [\"red\", \"green\", \"blue\"]:\n",
" ____ = ____ + len(word)\n",
"print(total)"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"# List of word lengths: [\"red\", \"green\", \"blue\"] => [3, 5, 4]\n",
"lengths = ____\n",
"for word in [\"red\", \"green\", \"blue\"]:\n",
" lengths.____(____)\n",
"print(lengths)"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"# Concatenate all words: [\"red\", \"green\", \"blue\"] => \"redgreenblue\"\n",
"words = [\"red\", \"green\", \"blue\"]\n",
"result = ____\n",
"for ____ in ____:\n",
" ____\n",
"print(result)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"##Solution 1\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"##Solution 2\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#solution 3\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>A <span class=\"label label-default\">for</span> loop runs commands once for each value in a collection.</li>\n",
"<li>The first line of the <span class=\"label label-default\">for</span> loop must end with a colon, and the body must be indented.</li>\n",
"<li><span class=\"label label-default\">Indentation</span> is always meaningful in Python.</li>\n",
"<li>A for loop is made up of a collection, a loop variable, and a body.</li>\n",
"<li>Loop variables can be called anything (but it is strongly advised to have a meaningful name to the looping variable).</li>\n",
"<li>The body of a loop can contain many statements.</li>\n",
"<li>Use <span class=\"label label-default\">range</span> to iterate over a sequence of numbers.</li>\n",
"<li>The Accumulator pattern turns many values into one.</li>\n",
" </ul> \n",
"</div>\n",
"</div>\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
}
],
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Writing Functions\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Break programs down into functions to make them easier to understand."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Functions are reusable, self-contained pieces of code that are called with a single command. \n",
"* They can be designed to accept arguments as input and return values, but they don’t need to do either. \n",
"* Variables declared inside functions only exist while the function is running and if a variable within the function (a local variable) has the same name as a variable somewhere else in the code, the local variable hides but doesn’t overwrite the other.\n",
"* Every method used in Python (for example, print) is a function"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Define a function using def with a name, parameters, a colon and a block of indented code."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![jupyter](images/python-function.svg)"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"#http://www.rapidtables.com/convert/temperature/fahrenheit-to-kelvin.htm"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Every function returns something.\n",
"* return keyword is not compulsory but a function always returns sth\n",
"* A function that doesn’t explicitly <span class=\"label label-default\">return</span> a value automatically returns <span class=\"label label-default\">None</span>."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Different order and default values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Arguments can be given default values with an equal sign in the function declaration. \n",
"* Any arguments in the function without default values is a required argument and MUST come before the argument with default values (which are optional in the function call)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Identifying Syntax Errors</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"1. Read the code below and try to identify what the errors are without running it.<br>\n",
"2. Run the code and read the error message. Is it a SyntaxError or an IndentationError?<br>\n",
"3. Fix the error.<br>\n",
"4. Repeat steps 2 and 3 until you have fixed all the errors.<br>\n",
"def another_function<br>\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"def another_function\n",
" print(\"Syntax errors are annoying.\")\n",
" print(\"But at least python tells us about them!\")\n",
" print(\"So they are usually not too hard to fix.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Simulating a dynamical system</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"In mathematics, a <a href=\"https://en.wikipedia.org/wiki/Dynamical_system\">dynamical system</a> is a system in which a function describes the time dependence of a point in a geometrical space. Canonical example of a dynamical system is a system called the <a href=\"https://en.wikipedia.org/wiki/Logistic_map\">logistic map</a>.<br><br>\n",
"\n",
"1. Define a function called **logistic_map** that takes two inputs: **X**, representing the state of the system at time t, and a parameter **r**. This function should return a value representing the state of the system at time **t+1**.<br>\n",
"2. Using a for loop, iterate the logistic_map function defined in part 1 starting from an **initial condition** of 0.5 for **T=10**, **100**, and **1000** periods. Store the intermediate results in a list so that after the for loop terminates you have accumulated a sequence of values representing the state of the logistic map at time t=0,1,…,T.<br>\n",
"3. Encapsulate the logic of your for loop into a function called **iterate** that takes the **initial condition** as its first input, the parameter **T** as its second input and the parameter **r** as its third input. The function should return the list of values representing the state of the logistic map at time t=0,1,…,T.<br><br>\n",
" </div>\n",
"</div>\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#Solucion"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"\n",
" \n",
" "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>Break programs down into functions to make them easier to understand.</li>\n",
" <li>Functions are reusable</li>\n",
" <li>Define a function using <span class=\"label label-default\">def</span> with a name, parameters, and a block of code.</li>\n",
" <li>Every function returns something.</li>\n",
"<li>Arguments may have default values.</li>\n",
"<li>Any argument without default values is a required argument and MUST come before the argument with default values.</li>\n",
" </ul> \n",
"</div>\n",
"</div>"
]
}
],
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Conditionals"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"![jupyter](images/python-flowchart-conditional.png)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* An <span class=\"label label-default\">if</span> statement (more properly called a <span class=\"label label-default\">conditional</span> statement) controls whether some block of code is executed or not.\n",
"* Structure is similar to a for statement:\n",
" * First line opens with if and ends with a colon\n",
" * Body containing one or more statements is indented (usually by 4 spaces)\n",
"* Use <span class=\"label label-default\">else</span> to execute a block of code when an if condition is not true.\n",
"* Use <span class=\"label label-default\">elif</span> to specify additional tests and provide several alternative choices.\n",
" * Use elif (short for “else if”) and a condition to specify these.\n",
" * Always associated with an if.\n",
" * Must come before the else (which is the “catch all”)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"# Conditionals are often used inside loops.\n",
"* Conditions are tested once, in order, that's why they are ften used inside loops.\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Combining conditions: using <span class=\"label label-default\">and</span>, <span class=\"label label-default\">or</span> and parenthesis"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - What Is Truth?</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"<span class=\"label label-default\">True</span> and <span class=\"label label-default\">False</span> are special words in Python called <span class=\"label label-default\">booleans</span> which represent true and false statements. However, they aren’t the only values in Python that are true and false. In fact, any value can be used in an if or elif. After reading and running the code below, explain what the rule is for which values are considered true and which are considered false.<br>\n",
"\n",
" </div>\n",
"</div>\n"
]
},
{
"cell_type": "raw",
"metadata": {
"scrolled": true
},
"source": [
"if '':\n",
" print('empty string is true')\n",
"if 'word':\n",
" print('word is true')\n",
"if []:\n",
" print('empty list is true')\n",
"if [1, 2, 3]:\n",
" print('non-empty list is true')\n",
"if 0:\n",
" print('zero is true')\n",
"if 1:\n",
" print('one is true')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Counting Vowels</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"1. Write a loop that counts the number of vowels in a character string.<br>\n",
"2. Test it on a few individual words and full sentences.<br>\n",
"3. Once you are done, compare your solution to your neighbor’s. <br>\n",
"\n",
" </div>\n",
"</div>\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#Solution\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Key Points</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" <ul>\n",
" <li>Use <span class=\"label label-default\">if</span> condition to start a conditional statement, <span class=\"label label-default\">elif</span> condition to provide additional tests, and <span class=\"label label-default\">else</span> to provide a default.</li>\n",
" <li>The bodies of the branches of conditional statements must be indented.</li>\n",
" <li>Conditionals are often used inside loops.</li>\n",
" <li>Use <span class=\"label label-default\">==</span> to test for equality.</li>\n",
" <li>X and Y is only true if both X and Y are true.</li>\n",
" <li>X or Y is true if either X or Y, or both, are true.</li>\n",
" <li>Zero, the empty string, and the empty list are considered false; all other numbers, strings, and lists are considered true.</li>\n",
" </ul> \n",
"</div>\n",
"</div>\n",
"\n"
]
}
],
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Scripts in Python"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* The Jupyter Notebook and other interactive tools are great for prototyping code and exploring data, but sooner or later we will want to use our program in a pipeline or run it in a shell script to process thousands of data and these programms won't need our interation."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-danger\" role=\"alert\">In this lesson we are switching from typing commands in a Python interpreter to typing commands in a shell terminal window (such as bash). When you see a $ in front of a command that tells you to run that command in the shell rather than the Python interpreter.</div> "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Command-Line Programs\n",
"* Using the text editor of your choice, in our case nano editor, save the following in a text file called sys_version.py:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Libraries\n",
"* Most of the power of a programming language is in its libraries.\n",
"* A library is a collection of files (called modules) that contains functions for use by other programs.\n",
"* A library is a collection of modules, but the terms are often used interchangeably, especially since many libraries only consist of a single module, so don’t worry if you mix them.\n",
"* Use <span class=\"label label-default\">import</span> to load a library module into a program’s memory.\n",
"* Then refer to things from the module as <span class=\"label label-default\">module_name.thing_name</span>.\n",
"* Python uses <span class=\"label label-default\">.</span> to mean “part of”.\n",
"* Use help to learn about the contents of a library module."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Print Python version "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"$ nano sys_version.py</div>"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"<div class=\"alert alert-info\" role=\"alert\">\n",
"import sys<br>\n",
"print('version is', sys.version)</div> \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"$ python sys_version.py</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Print argument list"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"$ nano argv_list.py</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-info\" role=\"alert\">\n",
"import sys<br>\n",
"print('sys.argv is', sys.argv)</div>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"$ python argv_list.py</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"$ python argv_list.py this is a list of arguments</div>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"$ nano temperature.py</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"\n",
"import sys\n",
"\n",
"def main():\n",
" #script = sys.argv[0]\n",
" temp = sys.argv[1]\n",
" print(temp)\n",
" \n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"\n",
"import sys\n",
"\n",
"def main():\n",
" #script = sys.argv[0]\n",
" temp = sys.argv[1]\n",
" print(temp)\n",
"\n",
"main()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"$ conversion.py</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"def fahr_to_kelvin(temp):\n",
" return ((temp - 32)* (5/9) + 273.15)\n",
"\n",
"print('Fahrenheit to Kelvin Conversion ',sys.argv[1],'-->',fahr_to_kelvin(56))\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Counting the number of arguments"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"$ conversion.py</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"#Count the number of arguments\n",
"import sys\n",
"def fahr_to_kelvin(temp):\n",
" return ((temp - 32) * (5/9)) + 273.15\n",
"\n",
"if ((len(sys.argv[1:])<1) or (len(sys.argv[1:])>=2)):\n",
" print(\"Error: 1 argument expected\")\n",
"else:\n",
" print('Fahrenheit to kelvin conversion',sys.argv[1], '-->',fahr_to_kelvin(int(sys.argv[1])))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### List of arguments"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\">\n",
"$ prime_numbers.py</div>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"import sys\n",
"\n",
"def prime_numbers(numbers):\n",
" for n in numbers:\n",
" n=int(n)\n",
" \n",
" if n<0: # meets first condition?\n",
"\n",
" # if a IS less than zero\n",
" print(n, 'is a negative number')\n",
"\n",
" elif n>0: # did not meet first condition. meets second condition?\n",
"\n",
" # if a ISN'T less than zero and IS more than zero\n",
" print(n, ' is a positive number')\n",
"\n",
" else: # met neither condition\n",
"\n",
" # if a ISN'T less than zero and ISN'T more than zero\n",
" print(n, ' must be zero!')\n",
" \n",
"\n",
"prime_numbers(sys.argv[1:])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Dynamic system"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"def logistic_map(X, r):\n",
" return r * X * (1 - X)\n",
"\n",
"\n",
"\n",
" \n",
"def iterate(initial_condition, T, r):\n",
" trajectory = [initial_condition]\n",
" for t in range(1, T):\n",
" trajectory.append(logistic_map(trajectory[t-1], r))\n",
" return trajectory\n",
"\n",
"\n",
"initial_condition = 0.5\n",
"T = 10\n",
"r = 1.0 # r=4, sistema caotico\n",
"print(iterate(initial_condition,T,r))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-primary\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">RECAP</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" \n",
"</div>\n",
"</div>\n"
]
}
],
"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.1"
}
},
"nbformat": 4,
"nbformat_minor": 2
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment