{ "cells": [ { "cell_type": "markdown", "metadata": { "hide_cell": true }, "source": [ "Make me look good. Click on the cell below and press Ctrl+Enter." ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "hide_cell": true }, "outputs": [ { "data": { "text/html": [ "\n", "\n", "\n", "\n", "\n", "\n" ], "text/plain": [ "" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.core.display import HTML\n", "HTML(open('css/custom.css', 'r').read())" ] }, { "cell_type": "markdown", "metadata": { "hide_cell": true }, "source": [ "
SM286D · Introduction to Applied Mathematics with Python · Spring 2020 · Uhan
\n", "\n", "
Lesson 5.
\n", "\n", "

User input and while loops

" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## This lesson..." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- User input\n", "- `while` loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## User input" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- Often you will want to get information from a user and incorporate that information into your program.\n", "\n", "- In Python, we can use the `input()` function to do this.\n", "\n", "- __Pro tip.__ The `input()` function always results in the user input being converted to a string.\n", "\n", "- Consider the following example:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your age? 27\n", "\n" ] } ], "source": [ "# Ask for the user's age\n", "age = input(\"What is your age? \")\n", "\n", "# What type of data does input() return?\n", "print(type(age))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- You can convert a string to an integer or a float using `int()` and `float()` respectively:" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "27\n", "\n" ] } ], "source": [ "# Convert age to an integer\n", "age_int = int(age)\n", "\n", "# Print to check the new variable\n", "print(age_int)\n", "\n", "# What type does the new variable have?\n", "print(type(age_int))" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "scrolled": true }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "27.0\n", "\n" ] } ], "source": [ "# Covert age to a float\n", "age_float = float(age)\n", "\n", "# Print to check the new variable\n", "print(age_float)\n", "\n", "# What type does the new variable have?\n", "print(type(age_float))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem.__ (PCC 5-10: Checking Usernames, modified) Do the following to create a program that simulates how websites ensure that everyone has a unique username. \n", "\n", "- Make a list of five or more usernames called `current_users`.\n", "- Ask the user to input their desired username.\n", "- Check to see if the user's desired username is taken:\n", " - If taken, print a message saying that username is taken.\n", " - If not taken, print a message saying that username is available.\n", "- Assume usernames are case-sensitive (so `Nelson` and `nelson` are not the same)." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Please enter a username: ProfessorAwesome\n", "I'm sorry, that username is taken.\n" ] } ], "source": [ "# List of current users\n", "current_users = ['ProfessorAwesome', 'Bingham', 'RustyChipmunk', 'ShineSpike', 'IAmSam15']\n", "\n", "# Ask user to input desired username\n", "username = input(\"Please enter a username: \")\n", "\n", "# Check if user's desired username is taken\n", "if username in current_users:\n", " print(\"I'm sorry, that username is taken.\")\n", "else:\n", " print(\"Congratulations, that username is available!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## While loops" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- A `while` loop runs a block of code *while* some statement is true.\n", "\n", "- A `while` loop stops only when the statement evaluates to `False`, or when the `break` statement is used\n", "\n", "- Consider the following examples:" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 6, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame(\"http://pythontutor.com/iframe-embed.html#code=x%20%3D%200%0Awhile%20x%20%3C%3D%205%3A%0A%20%20%20%20print%28x%29%0A%20%20%20%20x%20%2B%3D%201&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false\", width=800, height=400)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "data": { "text/html": [ "\n", " \n", " " ], "text/plain": [ "" ] }, "execution_count": 7, "metadata": {}, "output_type": "execute_result" } ], "source": [ "from IPython.display import IFrame\n", "IFrame(\"http://pythontutor.com/iframe-embed.html#code=x%20%3D%200%0Awhile%20True%3A%0A%20%20%20%20print%28x%29%0A%20%20%20%20x%20%2B%3D%201%0A%20%20%20%20%0A%20%20%20%20if%20x%20%3E%205%3A%0A%20%20%20%20%20%20%20%20break%0A%20%20%20%20&codeDivHeight=400&codeDivWidth=350&cumulative=false&curInstr=0&heapPrimitives=false&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false\", width=800, height=400)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Infinite loops and manually stopping a program" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- `for` loops always run for a fixed number of iterations.\n", "\n", "- On the other hand, it is possible for a `while` loop to run forever!\n", "\n", "- The code cell below contains an example of an infinite loop.\n", "\n", "- To stop the code in the cell below, you will need to click on the button (interrupt the kernel) or the button (restart the kernel) in the toolbar." ] }, { "cell_type": "code", "execution_count": null, "metadata": { "scrolled": true }, "outputs": [], "source": [ "x = 0\n", "while True:\n", " print(x)\n", " x += 1" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem. (PCC 5-10: Checking Usernames, modified again)__ Do the following to create a program that simulates how websites ensure that everyone has a unique username. \n", "\n", "- Make a list of five or more usernames called `current_users`.\n", "- Ask the user to input their desired username.\n", "- Check to see if the user's desired username is taken.\n", " - If taken, print a message saying that username is taken and ask the user again for their desired username.\n", " - If not taken, print a message saying that username is available.\n", "- Assume usernames are case-sensitive (so `Nelson` and `nelson` are not the same)." ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Please enter a username: ProfessorAwesome\n", "I'm sorry, that username is taken.\n", "Please enter a username: ProfessorBoring\n", "Congratulations, that username is available!\n" ] } ], "source": [ "# List of current users\n", "current_users = ['ProfessorAwesome', 'Bingham', 'RustyChipmunk', 'ShineSpike', 'IAmSam15']\n", "\n", "# Ask user to input desired username\n", "while True:\n", " username = input(\"Please enter a username: \")\n", " \n", " # Check if user's desired username is taken\n", " # If it isn't, stop the while loop\n", " if username in current_users:\n", " print(\"I'm sorry, that username is taken.\")\n", " else:\n", " print(\"Congratulations, that username is available!\")\n", " break" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Flags" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "- A __flag__ is a variable that acts as a symbol to either stop a program or exit a loop. \n", "\n", "- Usually a flag variable is either `True` or `False`. \n", "\n", "- Let's use a flag and a while loop to simulate the precarious position Robin Williams found himself in during the movie *Jumanji*. In the movie, the following rule had to be observed:\n", "\n", " > In the jungle, you must wait, until the dice read five or eight." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "6\n", "4\n", "5\n" ] } ], "source": [ "# Below we import the randint function from the random library\n", "# so that we can \"roll\" the dice in the code below\n", "from random import randint\n", "\n", "# Create a flag representing whether we're in the jungle\n", "# Initialize flag to True\n", "in_jungle = True\n", "\n", "while in_jungle:\n", " # Simulate the roll of 2 dice\n", " die1 = randint(1, 6)\n", " die2 = randint(1, 6)\n", " \n", " # Get the total\n", " dice_roll = die1 + die2\n", " print(dice_roll)\n", " \n", " # If the total is 5 or 8, update the flag to False\n", " if dice_roll == 5 or dice_roll == 8:\n", " in_jungle = False" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "---" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Classwork — on your own!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 1. (PCC 7-1: Rental Car)__ Write a program that asks the user what kind of rental car they\n", "would like. Print a message about that car, such as\n", "\n", "```\n", "Let me see if I can find you a Subaru.\n", "```" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What kind of car would you like? DeLorean\n", "Let me see if I can find you a DeLorean.\n" ] } ], "source": [ "# Ask user for car type\n", "car = input(\"What kind of car would you like? \")\n", "\n", "# Print message with user input\n", "print(f\"Let me see if I can find you a {car}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 2. (PCC 7-3: Multiples of Ten)__ Ask the user for a number, and then report whether the\n", "number is a multiple of 10 or not." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Please enter a number: 792\n", "That is not a multiple of ten!\n" ] } ], "source": [ "# Ask user for number\n", "number = input(\"Please enter a number: \")\n", "\n", "# Check if the number is a multiple of 10\n", "if (int(number) % 10) == 0:\n", " print(\"That is a multiple of ten!\")\n", "else: \n", " print(\"That is not a multiple of ten!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 3.__ Write code that asks for 2 numbers from the user and sets the variable `total` equal to their sum. Print the value of `total`." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Enter the first number: 42\n", "Enter the second number: 36\n", "The sum of your two numbers is 78.0.\n" ] } ], "source": [ "# Ask the user for two numbers\n", "first_num = input(\"Enter the first number: \")\n", "second_num = input(\"Enter the second number: \")\n", "\n", "# Convert the user input from strings to floats\n", "first_num = float(first_num)\n", "second_num = float(second_num)\n", " \n", "# Add the numbers\n", "total = first_num + second_num\n", " \n", "# Print the total value\n", "print(f\"The sum of your two numbers is {total}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 4 (PCC 7-5: Movie Tickets).__ A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is \\\\$10; and if they are over age 12, the ticket is \\\\$15. Write a loop in which you repeatedly ask users their age, and then tell them the cost of their movie ticket." ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your age? 78\n", "Your ticket costs $15\n", "What is your age? 32\n", "Your ticket costs $15\n", "What is your age? oops\n" ] }, { "ename": "ValueError", "evalue": "invalid literal for int() with base 10: 'oops'", "output_type": "error", "traceback": [ "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[0;31mValueError\u001b[0m Traceback (most recent call last)", "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m()\u001b[0m\n\u001b[1;32m 1\u001b[0m \u001b[0;32mwhile\u001b[0m \u001b[0;32mTrue\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;31m# loops forever but you get an error if you enter text\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0mage\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"What is your age? \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0;32mif\u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m<\u001b[0m \u001b[0;36m3\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0mmessage\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m\"Your ticket is free!\"\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0;32melif\u001b[0m \u001b[0mint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mage\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;34m<=\u001b[0m \u001b[0;36m12\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n", "\u001b[0;31mValueError\u001b[0m: invalid literal for int() with base 10: 'oops'" ] } ], "source": [ "while True: # loops forever but you get an error if you enter text\n", " age = input(\"What is your age? \")\n", " if int(age) < 3: \n", " message = \"Your ticket is free!\"\n", " elif int(age) <= 12: \n", " message = \"Your ticket costs $10.\"\n", " else: \n", " message = \"Your ticket costs $15\"\n", " print(message)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 5.__ Take a quick break." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 6. (PCC 7-6: Three Exits)__ Read pages 118-123 of PCC on `while` loops and make sure you understand the different ways of stopping a `while` loop.\n", "\n", "Write different versions of Problem 4 that do each of the following:\n", "\n", " - Use a conditional test in the while statement to stop the loop when the user enters `q`.\n", " - Use a flag to stop the loop when the user enters `q`.\n", " - Use a break statement to stop the loop when the user enters `q`." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your age? (enter q to quit) 1\n", "Your ticket is free!\n", "What is your age? (enter q to quit) 10\n", "Your ticket costs $10.\n", "What is your age? (enter q to quit) q\n", "See you soon!\n" ] } ], "source": [ "# Conditional exit\n", "age = 0\n", "while age != 'q': \n", " age = input(\"What is your age? (enter q to quit) \")\n", " if age == 'q':\n", " message = \"See you soon!\"\n", " elif int(age) < 3: \n", " message = \"Your ticket is free!\"\n", " elif int(age) <= 12: \n", " message = \"Your ticket costs $10.\"\n", " else: \n", " message = \"Your ticket costs $15\"\n", " print(message)" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your age? (enter q to quit) 1\n", "Your ticket is free!\n", "What is your age? (enter q to quit) 10\n", "Your ticket costs $10.\n", "What is your age? (enter q to quit) q\n", "See you soon!\n" ] } ], "source": [ "# Flag exit\n", "active = True\n", "while active: \n", " age = input(\"What is your age? (enter q to quit) \")\n", " if age == 'q':\n", " active = False\n", " message = \"See you soon!\"\n", " elif int(age) < 3: \n", " message = \"Your ticket is free!\"\n", " elif int(age) <= 12: \n", " message = \"Your ticket costs $10.\"\n", " else: \n", " message = \"Your ticket costs $15\"\n", " print(message)" ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "What is your age? (enter q to quit) 1\n", "Your ticket is free!\n", "What is your age? (enter q to quit) 10\n", "Your ticket costs $10.\n", "What is your age? (enter q to quit) q\n", "See you soon!\n" ] } ], "source": [ "# Break exit\n", "while True: \n", " age = input(\"What is your age? (enter q to quit) \")\n", " if age == 'q':\n", " print(\"See you soon!\")\n", " break\n", " if int(age) < 3: \n", " message = \"Your ticket is free!\"\n", " elif int(age) <= 12: \n", " message = \"Your ticket costs $10.\"\n", " else: \n", " message = \"Your ticket costs $15\"\n", " print(message)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 7.__ Use a while loop to approximate $\\sum_{k=1}^{\\infty} \\frac{1}{k^3}$ by summing all terms whose value is greater than $10^{-6}.$ Print your approximation." ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The sum of 1/k^3 for all k >= 1 is approximately 1.2020064006596782.\n" ] } ], "source": [ "# Initialize total value\n", "# Don't call the variable sum, which is a function name\n", "total = 0\n", "\n", "# Keep going while 1 / k^3 is greater than 10^-6\n", "k = 1\n", "while 1 / k**3 > 1e-6: \n", " total += 1 / k**3\n", " k += 1\n", "\n", "# Print the approximation\n", "print(f\"The sum of 1/k^3 for all k >= 1 is approximately {total}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 8.__ Add up the squares from $1^2$ to $1000^2$ by\n", "\n", "1. creating a list of the squares $1^2$, $2^2$, ..., $1000^2$ __with a list comprehension__, and then \n", "2. compute their sum using the `sum` function. \n", "\n", "Print your answer. (This doesn't use material from this lesson; this is just a warm up for the next problem.)" ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The sum of the first 1000 squares is 333833500.\n" ] } ], "source": [ "# Create list of squares using a list comprehension\n", "values = [i**2 for i in range(1, 1001)]\n", "\n", "# Add the squares, print the total\n", "print(f\"The sum of the first 1000 squares is {sum(values)}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 9.__ Use a `while` loop to add the squares from $1^2$ to $1000^2$. Print your answer. Hopefully you get the same answer as you did in Problem !" ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The sum of the first 1000 squares is 333833500.\n" ] } ], "source": [ "# Variable to hold total value\n", "# Don't call the variable sum, which is a function name\n", "total = 0 \n", "\n", "# Start with 1^2, and keep on going until we reach 1000^2\n", "i = 1\n", "while i <= 1000: \n", " total += i**2\n", " i += 1\n", " \n", "# Print the total\n", "print(f\"The sum of the first 1000 squares is {total}.\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "__Problem 10.__ What does the following code do? Run this code. Then run it with other positive integers instead of 17. What do you think happens in general? You've just made a conjecture. Compare it with the Collatz conjecture (search on the internet for this term). " ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "17\n", "52\n", "26\n", "13\n", "40\n", "20\n", "10\n", "5\n", "16\n", "8\n", "4\n", "2\n", "1\n" ] } ], "source": [ "number = 17\n", "print(number)\n", "\n", "while number != 1: \n", " if (number % 2)==0:\n", " number = int(number / 2)\n", " else:\n", " number = 3 * number + 1\n", " print(number)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "_Write your notes here. Double-click to edit._\n", "\n", "The code repeatedly divides an even number by 2 and multiplies an odd number by 3 and adds 1. It does this until the number reaches 1. I predict that this process will reach 1 no matter our choice of starting number. This is called the Collatz conjecture." ] } ], "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }