{ "metadata": { "name": "", "signature": "sha256:f33c90f55970c0fc7e3d057a3aab564f78b705294520ed0b27bb3a1808e82c52" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# while Statement\n", "\n", "- **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:** Based on: A Byte of Python" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## While loops until a condition is true." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Import the random module." ] }, { "cell_type": "code", "collapsed": false, "input": [ "import random" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create a variable of the true number of deaths of an event." ] }, { "cell_type": "code", "collapsed": false, "input": [ "deaths = 6" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Create a variable that is denotes if the while loop for keep running." ] }, { "cell_type": "code", "collapsed": false, "input": [ "running = True" ], "language": "python", "metadata": {}, "outputs": [], "prompt_number": 4 }, { "cell_type": "markdown", "metadata": {}, "source": [ "### while running is True" ] }, { "cell_type": "code", "collapsed": false, "input": [ "while running:\n", " # Create a variable that randomly create a integer between 0 and 10.\n", " guess = random.randint(0,10)\n", "\n", " # if guess equals deaths,\n", " if guess == deaths:\n", " # then print this\n", " print('Correct!')\n", " # and then also change running to False to stop the script\n", " running = False\n", " # else if guess is lower than deaths\n", " elif guess < deaths:\n", " # then print this\n", " print('No, it is higher.')\n", " # if guess is none of the above\n", " else:\n", " # print this\n", " print('No, it is lower')" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "No, it is lower\n", "No, it is higher.\n", "Correct!\n" ] } ], "prompt_number": 5 }, { "cell_type": "markdown", "metadata": {}, "source": [ "By the output, you can see that the while script keeping generating guesses and checking them until guess matches deaths, in which case the script stops." ] } ], "metadata": {} } ] }