{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's take a look at the exercise that we worked on earlier, where we had to compute the cost of a meal, after tax and tip.\n", "\n", "Assuming that we have a cost of food of $100, NY Sales Tax of 8.875% and a tip of 20%, the calculation is:" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The cost of the meal will be:\n", "128.875\n" ] } ], "source": [ "print(\"The cost of the meal will be:\")\n", "print(100 + 100 * 8.875 / 100 + 100 * 20 / 100)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's say now that we want to update the cost of food to be $75. You will notice that we need to go to multiple places in the expression and modify the value that corresponds to the cost of the food." ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The cost of the meal will be:\n", "96.65625\n" ] } ], "source": [ "print(\"The cost of the meal will be:\")\n", "print(75 + 75 * 8.875 / 100 + 75 * 20 / 100)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "By using variables, we can assign a mnemonic name to each value, and use the name instead of the value itself.\n", "\n", "Let's use variables for the cost of the food, the tax, and the tip. We can also assign the cost of the meal to another variable, calculated using the other variables." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The cost of the meal will be:\n", "96.65625\n" ] } ], "source": [ "food = 75\n", "tax = 8.875 / 100\n", "tip = 20 / 100\n", "cost = food + food * tax + food * tip\n", "print(\"The cost of the meal will be:\")\n", "print(cost)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Variable names\n", "\n", "In Python, a variable can be named almost anything, according to the whims of the programmer. \n", "\n", "Variable names can be arbitrarily long. They can contain both letters and numbers, but they cannot start with a number. It is legal to use uppercase letters, but it is a good idea to begin variable names with a lowercase letter. The underscore character (_) can appear in a name. It is often used in variables names with multiple words, such as `my_name` or `airspeed_of_airplace`. Variable names can also start with an underscore character, but we generally avoid doing this unless we are writing library code for others to use.\n", "\n", "Variables are declared by stating the variable name and assigning to it using the \"=\" operator. At any time, you can reassign a value to a variable." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "17\n" ] } ], "source": [ "n = 17\n", "print(n)" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "3.141592653589793\n" ] } ], "source": [ "pi = 3.1415926535897931\n", "print(pi)" ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "I love Python...\n", "I love Python...\n", "I love Python...\n", "I love Python...\n" ] } ], "source": [ "message = \"I love Python...\"\n", "print(message)\n", "print(message)\n", "print(message)\n", "print(message)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Percentage of men:\n", "41.17647058823529\n" ] } ], "source": [ "males = 7\n", "females = 10\n", "fraction = males / (males + females)\n", "print(\"Percentage of men:\")\n", "print(100 * fraction)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Updating Variable Values" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's revisit our meal cost calculation code:" ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The cost of the meal will be:\n", "96.65625\n" ] } ], "source": [ "food = 75\n", "tax = 8.875 / 100\n", "tip = 20 / 100\n", "cost = food + food * tax + food * tip\n", "print(\"The cost of the meal will be:\")\n", "print(cost)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### A small warning (especially for those with Excel background)\n", "\n", "Now let's update the cost of the food:" ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [], "source": [ "food = 100" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And let's see the cost of the meal:" ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The cost of the meal will be:\n", "96.65625\n" ] } ], "source": [ "print(\"The cost of the meal will be:\")\n", "print(cost)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "You will see that the value of the `cost` variable remained 96.65, and it was not automatically updated when we updated the `food` variable.. \n", "\n", "To update the `cost` variable, we need to execute again the calculation:" ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The cost of the meal will be:\n", "128.875\n" ] } ], "source": [ "cost = food + food * tax + food * tip\n", "print(\"The cost of the meal will be:\")\n", "print(cost)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that the value of `food` persisted from the prior cell. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Example: Using and Updating Variables\n", "\n", "Let's work on another example, to practice the use of variables. We will also see an example of updating the value of a variable." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Upon taking this class, you are recruited in a new hot startup. They offer you a starting salary of \\$150K, a promised 25% bonus, and an equity package currently worth \\$400K, vesting over a period of 4 years. You want to examine the true value of this package, so you write the following program:" ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "# A small example to start\n", "base_salary = 150000\n", "expected_bonus = 0.25\n", "equity = 400000\n", "years_vesting = 4" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The yearly value of this offer is 287500.0\n" ] } ], "source": [ "# Base scenario\n", "yearly_value = base_salary + expected_bonus * base_salary + equity / years_vesting\n", "print(\"The yearly value of this offer is\", yearly_value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, we will write the same program, but we will do the calculation in three steps. Notice that we will update the `yearly_value` in steps." ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The yearly value of this offer is 287500.0\n" ] } ], "source": [ "# Same computation as above, but in three steps\n", "# We start by adding the base_salary in the yearly_value\n", "yearly_value = base_salary\n", "# then we add the expected bonus\n", "yearly_value = yearly_value + expected_bonus * base_salary\n", "# and then we add the value of equity\n", "yearly_value = yearly_value + equity / years_vesting\n", "print(\"The yearly value of this offer is\", yearly_value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "As expected, the outcome is the same as before.\n", "\n", "Let's see one more variation of the same program, but now we will introduce the `+=` operator. The command\n", "\n", "`x += y` \n", "\n", "means \"_add the value of variable `y` to the variable `x`_\"." ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The yearly value of this offer is 187500.0\n" ] } ], "source": [ "# Same computation as above, but using the += shorthand\n", "yearly_value = base_salary\n", "yearly_value += expected_bonus * base_salary\n", "yearly_value += 0 * equity / years_vesting\n", "print(\"The yearly value of this offer is\", yearly_value)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Exercise\n", "\n", "Now let's do the following exercise. You not only want to know the value with the current company valuation (\\$400K equity) but also want to see what would happen if your equity is worth nothing at the end, and also examine what would happen if the company does really well, and grows by a factor of 10x. Write the code for the two scenarios below." ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [], "source": [ "# Crash and burn scenario. Equity is worth nothing at the end\n", "# your code here" ] }, { "cell_type": "code", "execution_count": 17, "metadata": {}, "outputs": [], "source": [ "# Optimistic scenario. The company goes up a lot, and equity is worth 10x more\n", "# your code here" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Selecting Good Variable Names\n", "\n", "Notice the importance of selecting good variable names, to make the program readable. \n", "\n", "The program below is identical to the one above, but with less explanatory names for the variables. Instead, we have comments to document the code." ] }, { "cell_type": "code", "execution_count": 18, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The yearly value of this offer is 287500.0\n" ] } ], "source": [ "s = 150000 # salary\n", "b = 0.25 # bonus percentage\n", "e = 400000 # value of promised equity\n", "y = 4 # years for vesting equity\n", "v = s + b * s + e / y # compute the yearly value\n", "print(\"The yearly value of this offer is\", v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, let's take the comments away. The program will run in exactly the same manner; comments are purely for humans to read, not for the computer. Still, notice how cryptic the program becomes." ] }, { "cell_type": "code", "execution_count": 19, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The yearly value of this offer is 287500.0\n" ] } ], "source": [ "s = 150000\n", "b = 0.25\n", "e = 400000\n", "y = 4\n", "v = s + b * s + e / y\n", "print(\"The yearly value of this offer is\", v)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "And here is the same program again, but with really bad selection of variable names. (You may find it artificial, but this is an example of variable names in a real student project submitted a few years ago.)" ] }, { "cell_type": "code", "execution_count": 20, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "The yearly value of this offer is 287500.0\n" ] } ], "source": [ "whiskey = 150000\n", "beer = 0.25\n", "gin = 400000\n", "vodka = 4\n", "rum = whiskey + beer * whiskey + gin / vodka\n", "print(\"The yearly value of this offer is\", rum)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Remember, the most frequent other person that will read your code is your future self. Treat your future self nicely!" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Improper variable names, Reserved Keywords, and Dangerous Choices for Variable Names" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If you give a variable an illegal name, you get a syntax error:" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "tags": [ "raises-exception", "flake8-noqa-cell" ] }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 3)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m 76trombones = 'big parade'\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "# 76trombones is illegal because it begins with a number.\n", "# REMOVE THE COMMENT CHARACTER IN THE NEXT LINE TO ATTEMPT\n", "76trombones = 'big parade'" ] }, { "cell_type": "code", "execution_count": 22, "metadata": { "tags": [ "raises-exception", "flake8-noqa-cell" ] }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 2)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m more@ = 1000000\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "# more@ is illegal because it contains an illegal character\n", "more@ = 1000000" ] }, { "cell_type": "code", "execution_count": 23, "metadata": { "tags": [ "raises-exception", "flake8-noqa-cell" ] }, "outputs": [], "source": [ "# You cannot have spaces in variable names\n", "daily diff = 10.10" ] }, { "cell_type": "code", "execution_count": 24, "metadata": {}, "outputs": [], "source": [ "# Using underscore is fine though\n", "daily_diff = 10.10" ] }, { "cell_type": "code", "execution_count": 25, "metadata": { "tags": [ "raises-exception", "flake8-noqa-cell" ] }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 2)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m2\u001b[0m\n\u001b[0;31m class = 'Introduction to Programming'\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "# What’s wrong with class? It turns out that \"class\" is one of Python’s keywords.\n", "class = 'Introduction to Programming'" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Reserved keywords" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python 3 has 33 _reserved keywords_, which are listed below and are also [available in the Python manual](https://docs.python.org/3/reference/lexical_analysis.html#keywords). It a very common mistake for beginners to use some of the reserved keywords below as their variable names, so please try to be vigilant about such mistakes. The editor will help you, as reserved keywords are often colored differently." ] }, { "cell_type": "raw", "metadata": {}, "source": [ "False class finally is return\n", "None continue for lambda try\n", "True def from nonlocal while\n", "and del global not with\n", "as elif if or yield\n", "assert else import pass\n", "break except in raise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice that the code below will not run because \"`raise`\" is a reserved keyword" ] }, { "cell_type": "code", "execution_count": 26, "metadata": { "tags": [ "raises-exception", "flake8-noqa-cell" ] }, "outputs": [ { "ename": "SyntaxError", "evalue": "invalid syntax (, line 3)", "output_type": "error", "traceback": [ "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m3\u001b[0m\n\u001b[0;31m raise = 35000\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" ] } ], "source": [ "# Remove the comment characters to try\n", "current_salary = 125000\n", "raise = 35000\n", "next_salary = current_salary + raise" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Warning: Do not use common function names as variables\n", "\n", "While it is prohibited to use reserved keywords, Python allows the to create variables that correspond to [common functions](https://docs.python.org/3.6/library/functions.html). This can lead to very strange behaviors. In general, it is a good practice to avoid using variables that are getting colored in a different color in the editor. " ] }, { "cell_type": "code", "execution_count": 27, "metadata": { "tags": [ "raises-exception", "flake8-noqa-cell" ] }, "outputs": [ { "ename": "TypeError", "evalue": "'int' object is not callable", "output_type": "error", "traceback": [ "\u001b[0;31m\u001b[0m", "\u001b[0;31mTypeError\u001b[0mTraceback (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[0mprint\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;36m100\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"What happened?\"\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: 'int' object is not callable" ] } ], "source": [ "print = 100\n", "print(\"What happened?\")" ] }, { "cell_type": "code", "execution_count": 28, "metadata": {}, "outputs": [], "source": [ "# Let's fix the mess...\n", "del print" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Key points to remember\n", "\n", "* We use variables to store values.\n", "\n", "* We can use variables to make our calculations readable and easier to update.\n", "\n", "* Variable values persist between cells. Variable values keep the value from the last _executed_ cell that updated them. (Remember that you can execute cells in any order.)\n", "\n", "* Using good variable names makes our programs easier to read and understand.\n", "\n", "* Variable names contain letters, numbers, and underscores; variable names cannot start with numbers.\n", "\n", "* There are a few _reserved keywords_ that cannot be used. It is also a good idea not to use common function names as variables (eg., `print`, `min`, `max`, etc.; they are all function and are colored green in the editor)\n", "\n", "\n", "\n" ] } ], "metadata": { "celltoolbar": "Tags", "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.2" } }, "nbformat": 4, "nbformat_minor": 1 }