Commit 5ca4d9f2 authored by Arucas Chacon's avatar Arucas Chacon

Completed notebooks

parent 2820c217
This diff is collapsed.
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Variables and assignment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use variables to store values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Variables are names for values.\n",
"* In Python the = symbol assigns the value on the right to the name on the left.\n",
"* The variable is created when a value is assigned to it.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"weight_kg = 55"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Variable names:\n",
" * can’t start with a digit\n",
" * can’t contain spaces, quotation marks, or other punctuation\n",
" * may contain an underscore (typically used to separate words in long variable names)\n",
"* Underscores at the start like __alistairs_real_age have a special meaning so we won’t do that until we understand the convention."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use print to display values"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Python has a built-in function called <span class=\"label label-default\">print</span> that prints things as text.\n",
"* To add a string to the printout, wrap the string in single quotations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(weight_kg)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print('weight in kg:', weight_kg)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Variables must be created before they are used."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(last_name)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"alert alert-success\" role=\"alert\">\n",
"Variables defined in one cell exist in all other cells once executed, so the relative location of cells in the notebook does\n",
"not matter (i.e., cells lower down can still affect those above). Remember: Notebook cells are just a way to organize a program: as far as Python is concerned, all of the source code is one long set of instructions.\n",
"</div>\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Variables can be used in calculations."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print('weight in pounds:', 2.2 * weight_kg)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"weight_lb = 2.2 * weight_kg\n",
"print('weight in kilograms:', weight_kg, 'and in pounds:', weight_lb)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use an index to get a single character from a string.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Strings are lists of characters.\n",
"* <span class=\"label label-success\">Indices start numbered from 0</span>.\n",
"* Use the position’s index in square brackets to get the character at that position."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"workshop_name = 'Software carpentry'\n",
"print(workshop_name)\n",
"print('the first character is',workshop_name[0])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use a slice to get a substring.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* A part of a string is called a substring. A substring can be as short as a single character.\n",
"* We take a slice of a string by using <span class=\"label label-default\">[start:stop]</span>, where start is replaced with the index of the first element we want and stop is replaced with the index of the element just after the last element we want.\n",
"* Mathematically, you might say that a slice selects [start:stop), from start to stop-1\n",
"* Taking a slice does not change the contents of the original string. Instead, the slice is a copy of part of the original string.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(workshop_name[0:6])\n",
"print(workshop_name[2:10])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use the built-in function len to find the length of a string.\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(len(workshop_name))\n",
"print(len(workshop_name[1:6]))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python is case-sensitive."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* Python thinks that upper- and lower-case letters are different, so <span class=\"label label-default\">Name</span> and <span class=\"label label-default\">name</span> are different variables.\n",
"* There are conventions for using upper-case letters at the start of variable names so we will use lower-case letters for now."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Use meaningful variable names."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"qwert = 55\n",
"poiu = \"Arucas'\"\n",
"print (poiu, 'weight is', qwert)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Swapping Values</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
" Fill the table showing the values of the variables in this program after each statement is executed.\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"# Command # Value of x # Value of y # Value of swap #\n",
"x = 1.0 # # # #\n",
"y = 3.0 # # # #\n",
"swap = x # # # #\n",
"x = y # # # #\n",
"y = swap # # # #"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Predicting Values</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"What is the final value of <span class=\"label label-default\">position</span> in the program below? (Try to predict the value without running the program, then check your prediction.)\n",
"\n",
" </div>\n",
"</div>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"initial = \"left\"\n",
"position = initial\n",
"initial = \"right\""
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<div class=\"panel panel-warning\">\n",
" <div class=\"panel-heading\">\n",
" <h3 class=\"panel-title\">Exercise - Choosing a name</h3>\n",
" </div>\n",
" <div class=\"panel-body\">\n",
"Which is a better variable name, <span class=\"label label-default\">m</span>, <span class=\"label label-default\">min</span>, or <span class=\"label label-default\">minutes</span>? Why? Hint: think about which code you would rather inherit from someone who is leaving the lab:\n",
"\n",
" </div>\n",
"</div>\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"ts = m * 60 + s\n",
"tot_sec = min * 60 + sec\n",
"total_seconds = minutes * 60 + seconds"
]
},
{
"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 variables to store values.</li>\n",
" <li>Use print to display values.</li>\n",
" <li>Variables persist between cells.</li>\n",
" <li>Variables must be created before they are used.</li>\n",
" <li>Variables can be used in calculations.</li>\n",
" <li>Use an index to get a single character from a string.</li>\n",
" <li>Use a slice to get a substring.</li>\n",
" <li>Use the built-in function len to find the length of a string.</li>\n",
" <li>Python is case-sensitive.</li>\n",
" <li>Use meaningful variable names.</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": [
"# 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": [
"age = 32\n",
"pi = 3.14\n",
"first_name = 'Arucas'\n",
"print(age)\n",
"print(pi)\n",
"print(first_name)"
]
},
{
"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": [
"print(type(age))\n",
"print(type(pi))\n",
"print(type(first_name))"
]
},
{
"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": [
"print(5-2)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print('hello' - 'h')"
]
},
{
"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": [
"full_name = 'Arucas' + ' ' + 'Chacon'\n",
"print(full_name)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"separator = '=' * 10\n",
"print(separator)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Strings have a length (but numbers don’t)."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(len(full_name))"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(len(pi))"
]
},
{
"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": [
"print(1 + '2')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true,
"scrolled": true
},
"outputs": [],
"source": [
"print(1 + int('2'))\n",
"print(str(1) + '2')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"print(\"string to float:\", float(\"3.4\"))\n",
"print(\"float to int:\", int(3.9))\n",
"print(\"int to float:\", float(3))"
]
},
{
"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": [
"print('half is', 1 / 2.0)\n",
"print('three squared is', 3.0 ** 2)\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": [
"val = 1.0+2.0j\n",
"print(val.real)\n",
"print(val.imag)\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": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"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": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"first = 1.0\n",
"second = \"1\"\n",
"third = \"1.1\"\n",
"\n",
"first + float(second)\n",
"float(second) + float(third)\n",
"#first + int(third)\n",
"first + int(float(third))\n",
"int(first) + int(float(third))\n",
"2.0 * second"
]
},
{
"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": [
"# This is a comment"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## A function may take zero or more arguments.\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"* We've alreadys een 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": [
"max(1,100,2000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"min(1,100,2000)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"round(3.712)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"round(2.5)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"round(3.712, 1)"
]
},
{
"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": [
"help(round)"
]
},
{
"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": [
"round()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"round?"
]
},
{
"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": [
"result = print('example')\n",
"print('result of print is', result)"
]
},
{
"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
}
This diff is collapsed.
{
"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": [
"word = 'oxigen'\n",
"for char in word:\n",
" print(char)"
]
},
{
"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": [
"for number in [2,3,5]:\n",
" print(number)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"for number in [2,3,5]:\n",
"print(number)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"first_name=\"Jonh\"\n",
" last_name=\"Smith\""
]
},
{
"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": [
"for number in range(3):\n",
" print(number)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"for number in range(1,10):\n",
" print(number, end= \" \")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"for number in range(1,10,2):\n",
" print(number)"
]
},
{
"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": [
"# Sum the first 10 integers.\n",
"total = 0\n",
"for number in range(10):\n",
" total = total + (number + 1)\n",
" #print(total)\n",
"print(total)"
]
},
{
"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": "raw",
"metadata": {},
"source": [
"#Solution\n",
"primes = [2, 3, 5]\n",
"for p in primes:\n",
" squared = p ** 2\n",
" cubed = p ** 3\n",
" print(p, squared, cubed)"
]
},
{
"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": [
"##Solution\n",
"original = \"theoretical physics\"\n",
"result = \"\"\n",
"for char in original:\n",
" result = char + result\n",
"print(result)"
]
},
{
"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\n",
"total = 0\n",
"for word in [\"red\", \"green\", \"blue\"]:\n",
" total = total + len(word)\n",
"print(total)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"##Solution\n",
"lengths = []\n",
"for word in [\"red\", \"green\", \"blue\"]:\n",
" lengths.append(len(word))\n",
"print(lengths)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#solution\n",
"words = [\"red\", \"green\", \"blue\"]\n",
"result = \"\"\n",
"for word in words:\n",
" result = result + word\n",
"print(result)"
]
},
{
"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
}
This diff is collapsed.
{
"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": [
"num = 37\n",
"if num > 100:\n",
" print('greater')\n",
"else:\n",
" print('not greater')\n",
"print('done')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
" a = 0\n",
"\n",
" if a<0: # meets first condition?\n",
"\n",
" # if a IS less than zero\n",
" print('a is a negative number')\n",
"\n",
" elif a>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('a 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('a must be zero!')"
]
},
{
"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": [
"numbers = [2, -1, 0, 10,-15,20,30]\n",
"for n in numbers:\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!')"
]
},
{
"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": [
"# Imaging that you need to meet two conditions\n",
"if (1 > 0) and (-1 > 0):\n",
" print('both parts are true')\n",
"else:\n",
" print('at least one part is false')\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"if (1 > 0) and (0 == 0):\n",
" print('both parts are true')\n",
"else:\n",
" print('at least one part is false')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"if (1 < 0) or (-1 < 0):\n",
" print('at least one test is true')\n",
"else:\n",
" print('both parts are false')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"if (1 < 0) or (10 < 0):\n",
" print('at least one test is true')\n",
"else:\n",
" print('both parts are false')"
]
},
{
"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",
"vowels = 'aeiouAEIOU'\n",
"sentence = 'We are going to count the number of vowels.'\n",
"count = 0\n",
"for char in sentence:\n",
" if char in vowels:\n",
" count += 1\n",
" \n",
"print(\"The number of vowels in this string is \" + str(count))"
]
},
{
"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
}
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