{ "cells": [ { "cell_type": "markdown", "id": "45e2f5bc", "metadata": {}, "source": [ "# `for` Loops\n", "\n", "One of the defining features of computers is their ability to perform repetitive tasks with precision and speed. In the realm of programming, Python, like many other languages, offers a powerful construct known as the `for` loop to automate and simplify such repetitive actions. \n", "\n", "## What is a For Loop?\n", "At its core, a `for` loop is a programming structure that enables you to execute a specific block of code repeatedly. It iterates over a sequence of items, performing the same set of actions for each item in the sequence. Whether you want to process a list of values, manipulate strings, or iterate over the elements of a dictionary, the `for` loop is a go-to tool.\n", "\n", "## Basic Structure of a For Loop\n", "In Python, a `for` loop is defined using the for keyword, followed by a variable (often referred to as an \"iterator\") that represents each item in the sequence, the in keyword, and the sequence itself. The indented code block immediately following the for statement defines what you want to do with each item in the sequence." ] }, { "cell_type": "code", "execution_count": 9, "id": "ffe45cae", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n" ] } ], "source": [ "for i in range(1,3):\n", " # Code to be executed for each item\n", " print(i)" ] }, { "cell_type": "markdown", "id": "08f3c7e7", "metadata": {}, "source": [ "# Using For Loops with Lists\n", "One common use case `for` for loops is iterating over [`lists`](../variables_data_types/lists.ipynb). Lists are collections of data elements, and you can effortlessly process each element in the list using a for loop. Here's an example:" ] }, { "cell_type": "code", "execution_count": 10, "id": "6288ebe0", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "My favourite books include:\n", " - Mastery\n", " - The Signal And The Noise\n", " - The Organized Mind\n" ] } ], "source": [ "fav_books = ['mastery', 'the signal and the noise', 'the organized mind']\n", "\n", "print(\"My favourite books include:\")\n", "for book in fav_books:\n", " print(\" - \" + book.title())" ] }, { "cell_type": "markdown", "id": "72d8e76e", "metadata": {}, "source": [ "In the above code, the `for` loop iterates over the `fav_books` list, converting each book title to the title case and printing it.\n", "\n", "## `for` Loops and the `range()` Function\n", "`for` loops can also work in tandem with the `range()` function, which generates a sequence of numbers. This is particularly useful when you need to repeat an action a specific number of times. However, it's essential to remember that `range()` generates numbers up to, but not including, the specified end value. Here's an example:" ] }, { "cell_type": "code", "execution_count": 11, "id": "b0bd0059", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "2\n", "3\n", "4\n", "5\n", "6\n", "7\n", "8\n", "9\n", "10\n" ] } ], "source": [ "for number in range(1,11):\n", " print(number)" ] }, { "cell_type": "markdown", "id": "ed01b01a", "metadata": {}, "source": [ "This code snippet will print numbers from 1 to 10, emphasizing the importance of being mindful of the \"off by one\" error.\n", "\n", "## Looping Over Dictionaries\n", "Python's `for` loop can efficiently navigate [`dictionaries`](../variables_data_types/dictionaries.ipynb) as well. Dictionaries are collections of key-value pairs, and you can loop over their keys, values, or both. Here's how it's done:" ] }, { "cell_type": "code", "execution_count": 12, "id": "4541b665", "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Jim\n", "Dwight\n", "Michael\n", "+37682929928\n", "+423998200919\n", "+876230123654\n", "Jim +37682929928\n", "Dwight +423998200919\n", "Michael +876230123654\n" ] } ], "source": [ "phone_numbers = {\"Jim\": \"+37682929928\", \n", " \"Dwight\": \"+423998200919\",\n", " \"Michael\": \"+876230123654\"\n", " }\n", "\n", "# Looping over keys\n", "for name in phone_numbers.keys():\n", " print(name)\n", "\n", "# Looping over values\n", "for number in phone_numbers.values():\n", " print(number)\n", "\n", "# Looping over items (key-value pairs)\n", "for name, number in phone_numbers.items():\n", " print(name, number)\n" ] }, { "cell_type": "markdown", "id": "86ec6a68-c2ef-4a8c-8638-5dac81489b83", "metadata": {}, "source": [ "In this example, we loop over the keys, values, and items (key-value pairs) within the `phone_numbers` dictionary, allowing us to access and manipulate the data as needed." ] } ], "metadata": { "jupytext": { "formats": "ipynb,md:myst" }, "kernelspec": { "display_name": "Python 3 (ipykernel)", "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.11.4" } }, "nbformat": 4, "nbformat_minor": 5 }