{ "cells": [ { "cell_type": "markdown", "metadata": { "id": "VcybRL6lIq-O" }, "source": [ "# Loops and Conditionals" ] }, { "cell_type": "markdown", "metadata": { "id": "fxa7FGu7Iq-Q" }, "source": [ "## For Loops\n", "\n", "A for loop is used for iterating over a sequence. The sequence can be a list, a tuple, a dictionary, a set, or a string.\n", "\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "FD8RTQabIq-R" }, "outputs": [], "source": [ "cities = ['San Francisco', 'Los Angeles', 'New York', 'Atlanta']\n", "\n", "for city in cities:\n", " print(city)" ] }, { "cell_type": "markdown", "metadata": { "id": "CtTpoZsiIq-S" }, "source": [ "To iterate over a dictionary, you can call the `items()` method on it which returns a tuple of key and value for each item." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "IhyJMlyYIq-S" }, "outputs": [], "source": [ "data = {'city': 'San Francisco', 'population': 881549, 'coordinates': (-122.4194, 37.7749) }\n", "\n", "for x, y in data.items():\n", " print(x, y)" ] }, { "cell_type": "markdown", "metadata": { "id": "MC-cZ4jTIq-S" }, "source": [ "The built-in `range()` function allows you to create sequence of numbers that you can iterate over" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "s5aQD5EoIq-S" }, "outputs": [], "source": [ "for x in range(5):\n", " print(x)" ] }, { "cell_type": "markdown", "metadata": { "id": "-EdoGJ_NIq-S" }, "source": [ "The range function can also take a start and an end number" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "mt9ist7mIq-T" }, "outputs": [], "source": [ "for x in range(1, 10, 2):\n", " print(x)" ] }, { "cell_type": "markdown", "metadata": { "id": "YjmjJ0_RIq-T" }, "source": [ "## Conditionals\n", "\n", "Python supports logical conditions such as equals, not equals, greater than etc. These conditions can be used in several ways, most commonly in *if statements* and loops.\n", "\n", "An *if statement* is written by using the `if` keyword.\n", "\n", "Note: A very common error that programmers make is to use *=* to evaluate a *equals to* condition. The *=* in Python means assignment, not equals to. Always ensure that you use the *==* for an equals to condition." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ZXzXSg5pIq-T" }, "outputs": [], "source": [ "for city in cities:\n", " if city == 'Atlanta':\n", " print(city)" ] }, { "cell_type": "markdown", "metadata": { "id": "RDVjqgLSIq-T" }, "source": [ "You can use `else` keywords along with `if` to match elements that do not meet the condition" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "UVprKXleIq-T" }, "outputs": [], "source": [ "for city in cities:\n", " if city == 'Atlanta':\n", " print(city)\n", " else:\n", " print('This is not Atlanta')" ] }, { "cell_type": "markdown", "metadata": { "id": "AgyTuBC5Iq-T" }, "source": [ "Python relies on indentation (whitespace at the beginning of a line) to define scope in the for loop and if statements. So make sure your code is properly indented." ] }, { "cell_type": "markdown", "metadata": { "id": "EyuMTS1EIq-U" }, "source": [ "You can evaluate a series of conditions using the `elif` keyword.\n", "\n", "Multiple criteria can be combined using the `and` and `or` keywords." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "ieLSAlWWIq-U" }, "outputs": [], "source": [ "cities_population = {\n", " 'San Francisco': 881549,\n", " 'Los Angeles': 3792621,\n", " 'New York': 8175133,\n", " 'Atlanta':498044\n", "}\n", "\n", "for city, population in cities_population.items():\n", " if population < 1000000:\n", " print('{} is a small city'.format(city))\n", " elif population > 1000000 and population < 5000000:\n", " print('{} is a big city'.format(city))\n", " else:\n", " print('{} is a mega city'.format(city))" ] }, { "cell_type": "markdown", "metadata": { "id": "wjkvlcskIq-U" }, "source": [ "## Control Statements\n", "\n", "A for-loop iterates over each item in the sequence. Sometimes is desirable to stop the execution, or skip certain parts of the for-loops. Python has special statements, `break`, `continue` and `pass`." ] }, { "cell_type": "markdown", "metadata": { "id": "nVioGPW_Iq-U" }, "source": [ "A `break` statement will stop the loop and exit out of it" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "0RbsWzSoIq-U" }, "outputs": [], "source": [ "for city in cities:\n", " print(city)\n", " if city == 'Los Angeles':\n", " print('I found Los Angeles')\n", " break" ] }, { "cell_type": "markdown", "metadata": { "id": "zKbhSW6SIq-U" }, "source": [ "A `continue` statement will skip the remaining part of the loop and go to the next iteration" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "5Pp2J0KdIq-U" }, "outputs": [], "source": [ "for city in cities:\n", " if city == 'Los Angeles':\n", " continue\n", " print(city)" ] }, { "cell_type": "markdown", "metadata": { "id": "oyk8QjIhIq-U" }, "source": [ "A `pass` statement doesn't do anything. It is useful when some code is required to complete the syntax, but you do not want any code to execute. It is typically used as a placeholder when a function is not complete." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "yX5rjvV6Iq-U" }, "outputs": [], "source": [ "for city in cities:\n", " if city == 'Los Angeles':\n", " pass\n", " else:\n", " print(city)" ] }, { "cell_type": "markdown", "metadata": { "id": "lEPeBA-MIq-U" }, "source": [ "## Exercise\n", "\n", "The Fizz Buzz challenge.\n", "\n", "Write a program that prints the numbers from 1 to 100 and for multiples of 3 print **Fizz** instead of the number and for the multiples of 5 print **Buzz**. If it is divisible by both, print **FizzBuzz**.\n", "\n", "So the output should be something like below\n", "\n", "`1, 2, Fizz, 4, Buzz, Fizz ... 13, 14, FizzBuzz, ...`\n", "\n", "Breaking down the problem further, we need to create for-loop with following conditions\n", "\n", "- If the number is a multiple of both 3 and 5 (i.e. 15), print FizzBuzz\n", "- If the number is multiple of 3, print Fizz\n", "- If the number is multiple of 5, print Buzz\n", "- Otherwise print the number\n", "\n", "Hint: See the code cell below. Use the modulus operator **%** to check if a number is divisible by another. `10 % 5` equals 0, meaning it is divisible by 5.\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": { "id": "KseRBGB2Iq-U" }, "outputs": [], "source": [ "for x in range(1, 10):\n", " if x%2 == 0:\n", " print('{} is divisible by 2'.format(x))\n", " else:\n", " print('{} is not divisible by 2'.format(x))" ] }, { "cell_type": "markdown", "metadata": { "id": "TPC6zR-BIq-U" }, "source": [ "----" ] } ], "metadata": { "colab": { "provenance": [] }, "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.5" } }, "nbformat": 4, "nbformat_minor": 0 }