{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Names\n", "\n", "Names are given to values in Python using an *assignment* statement. In an assignment, a name is followed by `=`, which is followed by any expression. The value of the expression to the right of `=` is *assigned* to the name. Once a name has a value assigned to it, the value will be substituted for that name in future expressions." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "30" ] }, "execution_count": 1, "metadata": {}, "output_type": "execute_result" } ], "source": [ "a = 10\n", "b = 20\n", "a + b" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "A previously assigned name can be used in the expression to the right of `=`. " ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.5" ] }, "execution_count": 2, "metadata": {}, "output_type": "execute_result" } ], "source": [ "quarter = 1/4\n", "half = 2 * quarter\n", "half" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "However, only the current value of an expression is assigned to a name. If that value changes later, names that were defined in terms of that value will not change automatically." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.5" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "quarter = 4\n", "half" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Names must start with a letter, but can contain both letters and numbers. A name cannot contain a space; instead, it is common to use an underscore character `_` to replace each space. Names are only as useful as you make them; it's up to the programmer to choose names that are easy to interpret. Typically, more meaningful names can be invented than `a` and `b`. For example, to describe the sales tax on a $5 purchase in Berkeley, CA, the following names clarify the meaning of the various quantities involved." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "0.475" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "purchase_price = 5\n", "state_tax_rate = 0.075\n", "county_tax_rate = 0.02\n", "city_tax_rate = 0\n", "sales_tax_rate = state_tax_rate + county_tax_rate + city_tax_rate\n", "sales_tax = purchase_price * sales_tax_rate\n", "sales_tax" ] } ], "metadata": { "anaconda-cloud": {}, "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.12" } }, "nbformat": 4, "nbformat_minor": 2 }