{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## For loops\n", "\n", "In several problems we solved in class, there was the need to repeat the same steps for a number of times. Instead of writing the same steps over and over again, we used the \"repeat\" word. One of the ways of translating this repetition to python is using `for` loops.\n", "\n", "The syntax for `for` loops is:\n", "\n", "```\n", "for i in :\n", " \n", "```\n", "\n", "Let's break this down.\n", "\n", "### Sequence of things\n", "\n", "The `` could be a sequence of integers, floats, booleans, etc. We start by looking at sequences of integers. We will do this by using the python command `range`. There are three ways to use that command:\n", "\n", "* `range(stop)` will generate the sequence of numbers from 0 to **stop-1**. So `range(6)` will generate the sequence 0,1,2,3,4,5.\n", "\n", "* `range(start,stop)` will generate the sequence of numbers from `start` to **`stop-1`**. So `range(4,10)` will generate the sequence 4,5,6,7,8,9.\n", "\n", "* `range(start,stop,step)` will generate the sequence of numbers beginning at `start`, with increments of `step`, until reaching `stop-1`. So `range(4,10,2)` will generate the sequence 4,6,8.\n", " - Note that `range(start,stop)` is the same as `range(start,stop,1)`.\n", " - Note that steps may be negative.\n", " \n", "The number of elements in your sequence determines how many times the loop repeats itself, or, more technically, how many times it **iterates**. Each loop repetition is called an **iteration**.\n", "\n", "If you are not sure which sequence of numbers a range would generate, you can check it by typing the range command you want to use, wrapped around with a `list` function. We will see more about lists later in the course." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[-4, -3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(range(-4,10))" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "[10, 9, 8, 7, 6, 5, 4]" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list(range(10,3,-1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Steps\n", "\n", "The steps that will be repeated in a loop need to be indented to the right, since this is inside the scope of the loop only. If you need to write more code after the loop is done, simply indent it back to align with the `for` keyword.\n", "\n", "Most of the times, you will want to repeat steps for different values of a variable. That is why the *loop variable* `i` is available for you to use in your ``. Each time the loop is repeated, `i` takes the next value in the sequence of things you determined.\n", "\n", "For example, take the loop:\n", "\n", "```\n", "for i in range(5):\n", " \n", "```\n", "\n", "The steps will be repeated 5 times (5 iterations), since the sequence is 0,1,2,3,4. \n", "* On the first iteration, `i` has the value 0. \n", "* On the second iteration, `i` has the value 1.\n", "* On the third iteration, `i` has the value 2.\n", "* On the fourth iteration, `i` has the value 3.\n", "* On the fifth iteration, `i` has the value 4.\n", "\n", "So, if we write something (useless) like this:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "collapsed": true }, "outputs": [], "source": [ "x = 0\n", "for i in range(100):\n", " x = i" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Once the loop is over, what will be the value of `x`?\n", "\n", "### Loop variable\n", "\n", "Every loop has what we call a **loop variable**. In the examples above, we have used `i` as this variable's name, but it could really be anything you want. For example:" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": true }, "outputs": [], "source": [ "for even in range(0,100,2):\n", " ..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "**Careful:** Do not modify variables that are used in the loop command. This can only make things more complicated." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 1\n", "\n", "Implement the funcion `sumOdds(m, n)` that returns the sum of all odd numbers between m and n, not inclusive. So `sumOdds(-5,6)` should return 5 (-3-1+1+3+5)." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [], "source": [ "def sumOdds(m,n):\n", " sum = 0\n", " for i in range(m+1,n):\n", " if i % 2 != 0:\n", " sum = sum + i\n", " return sum\n", "\n", "sumOdds(1,3)\n", "\n", "# Another option\n", "def sumOdds(m,n):\n", " sum = 0\n", " \n", " if m % 2 == 0:\n", " m = m + 1\n", " else:\n", " m = m + 2\n", " \n", " for odd in range(m,n,2):\n", " sum = sum + odd\n", " return sum" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Follow up to exercise 1\n", "\n", "Draw the iteration table for the code above." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 2\n", "\n", "The *alternating sum* of a sequence $(a_1, a_2, ... a_n)$ is defined as: $a_1 - a_2 + a_3 - ... \\pm a_n$.\n", "\n", "Implement the function `alternatingSum(n)` that returns the alternating sum of all numbers between 1 and n, inclusive." ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [], "source": [ "def alternatingSum(n):\n", " return 42" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Follow up to exercise 2:\n", "\n", "Try out this function for a few different numbers. Can you come up with a closed formula (one that does not use loops)?" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": true }, "outputs": [], "source": [ "def alternatingSum(n):\n", " return 42" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 3\n", "\n", "In mathematics, a perfect number is an integer for which the sum of all its own positive divisors (excluding itself) is equal to the number itself. For example the number 6 is perfect, because 1+2+3 is equal to 6. \n", "\n", "Implement the function `isPerfect(n)` that returns `True` if `n` is a perfect number, or `False` otherwise." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [], "source": [ "def isPerfect(n):\n", " return True\n", " \n", "# Perfect numbers to test with: 6, 28, 496" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Exercise 4\n", "\n", "Given some positive integer `n`, we can write `n*2` lines following a certain pattern. For example, if `n` is 5, the 10 lines are:\n", "```\n", "1 1 1\n", "1 2 2\n", "2 4 8\n", "2 5 9\n", "3 9 27\n", "3 10 28\n", "4 16 64\n", "4 17 65\n", "5 25 125\n", "5 26 126\n", "```\n", "\n", "Find out what is the pattern for generating the lines, and implement a function `patternSum(n)` that takes a positive integer `n` and returns the sum of all numbers in the `n*2` lines generated using the pattern above." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [], "source": [ "def patternSum(n):\n", " return 42" ] } ], "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.8.3" } }, "nbformat": 4, "nbformat_minor": 2 }