{"nbformat":4,"nbformat_minor":0,"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.8.3"},"colab":{"name":"ex0 - intro to python.ipynb","provenance":[{"file_id":"1JvFihr4n2BRQk5Z2yq8We3-kUVyh3E2a","timestamp":1653574498662},{"file_id":"1CyCkorDS44LaXsnpKIahzkgPfoVlypcc","timestamp":1645423944383},{"file_id":"1FwtNuKQIcKOsIQyfJiti8crBrYuhY3jA","timestamp":1638891872672}],"collapsed_sections":["-Kg-TBkI0mS-"],"toc_visible":true}},"cells":[{"cell_type":"markdown","metadata":{"id":"UTt709mbMcfP"},"source":["# Introduction to Basic Python Command, Data Structures, and Variables"]},{"cell_type":"markdown","metadata":{"id":"k8mvv6_oMcfU"},"source":["\n","\n","```\n","# This is formatted as code\n","```\n","\n","## Motivating Example\n","\n","This is an example Python program that displays the text “Hello, world!” followed by a description of how many pets someone has."]},{"cell_type":"code","metadata":{"id":"eIgsD9AbMcfV","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1637366242300,"user_tz":480,"elapsed":4,"user":{"displayName":"Sam Scarborough","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14Ghk5loPmSbpeoTj0WqLVWGK-2gSQlGreDneEmgK=s64","userId":"18324888543492053717"}},"outputId":"051904a6-93ef-4a0f-9d15-35c63d16b440"},"source":["# This lines prints hello world \n","print (\"Hello World!\")\n","print (\"I have no dogs\")"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Hello World!\n","I have no dogs\n"]}]},{"cell_type":"code","metadata":{"id":"gAKwkkfpMcfY","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1637366244880,"user_tz":480,"elapsed":566,"user":{"displayName":"Sam Scarborough","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14Ghk5loPmSbpeoTj0WqLVWGK-2gSQlGreDneEmgK=s64","userId":"18324888543492053717"}},"outputId":"f3d1a769-9735-430b-ca14-f4bbd39faed9"},"source":["# Printing text\n","print(\"Hello World!\")\n","\n","# Printing how many pets you have\n","print(\"I have 2 dogs.\")"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Hello World!\n","I have 2 dogs.\n"]}]},{"cell_type":"markdown","metadata":{"id":"d_yElViMMcfd"},"source":["When you use print, each new thing that you want to display will be shown on a new line. If you want to display text, you need to write the word print, followed by the text in quotes between parentheses: (\"insert your text here\").\n","\n","Do you notice those lines with # signs in front? Those are called comments. Comments are really useful to tell people what's happening in your code, as well as a reminder for yourself when you review what you've written. The comments aren't actual code, so you don't need to worry about Python reading them when your programs are running. In other words, they don't get printed out."]},{"cell_type":"markdown","metadata":{"id":"7aS9vB1ieicC"},"source":["### Try it out: Introduce yourself!\n","\n","Write a program that prints your name and something about yourself. Here’s an example of what your program could display: \n"," > `My name is Arya.`\n"," \n"," > `I like writing Python programs.`\n"," \n"," Please comment each line of your code informatively."]},{"cell_type":"code","metadata":{"id":"r6MOXpihMcff"},"source":["# Write your code here. \n","print (\"My name is Patrick\")\n","print (\"I like writing Python programs.\")"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"BnnugRhxMcfh"},"source":["Watch [this](https://youtu.be/Jto6IBy9z9k) video introducing you to **variables.**\n","\n","Often, when we're programming, we need to store some pieces of information. A good way to do this is by using **variables**. Variables are like containers: you can put things into them and extract their contents later.\n","\n","To declare a variable, there are three steps:\n","\n","1. Come up with a name for your variable\n","2. Write an equals sign (=)\n","3. Put the **value** you want to store in your variable after the = sign"]},{"cell_type":"markdown","metadata":{"id":"ki6JxFG8wsKz"},"source":["### Example: What I ate today \n","\n","Let's see how we can use a variable to store information about what someone ate for breakfast and lunch today, and then print it."]},{"cell_type":"code","metadata":{"id":"feE_Pgk9tLgs","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1635690826718,"user_tz":240,"elapsed":201,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"0ee1429e-1724-4b92-c062-ce4c5a04a5b0"},"source":["# a variable to store what I ate tooday \n","meal = \"english muffin\" \n","print (\"breakfast:\" + meal)\n","\n","# what I ate for lunch \n","meal = \"pizza with ranch dip\" \n","print (\"lunch: \" + meal) \n","\n","number_of_meals = 5\n","\n","print(number_of_meals)"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["breakfast:english muffin\n","lunch: pizza with ranch dip\n","5\n"]}]},{"cell_type":"markdown","metadata":{"id":"MhBR2vFFwgBg"},"source":["Here, we made a variable called `meal`, and initially assigned it the value of `\"English muffin\"`. Later on, we reassigned the variable with a different value, `\"Pizza with ranch dip\"`. Since we reassigned the variable, `\"English muffin\"` is completely replaced and we don't have access to that original value any more. If you wanted to keep the original value, you could consider defining a second variable, calling it something like `meal2`.\n","\n","Do you also notice that `+` sign in the `print` statements? You can use it to chain piece of text together when you want to display more than one word or phrase. This is called **concatenation**."]},{"cell_type":"markdown","metadata":{"id":"eK52VvZr1VwS"},"source":["## Variable types\n","\n","All of the code above has been used to record and display text information. In Python, text between quotation marks is called a **string**. Referring to examples from before, `\"English muffin\"` is a string, as is `\"I have 2 dogs.\"`\n","\n","However, we can store other pieces of information in variables aside from strings. For instance, we can store numbers in variables. There are two primary numeric variable types in Python: **integers** and **floats** (or floating-point numbers). Integers are whole numbers (e.g. 4), and floats are numbers with a decimal part (e.g. 8.26).\n","\n","Let's see an example of how to define two numeric variables and add them together."]},{"cell_type":"code","metadata":{"id":"QTwzSrG01UXt","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1636909661461,"user_tz":480,"elapsed":3,"user":{"displayName":"Braden Monroe","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjWHGIVTAWJFJX-igMgPLiTl88SyYPNavFiV4MCXA=s64","userId":"14803880866214127972"}},"outputId":"d21177d1-d9d1-4d06-ed40-1523c684c57f"},"source":["# define an integer \n","our_integer = 5 \n","\n","#define a float vriable \n","our_float = 3.65\n","\n","#add them together \n","result = our_integer + our_float \n","print(result)"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["8.65\n"]}]},{"cell_type":"markdown","metadata":{"id":"fbEDo3ki2Bm4"},"source":["Do you notice anything different about how these variables look? With strings, we need to use quotation marks to define them. But with numbers, we can leave out the quotes. That means that `2` and `\"2\"` are not the same thing: the first is an integer, while the second is a string.\n","\n","Notice that we can add numeric variables in Python using the `+` operator. So it behaves like traditional addition as well as the concatenation (putting strings together) that you saw earlier. The values of `our_integer` and `our_float` are being combined and stored in `our_result` in the above example.\n","\n","We have other mathematical operators available to us in Python too:\n","\n","* `-` subtraction (e.g. `4 - 2` evaluates to `2`)\n","* `*` multiplication (e.g. `3.4 * 10` evaluates to `34`)\n","* `/` exact division (e.g. `5/2` evaluates to `2.5`)\n","* `//` integer division (leaving off the decimal part, e.g. `5//2` evaluates to `2`)\n","\n","\n","\n"]},{"cell_type":"markdown","metadata":{"id":"vy71G7A8tfER"},"source":["### Example: Currency Converter \n","\n","Watch [this](https://youtu.be/kQ-_WkdO5dY) video with an explanation of this example.\n","\n","This example demonstrates how to create and update integer and float variables. The following program converts any amount (in dollars) to rupees, and displays the result. The amount is stored in a variable `amt_in_dollars`, and the conversion rate is stored in a variable, `conversion_rate`. The converted amount is stored in `amt_in_rupees` and displayed."]},{"cell_type":"code","metadata":{"id":"LZdlzMoDtpUv","colab":{"base_uri":"https://localhost:8080/","height":197},"executionInfo":{"status":"error","timestamp":1636909787321,"user_tz":480,"elapsed":338,"user":{"displayName":"Braden Monroe","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14GjWHGIVTAWJFJX-igMgPLiTl88SyYPNavFiV4MCXA=s64","userId":"14803880866214127972"}},"outputId":"973e208b-5f77-444f-b5b4-1575033cd342"},"source":["#define variables: store values in variables \n","amt_in_dollars = 20\n","conversion_rate = 74.93\n","\n","#convert dollars in rupees\n","amt_in_rupees = amt_in_dollars * conversion_rate\n","\n","print(\"$\" + amt_in_dollars + \" is Rs. \" + str(amt_in_rupees))"],"execution_count":null,"outputs":[{"output_type":"error","ename":"TypeError","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mTypeError\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 6\u001b[0m \u001b[0mamt_in_rupees\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mamt_in_dollars\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0mconversion_rate\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 8\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"$\"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mamt_in_dollars\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;34m\" is Rs. \"\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0mstr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mamt_in_rupees\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m","\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str"]}]},{"cell_type":"markdown","metadata":{"id":"Pk4qJvuM4rjB"},"source":["When we printed this time, we couldn't use the `+` operator directly between `\"$\"` and `amt_in_dollars`. That's because `\"$\"` is a string, but `amt_in_dollars` is an integer. So we had to convert the `amt_in_dollars` to a string, by using `str()` surrounding that variable.\n","\n","Do you notice that there are loads of decimal places after the decimal point in the final Rs. amount? Decimal mathematics isn't quite exact in Python, but you can see the result is pretty close."]},{"cell_type":"markdown","metadata":{"id":"QLDw0ZGXEsfZ"},"source":["### Try it out: Judge for the Olympics \n","\n","Write an Olympic Judging program that outputs the average scores from 3 different judges. Write a program with three variables for each score, called `score_a`, `score_b` and `score_C` respectively. Set the scores (out of 10) to integers of your choice, and print them one after the other. Then, calculate the average of the three scores, and print the result.\n","\n","Your output should appear like this: \n","\n","```\n","Judge 1: 10\n","Judge 2: 9\n","Judge 3: 8\n","Average Score: 9\n","```\n","\n","This example combines several concepts from previous exercises and examples. If you're unsure about how to start, break down the problem into parts that are similar to the things we've just covered.\n","\n","*Hint: calculate the **total** first (and store this in a variable) before you calculate and print your average.*"]},{"cell_type":"code","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"02VgY3iFs3zZ","executionInfo":{"status":"ok","timestamp":1635691315393,"user_tz":240,"elapsed":195,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"e4c8065b-2e0a-4bc1-e6c5-9a858f36f073"},"source":["# Write your Olympic Judging program here:\n","score_a = 7\n","print(\"Judge 1: \" + str(score_a)) \n","\n","score_b = 6.5\n","print(\"Judge 2: \" + str(score_b)) \n","\n","score_c = 8\n","print(\"Judge 3: \" + str(score_c)) \n","\n","avg = (score_a + score_b + score_c)/3\n","\n","print (\"Average Score: \" + str(avg))"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Judge 1: 7\n","Judge 2: 6.5\n","Judge 3: 8\n","Average Score: 7.166666666666667\n"]}]},{"cell_type":"markdown","metadata":{"id":"MxI-LK78lGMu"},"source":["## User Input\n","\n","Watch [this](https://youtu.be/BKT9A2N0vpU) video in preparation for this section."]},{"cell_type":"markdown","metadata":{"id":"WoMYCl8c9A4V"},"source":["\n","\n","When we run Python programs, we aren't restricted to specifying all the strings, integers and floats ourselves. We can also request input from users of your program. This is a powerful tool to make your programs flexible and personalised. AI applications frequently make use of user input to tailor an experience appropriately to a particular person."]},{"cell_type":"markdown","metadata":{"id":"998Efy5y-cdk"},"source":["### Example: A better Currency Converter\n","\n","Let's suppose that you just got back from a holiday to the US. You still have some dollar bills remaining, and you want to convert these dollars back to Rs. This program will respond to your requests and convert your money back for you. Give it a run! "]},{"cell_type":"code","metadata":{"colab":{"base_uri":"https://localhost:8080/"},"id":"fJb70YHelOAu","executionInfo":{"status":"ok","timestamp":1635681351489,"user_tz":240,"elapsed":12359,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"0059b723-2c69-491e-f3cc-a29b4b986a2f"},"source":["#ask user for name \n","name = input(\"What is your name? \" )\n","\n","\n","amt_in_dollars = input(\"Hi, \" + name + \"! How many dollars do you want to convert? \")\n","print(amt_in_dollars)\n","\n","conversion_rate = 74.93\n","\n","amt_in_rupees = float(amt_in_dollars) * conversion_rate\n","\n","print(\"$\" + amt_in_dollars + \" is Rs. \" + str(amt_in_rupees))"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["What is your name? Patrick\n","Hi, Patrick! How many dollars do you want to convert? 10\n","10\n","$10 is Rs. 691.8000000000001\n"]}]},{"cell_type":"markdown","metadata":{"id":"1-GHbmTs_T_A"},"source":["Isn't that neat? This code has read in your name, addressed you personally asking for how much money you want to convert, and performed the conversion for you.\n","\n","To get user input, we perform the following steps:\n","\n","\n","1. Come up with a variable name to store your input\n","2. Write `=`\n","3. Write `input()`\n","4. Within the parentheses, write the message that prompts the user to enter something\n","\n","By default, user input gets read in as a string. In the above example, we wanted to retrieve the dollar amount to convert from the user, but we don't want to store that as a string since we want to use it in calculations. So we need to convert it to an integer. We do this by enclosing that expression in `int()`: \n","\n","`amt_in_dollars = int(input(name + \", what dollar amount are you looking to convert? \"))`"]},{"cell_type":"markdown","metadata":{"id":"nJDueUiOmNxD"},"source":["### Try it out: A better way to Judge the Olympics\n","\n","Instead of setting the scores yourself, extend the Olympics judging program so that it asks for input from each judge, and then calculates the average of the three scores. The output should look like this:\n","\n","```\n","Judge 1, what’s your score? 10\n","Judge 2, what’s your score? 9\n","Judge 3, what’s your score? 8\n","Average score: 9\n","```\n","\n","This time, instead of storing the total in a separate variable from the average, try to jump to the average in just one step. Note that you can use parentheses to specify that you want an expression to be calculated before something else, like this:\n","\n","```\n","ans = (6 + 2 + 5) / 13\n","```\n","This way, the sum `6 + 2 + 5` gets calculated first, giving `13`. Then `13` is divided by `13` to give the answer, which is `1`. This value is stored in `ans`.\n"]},{"cell_type":"code","metadata":{"colab":{"base_uri":"https://localhost:8080/","height":528},"id":"Tlin7gBXsNZG","executionInfo":{"status":"error","timestamp":1635681821446,"user_tz":240,"elapsed":4578,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"349172e3-a88f-465d-bbc1-172fe57cebad"},"source":["# Write your Extended Olympic Judging program here: \n","score_a = input(\"Judge 1, what's your score? \")\n","score_b = input(\"Judge 2, what's your score? \")\n","score_c = input(\"Judge 3, what's your score? \")\n","sum = float(score_a) + float(score_b) + float(score_c)\n","\n","average = (sum/3)\n","print (\"Average Score: \" + str(average))"],"execution_count":null,"outputs":[{"output_type":"error","ename":"KeyboardInterrupt","evalue":"ignored","traceback":["\u001b[0;31m---------------------------------------------------------------------------\u001b[0m","\u001b[0;31mKeyboardInterrupt\u001b[0m Traceback (most recent call last)","\u001b[0;32m/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py\u001b[0m in \u001b[0;36m_input_request\u001b[0;34m(self, prompt, ident, parent, password)\u001b[0m\n\u001b[1;32m 728\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 729\u001b[0;31m \u001b[0mident\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mreply\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0msession\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrecv\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mstdin_socket\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;36m0\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 730\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/usr/local/lib/python3.7/dist-packages/jupyter_client/session.py\u001b[0m in \u001b[0;36mrecv\u001b[0;34m(self, socket, mode, content, copy)\u001b[0m\n\u001b[1;32m 802\u001b[0m \u001b[0;32mtry\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 803\u001b[0;31m \u001b[0mmsg_list\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0msocket\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrecv_multipart\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mmode\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcopy\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcopy\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 804\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mzmq\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mZMQError\u001b[0m \u001b[0;32mas\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/usr/local/lib/python3.7/dist-packages/zmq/sugar/socket.py\u001b[0m in \u001b[0;36mrecv_multipart\u001b[0;34m(self, flags, copy, track)\u001b[0m\n\u001b[1;32m 624\u001b[0m \"\"\"\n\u001b[0;32m--> 625\u001b[0;31m \u001b[0mparts\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m[\u001b[0m\u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mrecv\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mflags\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcopy\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mcopy\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mtrack\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mtrack\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m]\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 626\u001b[0m \u001b[0;31m# have first part already, only loop while more to receive\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32mzmq/backend/cython/socket.pyx\u001b[0m in \u001b[0;36mzmq.backend.cython.socket.Socket.recv\u001b[0;34m()\u001b[0m\n","\u001b[0;32mzmq/backend/cython/socket.pyx\u001b[0m in \u001b[0;36mzmq.backend.cython.socket.Socket.recv\u001b[0;34m()\u001b[0m\n","\u001b[0;32mzmq/backend/cython/socket.pyx\u001b[0m in \u001b[0;36mzmq.backend.cython.socket._recv_copy\u001b[0;34m()\u001b[0m\n","\u001b[0;32m/usr/local/lib/python3.7/dist-packages/zmq/backend/cython/checkrc.pxd\u001b[0m in \u001b[0;36mzmq.backend.cython.checkrc._check_rc\u001b[0;34m()\u001b[0m\n","\u001b[0;31mKeyboardInterrupt\u001b[0m: ","\nDuring handling of the above exception, another exception occurred:\n","\u001b[0;31mKeyboardInterrupt\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;31m# Write your Extended Olympic Judging program here:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 2\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 3\u001b[0;31m \u001b[0mscore_a\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Judge 1, what's your score? \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 5\u001b[0m \u001b[0mscore_b\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0minput\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Judge 2, what's your score? \"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py\u001b[0m in \u001b[0;36mraw_input\u001b[0;34m(self, prompt)\u001b[0m\n\u001b[1;32m 702\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_parent_ident\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 703\u001b[0m \u001b[0mself\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0m_parent_header\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 704\u001b[0;31m \u001b[0mpassword\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m,\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 705\u001b[0m )\n\u001b[1;32m 706\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;32m/usr/local/lib/python3.7/dist-packages/ipykernel/kernelbase.py\u001b[0m in \u001b[0;36m_input_request\u001b[0;34m(self, prompt, ident, parent, password)\u001b[0m\n\u001b[1;32m 732\u001b[0m \u001b[0;32mexcept\u001b[0m \u001b[0mKeyboardInterrupt\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 733\u001b[0m \u001b[0;31m# re-raise KeyboardInterrupt, to truncate traceback\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 734\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mKeyboardInterrupt\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 735\u001b[0m \u001b[0;32melse\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 736\u001b[0m \u001b[0;32mbreak\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n","\u001b[0;31mKeyboardInterrupt\u001b[0m: "]}]},{"cell_type":"markdown","metadata":{"id":"N0iZS9dBC8k2"},"source":["## Conditionals\n","\n","Watch [this](https://youtu.be/jkM2dfuHeu4) video in preparation for this exercise.\n","\n","In all the programs above, we have a fixed order in which things will happen. For instance, with our judge scores above, we know that we will be taking in input from 3 judges, calculating the average and printing it out.\n","\n","However, we might want to specify some alternative ways in which a program could run. In plain English, this means something like:\n","\n","\"if something is the case, execute the program in one particular way; otherwise do it another way\"\n","\n","We can achieve this in Python by using **Boolean** variables. A Boolean is another type of variable that can take on just two values: `True` and `False`. "]},{"cell_type":"markdown","metadata":{"id":"M0s5cBa9GD0d"},"source":["### Example: Self-Driving Car at a Traffic Light\n","\n","We're sitting in a nice Tesla that is approaching a traffic light. The Tesla is looking out to see whether the green light is illuminated."]},{"cell_type":"code","metadata":{"id":"plfnn9dYuTxH","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1635691432033,"user_tz":240,"elapsed":183,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"4503212a-43db-49df-b1d8-fe3208e13b37"},"source":["# We define a new Boolean variable called green_light \n","# In this case, the green light is illuminated, so we set the variable to True\n","green_light = True\n","\n","if green_light: #<- single variable\n"," print(\"Good to go!\")\n","else: \n"," print(\"Don't go yet...\")"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Good to go!\n"]}]},{"cell_type":"markdown","metadata":{"id":"N-4vV-kGHAji"},"source":["Nice, our Tesla can sail through the green light with no problems. But now we're approaching another traffic light that is not green:"]},{"cell_type":"code","metadata":{"id":"I31ZNrO0HJ5s","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1635691465407,"user_tz":240,"elapsed":329,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"d2a0052b-536d-475b-8a22-979bf8b47e6f"},"source":["# In this case, we're approaching a red light, so we set the variable to False\n","green_light = False\n","\n","if green_light: \n"," print(\"Good to go!\")\n","else: \n"," print(\"Don't go yet...\")"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["Don't go yet...\n"]}]},{"cell_type":"markdown","metadata":{"id":"CqQMCBj2HV1A"},"source":["Notice above that each `print()` statement above is indented and preceded by one of two lines:\n","\n","```\n","if green_light:\n","```\n","or\n","```\n","else:\n","...\n","```\n","\n","When you write `if`, Python checks to see whether the variable or expression after it evaluates to `True`. If it does, then the indented code after it will execute, and Python will skip the indented code after the `else`. If it evaluates to `False`, then the indented code after the `if` statement is skipped, and the indented code after `else` will execute. The examples above show both of these in action.\n","\n","Note that when using `if` and `else` statements, you need to end each of these lines with a colon (`:` ) and indent the subsequent code with a tab."]},{"cell_type":"markdown","metadata":{"id":"0VEEKk8CkoYU"},"source":["## Comparison operators: `==, !=, >, <, >=, <=`\n","\n","So far, we've been setting variables directly to Boolean values. Sometimes, however, we want to compare other values or expressions to each other. To do this, we can use **comparison operators**. \n","\n","There are six main types of comparison operator:\n","\n","1. `==` checks to see if two values/expressions are equal\n","2. `!=` checks to see if two values/expressions are not equal\n","3. `>` checks to see if the left-hand value/expression is greater than the right-hand value/expression\n","4. `<` checks to see if the left-hand value/expression is less than the right-hand value/expression\n","5. `>=` checks to see if the left-hand value/expression is greater than or equal to the right-hand value/expression\n","6. `<=` checks to see if the left-hand value/expression is less than or equal to the right-hand value/expression\n","\n","If the comparison condition is satistfied, the whole expression will evaluate to `True`. If it's not, the whole expression evaluates to `False`.\n","\n","Let's take a look at some simple examples of this. Run the following cell and examine the outputs:"]},{"cell_type":"code","metadata":{"id":"pFQfeN1inQlB","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1635691820336,"user_tz":240,"elapsed":198,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"01a33815-9a92-4148-f69f-a9221301b3ec"},"source":["# Define a variable called test\n","test = 2\n","\n","# Let's see if test is equal to 2, and print out the result\n","result = test == 2\n","print(result)\n","\n","# Let's see if test is greater than or equal to 4, and print out the result.\n","# This time, we're going to do it all in one line\n","print(test >= 4)\n","\n","# Finally, let's see if the result of 3 - test is not equal to the result of test/2.\n","print(3 - test != test/2)"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["True\n","False\n","False\n"]}]},{"cell_type":"markdown","metadata":{"id":"SiduqIyXoLYM"},"source":["Comparison operators also work on strings, as you can see below if you run the cell. This program combines the comparison operators with an `if` statement to get some different outputs. Will anything be printed out in this case?"]},{"cell_type":"code","metadata":{"id":"DtHeOXtVhYyF"},"source":["# Define a test string\n","test_string = \"hello\"\n","\n","# Will anything be printed here?\n","if test_string == \"pink\":\n"," print(\"The test string is pink\")"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"YJxyjt9Lv5C4"},"source":["Here, since we didn't specify an alternative output to print out, nothing gets printed. It's fine not to have an `else` statement if you don't want it!"]},{"cell_type":"markdown","metadata":{"id":"NKorZAoBhdPt"},"source":["**For Fun**"]},{"cell_type":"code","metadata":{"id":"cBLughVGoWQl","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1635691920319,"user_tz":240,"elapsed":7182,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"3486b24e-817a-442d-d9a1-f6414eb23c79"},"source":["# Define a test string\n","test_string = input(\"hello, what colour is the test string? \")\n","\n","# Will anything be printed here?\n","if test_string == \"pink\":\n"," print(\"The test string is pink\")\n","\n","else: \n"," print(\"you are incorrect\")"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["hello, what colour is the test string? pink\n","The test string is pink\n"]}]},{"cell_type":"code","metadata":{"id":"ZBZxLnCTiBSc","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1635691931912,"user_tz":240,"elapsed":4382,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"0678a79a-0333-4cd5-cb7e-58442dc36ad0"},"source":["# Define a test string\n","test_string = input(\"hello, what colour is the test string? \")\n","\n","# Will anything be printed here?\n","result = test_string == \"pink\"\n","print(result)"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["hello, what colour is the test string? pink\n","True\n"]}]},{"cell_type":"markdown","metadata":{"id":"liKM-vZIpfOh"},"source":["## Now you try!"]},{"cell_type":"markdown","metadata":{"id":"hq73OZ5GptOi"},"source":["**Write** two expressions of your own, with the first one evaluating to `True` and the second one evaluating to `False`. Print out the values of your expressions as you go."]},{"cell_type":"code","metadata":{"id":"apqxIhF7pq4F","outputId":"71c4bf4f-e20a-448a-91d4-8e1d841e55f6"},"source":["# Write your first expression here\n","test = 4 \n","\n","result = test >= 1 \n","print(result)\n","\n","result = test<=2\n","print(result)\n","\n","# Write your second expression here"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["True\n","False\n"]}]},{"cell_type":"markdown","metadata":{"id":"rLLB9mKwrMIQ"},"source":["## Controlling the traffic lights\n","\n","Remember the self-driving car example from before? It was pretty good, but we want to make it better. There, we only specified whether or not a light was green, but there are actually two alternatives for when a light is not green: it could be red or yellow.\n","\n","This time, we're going to let a user input what colour they want the traffic light to be. Then we'll tell the Tesla what it needs to do depending on the colour of the light that was entered."]},{"cell_type":"code","metadata":{"id":"SQ2uiLJkspI8"},"source":["# Get user input about the traffic light colour\n","light = input(\"What colour is the traffic light? \")\n","\n","# Don't worry about this line; it's just formatting the string so that there's\n","# no extra whitespace at the ends and it's all in lower case\n","light = light.lower().strip()\n","\n","# Tell the car what it needs to do based on the colour of the light\n","if light == \"red\": \n"," print(\"Don't go yet... \")\n","elif light == \"yellow\":\n"," print(\"Get ready to go... \")\n","elif light == \"green\":\n"," print(\"Good to go!\")\n","else:\n"," print(\"Huh?\")"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"lkOmgMeLv3Hd"},"source":["This example is a little more involved than before. There are two main things to notice here:\n","\n","\n","1. The above program uses the word `elif`. This is useful if you have multiple conditions you want to check. `if`/`else` on their own is fine if there's just one condition you want to check, but here we're seeing if the light is red, yellow or green.\n","2. The final `else` statement might seem unnecessary, but we've included it in case the user enters something other than red, yellow or green. If a Tesla saw a purple light, it might be confused!\n","\n"]},{"cell_type":"markdown","metadata":{"id":"UjyGTyglxG1e"},"source":["## Logical operators: `and`, `or`, `not`\n","\n","In the above examples, we were only checking one expression at a time. But sometimes we want to check more than one at once, or negate some expression that we've already checked. There are three keywords in Python for this:\n","\n","\n","1. `and` checks if both the left-hand and right-hand expressions are `True`. If they are, the whole expression evaluates to `True`; otherwise it evaluates to `False`.\n","\n","2. `or` checks if either the left-hand or right-hand expressions are `True` (or both of them). If at least one of these expressions evaluates to `True`, then the whole expression evaluates to `True`; otherwise it evaluates to `False`.\n","\n","3. `not` will reverse the value of whatever expression we are checking. So `not True` is the same as `False`, and `not False` is the same as `True`.\n","\n","Run the cell below to see the results of each of the expressions within."]},{"cell_type":"code","metadata":{"id":"WBh9TwOQ6xSG"},"source":["# Define some Booleans\n","bool_a = 2 * 3 == 6 \n","bool_b = 9 - 4 != 5 \n","\n","print(bool_a)\n","\n","print(bool_b)\n","\n","# Expression 1\n","print(bool_a and bool_b)\n","\n","# Expression 2\n","print(bool_a or bool_b)\n","\n","# Expression 3\n","print(not bool_b)"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"-Kg-TBkI0mS-"},"source":["## Loops\n","\n","To motivate the need for while loops, let's re-visit the if-condition. Recall that an `if` statement allows you to do something UNLESS a condition is `False`. If the condition is `False`, nothing is executed. What if we want to do something UNTIL a condition becomes `False`? This is exactly what loops are for: to execute a particular task repeatedly until some condition no longer holds `True`. \n","\n","Watch [this](https://youtu.be/ckltZHCqNnA) video in preparation for this topic."]},{"cell_type":"markdown","metadata":{"id":"V4oGzvQS05Gu"},"source":["## While loops: A personalized Self-Driving Car\n","\n","Let's explore this with an example. Let’s go back to our self-driving Tesla, but this time, let's personalize it. Suppose that our Tesla (let's call it *Jarvis*), only starts when the user summons it with a command, say \"*Jarvis, energize!*\". If we don’t enter that command, the car doesn’t start. We know this can be programmed with a simple `if` condition, like so: "]},{"cell_type":"code","metadata":{"id":"7pWsULq03k9d","outputId":"02644562-8714-4fe9-a542-b901b3d16ff9"},"source":["# Define the predetermined summon in a variable\n","summon = \"Jarvis, energize!\"\n","\n","# Ask the user for the command\n","command = input(\"What’s your command? \")\n","\n","# Tell the car what to do based on the correctness of the command\n","if command == summon:\n"," print(\"Your wish is my command!\")\n","else: \n"," print(\"Sorry, I don’t understand.\")"],"execution_count":null,"outputs":[{"name":"stdin","output_type":"stream","text":["What’s your command? Jarvis, energize!\n"]},{"name":"stdout","output_type":"stream","text":["Your wish is my command!\n"]}]},{"cell_type":"markdown","metadata":{"id":"Xk9njZY44Num"},"source":["… Now, instead of just giving the user a single try, what if we want to let the user keep guessing until they guess correctly?\n","\n","We can do that with something called a `while` loop. Take a look at this program, and give it a whirl: \n","\n"]},{"cell_type":"code","metadata":{"id":"OI5jHY3q4p6M","outputId":"84390d81-62cd-44d4-91d9-2d950931637b"},"source":["# Define the predetermined summon in a variable\n","summon = \"Jarvis, energize!\"\n","\n","# Ask the user for the command\n","command = input(\"What’s your command? \")\n","\n","# While the command isn't the summon we're looking for... then execute the indented block\n","while command != summon: \n"," print(\"Sorry, I don't understand.\") \n"," command = input(\"What's your command? \")\n"," \n","# This line of code will only execute when the loop is finished, i.e., when command is the predetermined summon\n","# Note how this line is NOT indented like the statements inside the while-loop\n","#will exit the loop when command == summon\n","print(\"Your wish is my command!\")"],"execution_count":null,"outputs":[{"name":"stdin","output_type":"stream","text":["What’s your command? Jarvis!\n"]},{"name":"stdout","output_type":"stream","text":["Sorry, I don't understand.\n"]},{"name":"stdin","output_type":"stream","text":["What's your command? Jarvis!\n"]},{"name":"stdout","output_type":"stream","text":["Sorry, I don't understand.\n"]},{"name":"stdin","output_type":"stream","text":["What's your command? Jarvis, energize!\n"]},{"name":"stdout","output_type":"stream","text":["Your wish is my command!\n"]}]},{"cell_type":"markdown","metadata":{"id":"_mr0HZ516N73"},"source":["In simple English, the `while` loop can be translated as: \"Until `command` is not the same as `summon`, ask user for input.\"\n","\n","Here's what a `while` loop looks like: \n","```\n","while condition\n"," ... do something ... \n"," ```\n","It looks a lot like an `if` statement. The only difference is the word \"while\" in place of the word \"if\". The condition still has to be something that evaluates to a boolean. The code under the `while` loop is the body. If the condition is `True`, it executes. \n","\n","EVERY TIME it executes, the condition is checked again. Unless the condition has become `False`, the body runs again."]},{"cell_type":"markdown","metadata":{"id":"hw_tTwE7-wRp"},"source":["## Try it out: Free tickets for the IPL \n","\n","You just landed 20 tickets for the IPL finals and generously want to give it away. With your recently acquired programming chops, you decide to write a program that keeps track of the tickets you have left. While there are still tickets left with you, ask the user how many tickets they would like to buy. Then print out how many are left with you after the purchase.\n"," \n","Bonus points if your program can catch the case where your user tries to buy more tickets than you have left with you. In that case, you should print a message to the yser saying that their request isn’t possible. \n","\n","Here's an example of what one run of the program might appear like: \n","\n","```\n","I'm giving away free tickets for the IPL. \n","\n","How many do you need? 5 \n","Great! I have 15 tickets left. \n","\n","How many do you need? 17\n","Sorry, I don't have that many. \n","\n","How many tickets do you need? 15\n","Great! I have 0 tickets left. \n","\n","All sold out!\n","```\n"]},{"cell_type":"markdown","metadata":{"id":"PuSx33yMuHXc"},"source":["Hints:\n","* You can set a `while` loop header condition to *anything* that evaluates to a Boolean. In this case, we want to make sure that there are still tickets left. This means that we'll want to compare the ticket count to something. What will this comparison look like?\n","* Suppose that you store the number of tickets that someone requests in a variable called `tickets`. Then after that value is stored, you can subtract it from `tickets_left` to figure out the new number of remaining tickets. This updated value will then get checked again in the next run of the while loop."]},{"cell_type":"markdown","metadata":{"id":"Y4SjoSCit3Tk"},"source":["### Enter your code below"]},{"cell_type":"code","metadata":{"id":"SdAMVtvreaur","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1637470059955,"user_tz":480,"elapsed":6794,"user":{"displayName":"Sam Scarborough","photoUrl":"https://lh3.googleusercontent.com/a-/AOh14Ghk5loPmSbpeoTj0WqLVWGK-2gSQlGreDneEmgK=s64","userId":"18324888543492053717"}},"outputId":"ecd86f35-f21f-4981-fc5d-76f0119d3360"},"source":["# Complete the IPL ticket-giveaway program. \n","print(\"I'm giving away free tickets for the IPL\")\n","\n","total = 21\n","request = input(\"How many tickets do you need? \")\n","\n","while float (request) >= total: \n"," print(\"Sorry, I don't have that many\")\n"," request = input(\"How many tickets would you like to request now? \")\n","\n","sum = total - 1 - int(request)\n","\n","print(\"Great, I have \" + str(sum) + \" tickets left\")"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["I'm giving away free tickets for the IPL\n","How many tickets do you need? 3\n","Great, I have 17 tickets left\n"]}]},{"cell_type":"markdown","metadata":{"id":"srLwyhk9Djkh"},"source":["## For loops\n","\n","A while loop works well when we don't know in advance how many times we will have to do something. But what if we know exactly how many times you'll have to do something?\n","\n","We can use a `for` loop! Here's an example of what it looks like. \n","\n","Watch [this](https://youtu.be/jBVv-5UuFQc) video in preparation for this topic."]},{"cell_type":"code","metadata":{"id":"WHx66S3UHNMO","outputId":"21d5f4f3-6d85-4d41-c9f6-4950e5fab348"},"source":["for i in range(4): \n"," # Do this 4 times\n"," print(\"This is iteration number: \" + str(i))"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["This is iteration number: 0\n","This is iteration number: 1\n","This is iteration number: 2\n","This is iteration number: 3\n"]}]},{"cell_type":"markdown","metadata":{"id":"2aYA1T5hHZZV"},"source":["A `for` loop consists of three main things: \n","* You say \"`for i in range`\"\n","* An integer in parentheses, which is the number of times you want to do something\n","* The indented code, called body, which will execute repeatedly"]},{"cell_type":"markdown","metadata":{"id":"iwMKMB78nsvp"},"source":["### Example: A more secure Self-Driving Car \n","\n","Our friend at Tesla, Elon Musk, just told us it isn’t safe to let the user have unlimited go’s at guessing the command. He recommends we give the user only five tries to guess the command. Let’s see how we might use our handy-dandy `for` loop here: "]},{"cell_type":"code","metadata":{"id":"2TNFWR9gn9on","outputId":"82ab3e47-9446-4093-e932-bf30ce0bc42a"},"source":["# Define the predetermined summon in a variable\n","summon = \"Jarvis, energize!\"\n","\n","# Try the command five times\n","for i in range(5): \n"," command = input(\"What’s your command? \")\n"," if command == summon:\n"," print(\"Your wish is my command!\")\n"," break\n"," else: \n"," print(\"Sorry, I don’t understand!\")"],"execution_count":null,"outputs":[{"name":"stdin","output_type":"stream","text":["What’s your command? Jarvis, energize!\n"]},{"name":"stdout","output_type":"stream","text":["Your wish is my command!\n"]}]},{"cell_type":"code","metadata":{"id":"zDSBTuU84oJ9","outputId":"4d590581-591e-4379-dbce-78007234b22f"},"source":["for i in range(4):\n"," command = input(\"what's up\")"],"execution_count":null,"outputs":[{"name":"stdin","output_type":"stream","text":["what's up 1\n","what's up 2\n","what's up a\n","what's up b\n"]}]},{"cell_type":"markdown","metadata":{"id":"iYXMPBbmo-s8"},"source":["Notice a new `break` statement in the `if` condition? When the condition is `True`, the break statement skips the entire loop even before it finishes all its iterations. In the above program, it ensures that the user is not asked to give the command again if they've gotten it right before the first five tries."]},{"cell_type":"markdown","metadata":{"id":"dx76IiuieRn3"},"source":["### Try it out: Judging for the Olympics v3 \n","\n","Remember the Olympics Judging program from earlier? Re-write it with a for-loop. As a reminder, the program asks a score from each of the three judges, and then calculates the average. The output looks like this: \n","\n","```\n","Judge 1, what’s your score? 10\n","Judge 2, what’s your score? 9\n","Judge 3, what’s your score? 8\n","The average score is 9. \n","\n","```\n","\n"]},{"cell_type":"code","metadata":{"id":"VnklZEgbeYR7"},"source":["# Write your new version of the Olympics Judging program with for loops here.\n"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"87_LZVcq1TeU"},"source":["## Lists\n","\n","Watch [this](https://youtu.be/da8cmMaZ_8E) video in preparation for this topic.\n","\n","Another common data type is lists. You can think of lists as storing multiple variables, or a collection of variables, in one place. It's also important to note that the variables are in a particular order and are each assigned an index in the list. "]},{"cell_type":"code","metadata":{"id":"higKQZtE2DAY","colab":{"base_uri":"https://localhost:8080/"},"executionInfo":{"status":"ok","timestamp":1636913570792,"user_tz":300,"elapsed":9,"user":{"displayName":"Patrick Funk","photoUrl":"https://lh3.googleusercontent.com/a/default-user=s64","userId":"06363259130993623477"}},"outputId":"c334a616-d5b0-4e17-aff3-628567a9eb43"},"source":["# Let's create a grocery list for when we go to the store\n","groceries = []\n","groceries.append('apples')\n","groceries.append('milk')\n","groceries.append('bread')\n","groceries.append('cheese')\n","\n","\n","\n","for var, item in enumerate(groceries):\n"," print(item + ' is at index: ' + str(var))"],"execution_count":null,"outputs":[{"output_type":"stream","name":"stdout","text":["apples is at index: 0\n","milk is at index: 1\n","bread is at index: 2\n","cheese is at index: 3\n"]}]},{"cell_type":"markdown","metadata":{"id":"6sRqp6-ty_ZA"},"source":["## Try it out: Best Foot Forward\n","You’re applying to Stanford and you realize you want to submit only the best score from all your attempts at the SAT. The scores from all the attempts is stored in a list, called `scores`. Write a program that traverses the list and then prints the highest score from the list. \n","\n","**Note**: Do not use the built-in function `max` in your program!"]},{"cell_type":"code","metadata":{"id":"YdtnOAaPy-x7"},"source":["# Complete this program to find and print the highest score from the list\n"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"Z3fkjPLaqsHg"},"source":["## Functions\n","\n","Watch [this](https://youtu.be/_vCWEAZLXXs) video in preparation for this topic.\n","\n","A Python function is similar to how we think of functions in math. You've actually already made use of functions earlier-- `range`, `input` and `append` are all examples of functions. You can think of these as pre-defined functions in Python that can be called for various uses. Now, you'll learn how to make your own functions.\n","\n","Let's say you're building a chatbot, Jarvis, which needs to greet the user every time it's summoned, like so:"]},{"cell_type":"code","metadata":{"id":"OHKWTDRRBZRA","outputId":"af0682aa-ef43-463c-8358-6e93853883a3"},"source":["print(\"Hi!\")\n","print(\"Allow me to introduce myself. I'm Jarvis, and I can call and mesage people for you. I can also share a joke or two.\")\n","print(\"What can I help you with?\")"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["Hi!\n","Allow me to introduce myself. I'm Jarvis, and I can call and mesage people for you. I can also share a joke or two.\n","What can I help you with?\n"]}]},{"cell_type":"markdown","metadata":{"id":"3XpSjoulDNzk"},"source":["Every time a user summons Jarvis, we call these three lines of code. Even if Jarvis is summoned 3-4 times, that's a lot of lines of code required. Instead, we can assign these lines of code to a `function`. We'll call the function `greeting`, and define it in the following way. \n","\n","Every function you define contains the word `def`, the name of your function, a pair of parenthses, and a colon, followed by some code underneath. When we define a function, nothing actually happens in the console. Try this:"]},{"cell_type":"code","metadata":{"id":"fSI9u8E3FmkD"},"source":["def greeting(): \n"," print(\"Hi!\")\n"," print(\"Allow me to introduce myself. I'm Jarvis, and I can call and mesage people for you. I can also share a joke or two.\")\n"," print(\"What can I help you with?\") "],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"_5SX8EKeGKYK"},"source":["At this point, we have merely taught Jarvis how to print a greeting. Now we have to tell Jarvis to actually do it, and we do this by calling the function, like so:"]},{"cell_type":"code","metadata":{"id":"2UuaZo-qGVGd","outputId":"72cd619f-5efe-47dc-c525-dc82c00a6932"},"source":["greeting()"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["Hi Alex!\n"]}]},{"cell_type":"markdown","metadata":{"id":"XQBUr90cHHVq"},"source":["Each time we call it, the code in the function gets executed. This is part of why functions are valuable. They allow us to save some code for later, and then use and re-use it without typing it out each time.\n","\n","## Variable Scope in Functions (optional)\n","\n","For the purpose exploring functions further, let's use a shorter greeting and add the user's name to it. Then we can declare a variable with the name, like we normally would."]},{"cell_type":"markdown","metadata":{"id":"Kc7Dixf6IlNq"},"source":["But watch out, if you do this, the variable `name` is only available within the function. If you try to use `name` outside the function, it causes an error. Do you see an error when you run this program?"]},{"cell_type":"code","metadata":{"id":"tf07EEMBIeaf","outputId":"6334b6ea-5c00-401b-f771-7ea64e5bc8a0"},"source":["def greeting(): \n"," name = \"Arya\"\n"," print(\"Hi \" + name + \"!\") \n"," \n","greeting()\n","print(name)"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["Hi Arya!\n","Yin\n"]}]},{"cell_type":"markdown","metadata":{"id":"2qYfeoApJMxm"},"source":["But here's where Python gets a little funky. If you declare the variable OUTSIDE a function, you can still access it INSIDE the function. Take a look at this:\n"]},{"cell_type":"code","metadata":{"id":"bC-BRSDBItU8","outputId":"1acaa706-21f7-4e34-9f7c-5ab540420bb5"},"source":["name = \"Arya\"\n","\n","def greeting(): \n"," print(\"Hi \" + name + \"!\")\n"," \n","greeting()\n","print(name)"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["Hi Arya!\n","Arya\n"]}]},{"cell_type":"markdown","metadata":{"id":"tfpyxxy4JgGV"},"source":["Here's another place where Python gets REALLY funky. If a variable is declared outside a function, and you try to CHANGE it inside the function, you actually create ANOTHER variable of the same name! In this example, there are two variables called `name`. One of them lives inside `greeting`, and the other lives outside of it. Run this code and see what happens."]},{"cell_type":"code","metadata":{"id":"pHDPFzZPJY7O","outputId":"a11db91a-1f8d-46ec-ae44-c856ecdf4ab3"},"source":["name = \"Arya\"\n","\n","def greeting():\n"," name = \"Alex\"\n"," print(\"Hi \" + name + \"!\")\n"," \n","greeting() # This print statement will refer to the version of name inside greeting()\n","print(name) # This print statement will refer to the version of name on the first line"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["Hi Alex!\n","Arya\n"]}]},{"cell_type":"markdown","metadata":{"id":"BITv9AWDL8Z_"},"source":["## Functions with Parameters\n","\n","Watch [this](https://youtu.be/wHiMhywV8j0) video in preparation for this topic.\n","\n","As it stands now, functions are pretty limited; they always do the same thing. The function `greeting` always greets Arya.\n","\n","We can make a function behave differently by re-assigning the variable `name` each time, but that would be annoying. Fortunately, there's a better way to do this, and it exists in the form of **parameters**, which are pieces of information you can give the function when you call them. \n","\n","A parameter is basically a variable name. You put the variable name in the function's parentheses, and you can then use the name in the function as though it were a variable you declared."]},{"cell_type":"code","metadata":{"id":"m7tWzdhkL_Xl"},"source":["def greeting(name): \n"," print(\"Hi \" + name + \"!\")"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"FtFb-88eOwdK"},"source":["But where does this variable get its value from?\n","\n","You actually give the variable a value when you call the function, like the following lines of code. Give it a whirl, what do you get?\n"]},{"cell_type":"code","metadata":{"id":"hmSm7QnhO8gb","outputId":"d19c87ba-1457-46ab-eee2-b6a48f55c91c"},"source":["greeting(\"Arya\")\n","greeting(\"Alex\")\n","greeting(\"Adi\")"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["Hi Arya!\n","Hi Alex!\n","Hi Adi!\n"]}]},{"cell_type":"markdown","metadata":{"id":"zzJ0rkydPyrJ"},"source":["Functions can also have **multiple** parameters. Let's say we want to print the current temperature with the greeting. Then the provide the paramters in paretheses, separated by commas."]},{"cell_type":"code","metadata":{"id":"CjtVvXorPl8n","outputId":"eaefb85f-0973-48d4-c984-1ff7c1b723bc"},"source":["# Function definition includes two parameters for name and temp\n","def greeting(name, temp): \n"," print(\"Hi \" + name + \"!\")\n"," print(\"It's \" + str(temp) + \" degree celsius today.\")\n","\n","# While calling the function, we provide the values for BOTH parameters\n","greeting(\"Arya\", 21)\n","greeting(\"Alex\", 37)"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["Hi Arya!\n","It's 21 degree celsius today.\n","Hi Alex!\n","It's 37 degree celsius today.\n"]}]},{"cell_type":"markdown","metadata":{"id":"3fcjs9xRUVqZ"},"source":["## Functions with Return Values\n","\n","When you write a function, you have the option of making it return a value. Here's an example of a function that returns a `string variable` with a greeting. \n","\n","Run the program. Notice how the first print statement is empty, and the second print statement prints the string returned by the `greeting` function."]},{"cell_type":"code","metadata":{"id":"vUPmszQhW5ix","outputId":"5234a06b-6028-445f-8de6-fa42e829711e"},"source":["# Defining a function that returns a greeting string \n","def greeting(name): \n"," return \"Hey \" + name + \"!\"\n","\n","# Here, a variable is declared and printed\n","my_greeting = \"\"\n","print(my_greeting)\n","\n","# Here, the variables is assigned to the value returned by the greeting function\n","my_greeting = greeting(\"Arya\")\n","print(my_greeting)"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["\n","Hey Arya!\n"]}]},{"cell_type":"markdown","metadata":{"id":"Kl6SojLhd0LU"},"source":["## Try it out: Can you predict what Dory sings? (optional)\n","\n","*Finding Dory* is an amazing film! Dory, the friendly but forgetful blue tang fish, often sings a song to herself and her friends to keep motivation high when they are feeling lost. The following program prints out what Dory sings. **Without running the program, can you predict its output?** "]},{"cell_type":"code","metadata":{"id":"euCyitMOZEpL","outputId":"45b7764a-4035-4013-a252-d90d615df01b"},"source":["def sing_song(friend, quote):\n"," song = \"I sing for \" + friend + \": \"\n"," for i in range(3): \n"," song = song + quote\n"," return song\n","\n","def sing_for_all(quote): \n"," friends = [\"Nemo\", \"Marlin\", \"Destiny\"]\n"," song = \"\"\n"," for friend in friends: \n"," print(song + sing_song(friend, quote))\n"," \n","sing_for_all(\"Just keep swimming. \")\n"],"execution_count":null,"outputs":[{"name":"stdout","output_type":"stream","text":["I sing for Nemo: Just keep swimming. Just keep swimming. Just keep swimming. \n","I sing for Marlin: Just keep swimming. Just keep swimming. Just keep swimming. \n","I sing for Destiny: Just keep swimming. Just keep swimming. Just keep swimming. \n"]}]},{"cell_type":"markdown","metadata":{"id":"BkmSWh9Lh1ju"},"source":["Now run the program and compare your solution to the output. How did you do? :)"]},{"cell_type":"markdown","metadata":{"id":"rBCUCuQUma7X"},"source":["## Try it out: Turn up the temperature\n","\n","You're probably used to reading the temperature in Celsius units. Unfortunately, your soon-to-be friends from Stanford don't understand Celsius; they are only used to Farenheit. To make any discussion about weather easier with them, write a program that helps you convert the temperature between the Celsius and Farenheit: \n","\n","1. Write a function called `c_to_f` that takes an input `c_temp`, a temperature in Celsius, and converts it to `f_temp`, that temperature in Fahrenheit. It should then return `f_temp`. The equation you should use is: \n","\n","> $F = (1.8 * C) + 32$\n","\n","\n","2. Let’s test your function with a value of 0 Celsius. Print out your output.\n","\n"]},{"cell_type":"code","metadata":{"id":"DycsOkuspAXe"},"source":["# Define your function here\n","\n","# Call your function and print output here\n"],"execution_count":null,"outputs":[]},{"cell_type":"markdown","metadata":{"id":"erdiMaacuYLr"},"source":["# CONGRATULATIONS!\n","Well done for finishing this notebook! If you have any remaining questions, be sure to ask them when you get to the camp. We are excited to meet you!"]}]}