\n", + "
\n", + "

### Exercise - Types

\n", + "
\n", + "
\n", + " What type of value is 3.4?
\n", + " What type of value is 3.25 + 4?
\n", + " What type of value is 4/2?
\n", + "
\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "
\n", + "

### Exercise - Division Types

\n", + "
\n", + "
\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.
\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", + "
\n", + "
\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", + "
\n", + "
\n", + "

### Exercise - Arithmetic with Different Types

\n", + "
\n", + "
\n", + " Which of the following will print 2.0? Note: there may be more than one right answer.
\n", + " first = 1.0
\n", + "second = \"1\"
\n", + "third = \"1.1\"
\n", + "
\n", + "
\n", + "1. first + float(second)
\n", + "2. float(second) + float(third)
\n", + "3. first + int(third)
\n", + "4. first + int(float(third))
\n", + "5. int(first) + int(float(third))
\n", + "6. 2.0 * second\n", + "
\n", + "
\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "
\n", + "

### Key Points

\n", + "
\n", + "
\n", + "
\n", + "
• Every value has a type.
• \n", + "
• Use the built-in function type() to find the type of a value.
• \n", + "
• Types control what operations can be done on values.
• \n", + "
• Strings can be added and multiplied.
• \n", + "
• Strings have a length (but numbers don’t).
• \n", + "
• Must convert numbers to strings or vice versa when operating on them.
• \n", + "
• Must convert numbers to strings or vice versa when operating on them.
• \n", + "
• Can mix integers and floats freely in operations.
• \n", + "
\n", + "
\n", + "
\n", + "
\n", + "

### Key Points

\n", + "
\n", + "
\n", + "
\n", + "
• \n", + "
• A function may take zero or more arguments.
• \n", + "
• Commonly-used built-in functions include max, min, and round.
• \n", + "
• Functions may have default values for some arguments.
• \n", + "
• Use the built-in function help to get help for a function.
• \n", + "
• The Jupyter Notebook has two ways more to get help.
• \n", + "
• Every function returns something.
• \n", + "
\n", + "
\n", + "
\n", + " Lists and character strings are both *collections*.\n", + "
" + ] + }, + { + "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": [ + "
\n", + "
\n", + "

### Exercise - Fill in the Blanks

\n", + "
\n", + "
\n", + "\n", + "
\n", + "
" + ] + }, + { + "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": [ + "
\n", + "
\n", + "

### Exercise - How Large is a Slice?

\n", + "
\n", + "
\n", + "If ‘low’ and ‘high’ are both non-negative integers, how long is the list values[low:high]?\n", + "
\n", + "
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "
\n", + "

### Exercise - Nested Lists

\n", + "
\n", + "
\n", + "\n", + "
\n", + "
" + ] + }, + { + "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": [ + "
\n", + "
\n", + "

### Key Points

\n", + "
\n", + "
\n", + "
\n", + "
• A list stores many values in a single structure..
• \n", + "
• Use an item’s index to fetch it from a list.
• \n", + "
• Lists’ values can be replaced by assigning to them.
• \n", + "
• Appending items to a list lengthens it.
• \n", + "
• Use del to remove items from a list entirely.
• \n", + "
• The empty list contains no values.
• \n", + "
• Lists may contain values of different types.
• \n", + "
• Character strings can be indexed like lists.
• \n", + "
• Character strings are immutable.
• \n", + "
• Indexing beyond the end of the collection is an error.
• \n", + "
\n", + "
\n", + "
\n", + "
\n", + "

### Exercise - Squared and cubed prime numbers

\n", + "
\n", + "
\n", + " We have a list of prime numbers, and we want to calculate the squared and cubed numbers for every prime number.\n", + "
\n", + "\n", + "
\n", + "
\n", + " \n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "
\n", + "

### Exercise - Reverse a string

\n", + "
\n", + "
\n", + " Fill in the blanks in the program below so that it prints “nit” (the reverse of the original character string “tin”).

\n", + "
\n", + "
\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": [ + "
\n", + "
\n", + "

### Exercise - Practice Accumulating

\n", + "
\n", + "
\n", + " Fill in the blanks in each of the programs below to produce the indicated result.

\n", + "
\n", + "
" + ] + }, + { + "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": [ + "
\n", + "
\n", + "

### Key Points

\n", + "
\n", + "
\n", + "
\n", + "
• A for loop runs commands once for each value in a collection.
• \n", + "
• The first line of the for loop must end with a colon, and the body must be indented.
• \n", + "
• Indentation is always meaningful in Python.
• \n", + "
• A for loop is made up of a collection, a loop variable, and a body.
• \n", + "
• Loop variables can be called anything (but it is strongly advised to have a meaningful name to the looping variable).
• \n", + "
• The body of a loop can contain many statements.
• \n", + "
• Use range to iterate over a sequence of numbers.
• \n", + "
• The Accumulator pattern turns many values into one.
• \n", + "
\n", + "
\n", + "
\n", + "
\n", + "

### Exercise - Identifying Syntax Errors

\n", + "
\n", + "
\n", + "1. Read the code below and try to identify what the errors are without running it.
\n", + "2. Run the code and read the error message. Is it a SyntaxError or an IndentationError?
\n", + "3. Fix the error.
\n", + "4. Repeat steps 2 and 3 until you have fixed all the errors.
\n", + "def another_function
\n", + "
\n", + "
" + ] + }, + { + "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": [ + "
\n", + "
\n", + "

### Exercise - Simulating a dynamical system

\n", + "
\n", + "
\n", + "In mathematics, a dynamical system 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 logistic map.

\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**.
\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.
\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.

\n", + "
\n", + "
\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": [ + "
\n", + "
\n", + "

### Key Points

\n", + "
\n", + "
\n", + "
\n", + "
• Break programs down into functions to make them easier to understand.
• \n", + "
• Functions are reusable
• \n", + "
• Define a function using def with a name, parameters, and a block of code.
• \n", + "
• Every function returns something.
• \n", + "
• Arguments may have default values.
• \n", + "
• Any argument without default values is a required argument and MUST come before the argument with default values.
• \n", + "
\n", + "
\n", + "
\n", + "
\n", + "

### Exercise - What Is Truth?

\n", + "
\n", + "
\n", + "True and False are special words in Python called booleans 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.
\n", + "\n", + "
\n", + "
\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": [ + "
\n", + "
\n", + "

### Exercise - Counting Vowels

\n", + "
\n", + "
\n", + "1. Write a loop that counts the number of vowels in a character string.
\n", + "2. Test it on a few individual words and full sentences.
\n", + "3. Once you are done, compare your solution to your neighbor’s.
\n", + "\n", + "
\n", + "
\n", + "\n", + "\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "#Solution\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "
\n", + "

### Key Points

\n", + "
\n", + "
\n", + "
\n", + "
• Use if condition to start a conditional statement, elif condition to provide additional tests, and else to provide a default.
• \n", + "
• The bodies of the branches of conditional statements must be indented.
• \n", + "
• Conditionals are often used inside loops.
• \n", + "
• Use == to test for equality.
• \n", + "
• X and Y is only true if both X and Y are true.
• \n", + "
• X or Y is true if either X or Y, or both, are true.
• \n", + "
• Zero, the empty string, and the empty list are considered false; all other numbers, strings, and lists are considered true.
• \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 +} diff --git a/09_scripts_acdf.ipynb b/09_scripts_acdf.ipynb new file mode 100644 index 0000000000000000000000000000000000000000..eb3e703f7bf14b53ab07681283b6117906cf0c76 --- /dev/null +++ b/09_scripts_acdf.ipynb @@ -0,0 +1,332 @@ +{ + "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": [ + "
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.
" + ] + }, + { + "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 import to load a library module into a program’s memory.\n", + "* Then refer to things from the module as module_name.thing_name.\n", + "* Python uses . 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": [ + "
\n", + "\$ nano sys_version.py
" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "
\n", + "import sys
\n", + "print('version is', sys.version)
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\$ python sys_version.py
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Print argument list" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\$ nano argv_list.py
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "import sys
\n", + "print('sys.argv is', sys.argv)
\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\$ python argv_list.py
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\$ python argv_list.py this is a list of arguments
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "
\n", + "\$ nano temperature.py
" + ] + }, + { + "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": [ + "
\n", + "\$ conversion.py
" + ] + }, + { + "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": [ + "
\n", + "\$ conversion.py
" + ] + }, + { + "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": [ + "
\n", + "\$ prime_numbers.py
" + ] + }, + { + "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": [ + "
\n", + "
\n", + "

### RECAP

\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 +}