{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
" \n",
"
"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# Python - Loops and Iteration\n",
"\n",
"In this notebook, we will be introducing loops and iteration. They are commonly used tools in programming as they allow us to perform repetitive tasks.\n",
"\n",
"To run a code cell, select the cell you wish to run, then either:\n",
"1. Click the `▶Run` button at the top of the page, or\n",
"2. Hit shift+enter.\n",
"\n",
"#### Table of Contents:\n",
"[While loops](#While_Loops)
\n",
"[For Loops](#For_Loops)
\n",
"[Range Function](#Range_Function)
\n",
"[Range function applied to sequences](#Range_Function_on_sequence)
\n",
"[Break Statements](#Break_Statements)
\n",
"[Incrementing and Decrementing](#Increment_Decrement)
\n",
"[Infinite Loops](#Infinite_Loops)
\n",
"[Loops With If/Else statements](#Loops_with_conditions)
\n",
"[Nested Loops](#Nested_Loops)
\n",
"[Conclusion](#Conclusion)
"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### While Loops:\n",
"\n",
"While loops are extremely useful in programming. The idea of while loops is to execute a block of code while a boolean expression is `True`. In general, the syntax for a while loop is:\n",
"\n",
"```\n",
"while something_True:\n",
" Do some work\n",
"```\n",
"\n",
"Here is an example of a basic `while` loop. This loop will print `n` as long as `n` is greater than 0. The computer will check the `n > 0` condition after it decrements `n`. If that condition still holds, then we will continue to print and decrement. If `n = 0` then the condition is no longer `True`, so the computer will not enter the `while` loop."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n = 10\n",
"while (n > 0):\n",
" print(n)\n",
" n = n - 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another example. Since `n < 0` to start, the `while` condition is not satisfied."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n = -10\n",
"while (n > 0):\n",
" print(n)\n",
" n = n - 1\n",
" \n",
"print(\"n is less than\", 0)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### For Loops:\n",
"\n",
"`for` loops differ from `while` loops in that `for` loops will iterate a fixed number of times, whereas a `while` loop will continue until the condition is no longer satisfied. We generally use `for` loops to iterate over sequences such as lists and strings. The two keywords used in for loops are `for` and `in`.\n",
"\n",
"In general, the syntax for a for loop is:\n",
"\n",
"```\n",
"for Some_Variable_of_Interest in Sequence:\n",
" Do some work\n",
"```\n",
"\n",
"Note that the sequence can be a string, list, or a dictionary.\n",
"\n",
"Here is an example of iterating over a string. The sequence part of this `for` loop contains a string, The computer will take the string and assign the first value in that string to the variable `letter`. Then the statement inside the `for` loop is executed. Each element in the string will then be assigned to the variable `letter` until there are no more letters left in the string."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for letter in \"Dog\":\n",
" print(\"Current Letter:\", letter)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another example of iterating over a string. The same idea as above, but now the elements assigned to the variable are from a list."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fruits = [\"banana\", \"apple\", \"mango\"]\n",
"for fruit in fruits:\n",
" print(\"Current fruit:\", fruit)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"#### The Range Function:\n",
"\n",
"The `range` function is a function which generates a list of numbers, starting from `0`, and going to the number `n - 1` by default. Its function definition is given by:\n",
"\n",
"`range(start, stop, step)`\n",
"\n",
"`start` specifies the first number, `stop` specifies the last number, and `step` is the number by which we increment. `start` is included in the list, but `stop` is not. Each parameter has to be an integer."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(5):\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(3, 6):\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(4, 10, 2):\n",
" print(i)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for i in range(0, -10, -2):\n",
" print(i)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"#### Iterating over list indices and dictionary keys:\n",
"\n",
"We can apply the `range` function to iterate over the index of a list. This can be useful if we want to iterate over the list in some order that is not the default. For dictionaries, a `for` loop will loop over the keys of the dictionary.\n",
"\n",
"An example of iterating through a list using `range`. What happens here is the same as what happens above when we interated through a string."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"fruits = [\"banana\", \"apple\", \"mango\"]\n",
"for index in range(len(fruits)):\n",
" print(\"Current fruit:\", fruits[index])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"An example of iteration on a dictionary."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"d = {\"x\": 1, \"y\": 2, \"z\": 3}\n",
"for key in d:\n",
" print(key, \"corresponds to\", d[key])"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### Application: Randomly Generated List\n",
"\n",
"Suppose we wish to generate a list of numbers of size `n`.\n",
"\n",
"We can use a `for` loop, the `range` function, and the `randint` function from the [random](https://docs.python.org/3/library/random.html) library to do this.\n",
"\n",
"The `randint` function will generate a random integer from a specified interval.\n",
"\n",
"The syntax is `randint(a,b)`. The values `a` and `b` are the endpoints, and are included as possible values.\n",
"\n",
"Change the value of the `size_of_list` variable to see what happens."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"size_of_list = 7\n",
"\n",
"import random as rand\n",
"random_list = []\n",
"\n",
"for i in range(0, size_of_list):\n",
" # Append a random value to the list using the randint function \n",
" random_list.append(rand.randint(1,1000))\n",
"print(random_list)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### The Break Statement:\n",
"\n",
"Suppose that we wish to end a loop early if a certain condition is met. We can use what is known as a `break` statement. The `break` statement will terminate `while` and `for` loops early. Usually it is used in conjunction with `if` and `else` statements.\n",
"\n",
"For example, This loop will add `1` to the variable `n`. If `n` is greater than `10` then the `if` statements will be `True`, and the `while` loop will be exited. After that the next line of code will be executed."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n = 0\n",
"while True:\n",
" n = n + 1\n",
" if n > 10:\n",
" break\n",
" print(n)\n",
" \n",
"print(\"Done!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"Another example, this time iterating through the letters in a string, and breaking out if the letter is equal to `h`. Notice the `==` to check for equality."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for letter in \"Python\":\n",
" if letter == \"h\":\n",
" break\n",
" print(\"Current Letter:\", letter)\n",
"\n",
"print(\"Done!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Practice:\n",
"\n",
"Code the following:\n",
"\n",
"1. Using a loop of your choice, output the squares of the numbers 1 to 10.\n",
"2. Find the value of $2^{16}$ using a `for` loop.\n",
"3. Using a `for` loop, print the reciprocals of the numbers from 1 to 20."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# Code goes here\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### Incrementing and Decrementing:\n",
"\n",
"We can increment or decrement variables in loops using two different notations. We used one in a previous example, where we set a variable equal to itself plus `1` to increment by one each time through the loop. We can decrement in a similar way."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n = 5\n",
"while n > 0:\n",
" print(n)\n",
" n = n - 1\n",
"print(\"Blastoff!\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"To increment or decrement we can also use the short form `n += 1` or `n -= 1`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n = 0\n",
"while n < 10:\n",
" n += 2 # equivalent to n = n + 2\n",
" print(n)\n",
"\n",
"print(\"Done!\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"n = 10\n",
"while n > 0:\n",
" print(n)\n",
" n -= 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Off by one error:\n",
"\n",
"An *off by one* error occurs when a `while` loop or `for` loop executes one too many or one too few times. A common cause is using `<` or `>` when `<=` or `>=` should have been used.\n",
"\n",
"Note the difference between the outputs of the following loops."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"list_of_words = ['zero', 'one', 'two', 'three', 'four', 'five']\n",
"print('Loop 1:')\n",
"i = 0\n",
"while i < 5:\n",
" print(list_of_words[i])\n",
" i += 1\n",
"print('')\n",
"print('Loop 2:')\n",
"j = 0\n",
"while j <= 5:\n",
" print(list_of_words[j])\n",
" j += 1"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### Infinite Loops:\n",
"\n",
"Infinite loops occur when the condition required to enter a loop never becomes `False`. This can cause undesirable behaviour or cause the computer to crash. We highly recommend avoiding these. The main culprit for these is forgetting to update a variable, or by having a loop condition that will never be `False`.\n",
"\n",
"Just to illustrate the following code would continue to increment `x` and then eventually crash the kernel. The error here is that the `while` condition is always satisfied, we would need to change the condition to get the `while` loop working.\n",
"\n",
"```\n",
"x = 6\n",
"while x > 5:\n",
" print(x)\n",
" x += 1\n",
" ```\n",
"\n",
"Sometimes infinite loops are desirable. For example computers waiting for a user input will be in an infinite loop checking for some sort of activity. This loop will continue until there is input or the device is turned off."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### Loops with if/else statements:\n",
"\n",
"As we saw when we were using the `break` statement, we can have conditional expressions inside loops.\n",
"\n",
"The following code use the `%` operator, which give the remainder after division.\n",
"\n",
"For example, `9 % 4` returns `1` since `9 ÷ 4 = 2` with a remainder of `1`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for n in range(10, 16):\n",
" if n % 2 == 0:\n",
" print(n, \"is even.\")\n",
" else:\n",
" print(n, \"is odd.\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"### Nested Loops:\n",
"\n",
"It is often useful to create what are known as **nested** loops. Nested loops are simply loops contained in a main loop. Usually, we would have code that looks like:\n",
"\n",
"```\n",
"while something_True:\n",
" Do some work\n",
" while something_else_True:\n",
" Do some other work\n",
"```\n",
"\n",
"The following code iterates over `n` from `3` to `8` (not including `8`) with a `for` loop. Each time through the `for` loop it uses a `while` loop to iterate over numbers from `1` to `n`."
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"for n in range(3, 8):\n",
" print('Counting up to', n)\n",
" i = 0\n",
" while i < n:\n",
" i += 1\n",
" if i%2 == 0:\n",
" print(i, 'is even')\n",
" else:\n",
" print(i, 'is odd')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### Extra Resources:\n",
"\n",
"[Some basic examples](https://www.pythonforbeginners.com/loops/for-while-and-nested-loops-in-python)\n",
"\n",
"[More examples of material covered in this notebook](https://www.learnpython.org/en/Loops)\n",
"\n",
"[Introduction to Python loops with examples](https://www.geeksforgeeks.org/loops-in-python/)\n",
"\n",
"[Different looping techniques with examples](https://www.geeksforgeeks.org/looping-techniques-python/)\n",
"\n",
"[More examples of looping with control statements](https://www.geeksforgeeks.org/loops-and-loop-control-statements-continue-break-and-pass-in-python/)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n",
"## Conclusion:\n",
"\n",
"This notebook introduced\n",
"1. `while` and `for` loops\n",
"2. The `range` function and `break` statements\n",
"3. Infinite Loops\n",
"4. Nested conditional statements and nested loops"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"[](https://github.com/callysto/curriculum-notebooks/blob/master/LICENSE.md)"
]
}
],
"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.7.4"
}
},
"nbformat": 4,
"nbformat_minor": 2
}