{ "nbformat": 4, "nbformat_minor": 0, "metadata": { "colab": { "provenance": [] }, "kernelspec": { "name": "python3", "display_name": "Python 3" }, "language_info": { "name": "python" } }, "cells": [ { "cell_type": "markdown", "metadata": { "id": "Y30FK5CHTRZ9" }, "source": [ "#**Workshop 4: Repetition Structures**\n" ] }, { "cell_type": "markdown", "metadata": { "id": "cMHKRoQeTVbj" }, "source": [ "##**Objectives**\n", "At the end of this workshop, you will be able to:\n", "* Differentiate between while loops, for loops, validation loops and nested loops\n", "* Write a program using a while loop\n", "* Write a program using a for loop\n" ] }, { "cell_type": "markdown", "metadata": { "id": "L1e6_Zo-Tj9O" }, "source": [ "##**Why should I bother using loops at all? When the code below works just fine?**\n", "* Shortens code and makes it easier to debug\n", "* Gives you more control over your program\n", "* Allows you to repeat actions" ] }, { "cell_type": "code", "metadata": { "id": "9oerHazwZT8G" }, "source": [ "#Get the price of five different items and total cost\n", "item1=float(input('Enter the price of the first item:'))\n", "item2=float(input('Enter the price of the second item:'))\n", "item3=float(input('Enter the price of the third item:'))\n", "item4=float(input('Enter the price of the fourth item:'))\n", "item5=float(input('Enter the price of the fifth item:'))\n", "item_cost=float(item1+item2+item3+item4+item5)\n", "\n", "#Calculate Sales tax\n", "sales_tax=float((format(item_cost*.07, ',.2f'))\n", "total_cost=float(format(sales_tax+item_cost, ',.2f'))\n", "\n", "\n", "#display sales tax and total cost\n", "print('sales tax:', sales_tax)\n", "print('total cost:', total_cost)\n" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "b1j5JwcQUCaj" }, "source": [ "##**While Loops**\n", "\n", "The first type of repetition structure we’re going to discuss today is the While loop. While loops utilize conditionals to test whether or not a condition is true. If the condition is tested to be true, the loop tells python what task to run. When the condition is tested false, the loop tells the program to end.\n", "\n", "If you don’t add in a way for the loop to be false, you will accidentally create something known as an infinite loop. Infinite loops cause programs to run until manually terminated and are something to be avoided. (Beware the infinate loop!)\n", "\n" ] }, { "cell_type": "code", "metadata": { "id": "QQ6uq9G3UQnE" }, "source": [ "#variable to control the loop\n", "shopping = 'y'\n", "\n", "#empty list for items\n", "shopList = []\n", "\n", "#loop to start shopping\n", "while shopping == 'y' or shopping == 'Y':\n", "\n", "#append items to list\n", " item = float(input('What is the cost of the item you are trying to buy?'))\n", " shopList.append(item)\n", " print(shopList)\n", " shopping = input('Do you have another item that you want to purchase? Enter y for yes:')\n", "\n", "#end of loop message\n", "print('Thanks for shopping with us! Your total today is:', sum(shopList))" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "hmtOIazJUgke" }, "source": [ "##**For Loops**\n", "\n", "A for loop is a count controlled loop that iterates a specific number of times." ] }, { "cell_type": "code", "metadata": { "id": "PcyunWRrUquf" }, "source": [ "print('I will display the numbers 1 through 5')\n", "for num in [1,2,3,4,5]:\n", " print(num)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "nrMGAK0FUrtd" }, "source": [ "You can also print a range" ] }, { "cell_type": "code", "metadata": { "id": "Jx3eC3qyUtqN" }, "source": [ "for x in range(5):\n", " print('Hello world!')" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "fdtV2eNUV-ZH" }, "source": [ "The following example is of a math program that uses a few pieces of code we haven't gone over yet:\n", "\n", "* import random is used to import a random number generator\n", "* random.randint(1,10) means we're asking python for a random number between 1 and 10\n", "\n", "When you run this program, you will be given 10 addition problems to calculate. If you get the answer wrong, you're given an incorrect message. If you get the answer correct, you're given a correct message. The program is also keeping track of the number you get correct." ] }, { "cell_type": "code", "metadata": { "id": "gsMMTS5DV8qZ" }, "source": [ "import random\n", "\n", "#variable to keep track of correct answers\n", "correct = 0\n", "\n", "#for loop to control how many questions you’re asked\n", "for total in range(10):\n", "\n", "#random numbers being added together\n", " num1 = random.randint(1,10)\n", " num2 = random.randint(1,10)\n", " num3 = num1 + num2\n", " print(num1, \"+\", num2, \"=\")\n", " answer = int(input(\"What is the answer?\"))\n", "\n", "#if else statements to determine correctness\n", " if answer == num3:\n", " correct+=1\n", " print(\"That’s right!\")\n", " else:\n", " print(\"That’s not right!\")\n", "\n", "print(\"You've answered\", correct, \"qustions correctly.\")" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "6rpcdN2NYDWq" }, "source": [ "##**Use validation loops to inspect input data**\n", " Validation loops ensure that data the user inputs will work with the code you have written and helps prevent user error." ] }, { "cell_type": "code", "metadata": { "id": "MMTHgGkgYHYt" }, "source": [ "score = int(input('Enter a test score:'))\n", "\n", "while score < 0 or score >100:\n", " print('ERROR: The score cannot be negative or greater than 100.')\n", " score = int(input('Enter a test score:'))\n", "\n", "print(score)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "dGXgzKmxYe7M" }, "source": [ "##**Nested loops are loops within a loop!**\n", "\n", " You can have multiple while loops running in python at any point in time. An example would be beginning a loop with a validation loop.\n" ] }, { "cell_type": "code", "metadata": { "id": "shet1Bfkf5ka" }, "source": [ "games = 'y'\n", "player_scores = []\n", "\n", "while games == 'y' or games == 'Y':\n", "\n", " score = int(input('Enter a game score:'))\n", " while score < 0 or score >100:\n", " print('ERROR: The score cannot be negative or greater than 100.')\n", " score = int(input('Enter a game score:'))\n", "\n", " player_scores.append(score)\n", " games = (input('Would you like to enter another game score?'))\n", "\n", "print(player_scores)" ], "execution_count": null, "outputs": [] }, { "cell_type": "markdown", "metadata": { "id": "u9iP0HCQcqPM" }, "source": [ "##**Try it yourself**\n", "\n", "You’re having a party and are trying to write a program that will allow you to input the names of your guests into a list and then print out your completed list.\n", "* Create a while loop that will prompt you to add names to your list\n", "* Create a for loop that will print out each name on its own line\n", "\n", "\n", "*Hint: take a look at the code we’ve used today and in previous bites!*\n" ] }, { "cell_type": "code", "metadata": { "id": "IKXHZj58c0IL" }, "source": [], "execution_count": null, "outputs": [] } ] }