{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Continue And Break Loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- **Author:** [Chris Albon](http://www.chrisalbon.com/), [@ChrisAlbon](https://twitter.com/chrisalbon)\n", "- **Date:** -\n", "- **Repo:** [Python 3 code snippets for data science](https://github.com/chrisalbon/code_py)\n", "- **Note:**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Import the random module" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "collapsed": false }, "outputs": [], "source": [ "import random" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "In this while loop:\n", "- If the number is less than 3, the loop restarts again.\n", "- If the number is 4, it changes running to false and the loop ends.\n", "- If the number is 5, it breaks out of the loop and the loop ends." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create a while loop" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "collapsed": false }, "outputs": [], "source": [ "# set running to true\n", "running = True" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "collapsed": false }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "It is too small, starting over.\n", "It is too small, starting over.\n", "It is 4! Changing running to false\n" ] } ], "source": [ "# while running is true\n", "while running:\n", " # Create a random integer between 0 and 5\n", " s = random.randint(0,5)\n", " # If the integer is less than 3\n", " if s < 3:\n", " # Print this\n", " print('It is too small, starting over.')\n", " # Reset the next interation of the loop\n", " # (i.e skip everything below and restart from the top)\n", " continue\n", " # If the integer is 4\n", " if s == 4:\n", " running = False\n", " # Print this\n", " print('It is 4! Changing running to false')\n", " # If the integer is 5,\n", " if s == 5:\n", " # Print this\n", " print('It is 5! Breaking Loop!')\n", " # then stop the loop\n", " break" ] } ], "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.3.5" } }, "nbformat": 4, "nbformat_minor": 0 }