From 47fd3c25911ac7f4433fad1d0e71bf51f567eb95 Mon Sep 17 00:00:00 2001 From: anthonyvantran Date: Thu, 26 Dec 2024 08:54:36 -0500 Subject: [PATCH 1/2] ThinkPython3 Chapter 1/Exercises --- chapters/chap01.ipynb | 1987 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1987 insertions(+) create mode 100644 chapters/chap01.ipynb diff --git a/chapters/chap01.ipynb b/chapters/chap01.ipynb new file mode 100644 index 0000000..1f8949d --- /dev/null +++ b/chapters/chap01.ipynb @@ -0,0 +1,1987 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "view-in-github", + "colab_type": "text" + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "id": "1331faa1", + "metadata": { + "id": "1331faa1" + }, + "source": [ + "You can order print and ebook versions of *Think Python 3e* from\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + ] + }, + { + "cell_type": "markdown", + "id": "a14edb7e", + "metadata": { + "tags": [], + "id": "a14edb7e" + }, + "source": [ + "# Welcome\n", + "\n", + "This is the Jupyter notebook for Chapter 1 of [*Think Python*, 3rd edition](https://greenteapress.com/wp/think-python-3rd-edition), by Allen B. Downey.\n", + "\n", + "If you are not familiar with Jupyter notebooks,\n", + "[click here for a short introduction](https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/jupyter_intro.ipynb).\n", + "\n", + "Then, if you are not already running this notebook on Colab, [click here to run this notebook on Colab](https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/chap01.ipynb)." + ] + }, + { + "cell_type": "markdown", + "id": "3b4a1f57", + "metadata": { + "tags": [], + "id": "3b4a1f57" + }, + "source": [ + "The following cell downloads a file and runs some code that is used specifically for this book.\n", + "You don't have to understand this code yet, but you should run it before you do anything else in this notebook.\n", + "Remember that you can run the code by selecting the cell and pressing the play button (a triangle in a circle) or hold down `Shift` and press `Enter`." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "213f9d96", + "metadata": { + "tags": [], + "id": "213f9d96", + "outputId": "18c4e522-b945-4dbd-fa55-c9413a83eacf", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Downloaded thinkpython.py\n" + ] + } + ], + "source": [ + "from os.path import basename, exists\n", + "\n", + "def download(url):\n", + " filename = basename(url)\n", + " if not exists(filename):\n", + " from urllib.request import urlretrieve\n", + "\n", + " local, _ = urlretrieve(url, filename)\n", + " print(\"Downloaded \" + str(local))\n", + " return filename\n", + "\n", + "download('https://github.com/AllenDowney/ThinkPython/raw/v3/thinkpython.py');\n", + "\n", + "import thinkpython" + ] + }, + { + "cell_type": "markdown", + "id": "333a6fc9", + "metadata": { + "tags": [], + "id": "333a6fc9" + }, + "source": [ + "# Programming as a way of thinking\n", + "\n", + "The first goal of this book is to teach you how to program in Python.\n", + "But learning to program means learning a new way to think, so the second goal of this book is to help you think like a computer scientist.\n", + "This way of thinking combines some of the best features of mathematics, engineering, and natural science.\n", + "Like mathematicians, computer scientists use formal languages to denote ideas -- specifically computations.\n", + "Like engineers, they design things, assembling components into systems and evaluating trade-offs among alternatives.\n", + "Like scientists, they observe the behavior of complex systems, form hypotheses, and test predictions.\n", + "\n", + "We will start with the most basic elements of programming and work our way up.\n", + "In this chapter, we'll see how Python represents numbers, letters, and words.\n", + "And you'll learn to perform arithmetic operations.\n", + "\n", + "You will also start to learn the vocabulary of programming, including terms like operator, expression, value, and type.\n", + "This vocabulary is important -- you will need it to understand the rest of the book, to communicate with other programmers, and to use and understand virtual assistants." + ] + }, + { + "cell_type": "markdown", + "id": "a371aea3", + "metadata": { + "id": "a371aea3" + }, + "source": [ + "## Arithmetic operators\n", + "\n", + "An **arithmetic operator** is a symbol that represents an arithmetic computation. For example, the plus sign, `+`, performs addition." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2568ec84", + "metadata": { + "id": "2568ec84" + }, + "outputs": [], + "source": [ + "30 + 12" + ] + }, + { + "cell_type": "markdown", + "id": "fc0e7ce8", + "metadata": { + "id": "fc0e7ce8" + }, + "source": [ + "The minus sign, `-`, is the operator that performs subtraction." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c4e75456", + "metadata": { + "id": "c4e75456" + }, + "outputs": [], + "source": [ + "43 - 1" + ] + }, + { + "cell_type": "markdown", + "id": "63e4e780", + "metadata": { + "id": "63e4e780" + }, + "source": [ + "The asterisk, `*`, performs multiplication." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "022a7b16", + "metadata": { + "id": "022a7b16" + }, + "outputs": [], + "source": [ + "6 * 7" + ] + }, + { + "cell_type": "markdown", + "id": "a6192d13", + "metadata": { + "id": "a6192d13" + }, + "source": [ + "And the forward slash, `/`, performs division:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "05ae1098", + "metadata": { + "id": "05ae1098" + }, + "outputs": [], + "source": [ + "84 / 2" + ] + }, + { + "cell_type": "markdown", + "id": "641ad233", + "metadata": { + "id": "641ad233" + }, + "source": [ + "Notice that the result of the division is `42.0` rather than `42`. That's because there are two types of numbers in Python:\n", + "\n", + "* **integers**, which represent numbers with no fractional or decimal part, and\n", + "\n", + "* **floating-point numbers**, which represent integers and numbers with a decimal point.\n", + "\n", + "If you add, subtract, or multiply two integers, the result is an integer.\n", + "But if you divide two integers, the result is a floating-point number.\n", + "Python provides another operator, `//`, that performs **integer division**.\n", + "The result of integer division is always an integer." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "4df5bcaa", + "metadata": { + "id": "4df5bcaa" + }, + "outputs": [], + "source": [ + "84 // 2" + ] + }, + { + "cell_type": "markdown", + "id": "b2a620ab", + "metadata": { + "id": "b2a620ab" + }, + "source": [ + "Integer division is also called \"floor division\" because it always rounds down (toward the \"floor\")." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ef08d549", + "metadata": { + "id": "ef08d549" + }, + "outputs": [], + "source": [ + "85 // 2" + ] + }, + { + "cell_type": "markdown", + "id": "41e2886a", + "metadata": { + "id": "41e2886a" + }, + "source": [ + "Finally, the operator `**` performs exponentiation; that is, it raises a\n", + "number to a power:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "df933e80", + "metadata": { + "id": "df933e80", + "outputId": "9eed2257-859a-47ff-c18e-3dd4ad5c08bd", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "49" + ] + }, + "metadata": {}, + "execution_count": 3 + } + ], + "source": [ + "7 ** 2" + ] + }, + { + "cell_type": "markdown", + "id": "b2502fb6", + "metadata": { + "id": "b2502fb6" + }, + "source": [ + "In some other languages, the caret, `^`, is used for exponentiation, but in Python\n", + "it is a bitwise operator called XOR.\n", + "If you are not familiar with bitwise operators, the result might be unexpected:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "306b6b88", + "metadata": { + "id": "306b6b88", + "outputId": "def8be03-2d42-44ac-e7dc-becf27da931d", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "5" + ] + }, + "metadata": {}, + "execution_count": 2 + } + ], + "source": [ + "7 ^ 2" + ] + }, + { + "cell_type": "markdown", + "id": "30078370", + "metadata": { + "id": "30078370" + }, + "source": [ + "I won't cover bitwise operators in this book, but you can read about\n", + "them at ." + ] + }, + { + "cell_type": "markdown", + "id": "0f5b7e97", + "metadata": { + "id": "0f5b7e97" + }, + "source": [ + "## Expressions\n", + "\n", + "A collection of operators and numbers is called an **expression**.\n", + "An expression can contain any number of operators and numbers.\n", + "For example, here's an expression that contains two operators." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "6e68101d", + "metadata": { + "id": "6e68101d", + "outputId": "24fb7b7e-b656-4859-a013-fbe1ba7fbe6f", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "42" + ] + }, + "metadata": {}, + "execution_count": 4 + } + ], + "source": [ + "6 + 6 ** 2" + ] + }, + { + "cell_type": "markdown", + "id": "8e95039c", + "metadata": { + "id": "8e95039c" + }, + "source": [ + "Notice that exponentiation happens before addition.\n", + "Python follows the order of operations you might have learned in a math class: exponentiation happens before multiplication and division, which happen before addition and subtraction.\n", + "\n", + "In the following example, multiplication happens before addition." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "ffc25598", + "metadata": { + "id": "ffc25598", + "outputId": "c8ce737e-6864-4163-f2a5-96c0500bf8c2", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "42" + ] + }, + "metadata": {}, + "execution_count": 5 + } + ], + "source": [ + "12 + 5 * 6" + ] + }, + { + "cell_type": "markdown", + "id": "914a60d8", + "metadata": { + "id": "914a60d8" + }, + "source": [ + "If you want the addition to happen first, you can use parentheses." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "8dd1bd9a", + "metadata": { + "id": "8dd1bd9a", + "outputId": "531b2fa8-fcd9-4946-bf02-7852d647a437", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "102" + ] + }, + "metadata": {}, + "execution_count": 6 + } + ], + "source": [ + "(12 + 5) * 6" + ] + }, + { + "cell_type": "markdown", + "id": "67ae0ae9", + "metadata": { + "id": "67ae0ae9" + }, + "source": [ + "Every expression has a **value**.\n", + "For example, the expression `6 * 7` has the value `42`." + ] + }, + { + "cell_type": "markdown", + "id": "caebaa51", + "metadata": { + "id": "caebaa51" + }, + "source": [ + "## Arithmetic functions\n", + "\n", + "In addition to the arithmetic operators, Python provides a few **functions** that work with numbers.\n", + "For example, the `round` function takes a floating-point number and rounds it off to the nearest integer." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "1e3d5e01", + "metadata": { + "id": "1e3d5e01", + "outputId": "c7c27fdb-3bba-457a-e95e-be1a3a57447c", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "42" + ] + }, + "metadata": {}, + "execution_count": 7 + } + ], + "source": [ + "round(42.4)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "d1b220b9", + "metadata": { + "id": "d1b220b9", + "outputId": "5bf9a954-c589-49ca-eaa6-6e81b4fdee26", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "43" + ] + }, + "metadata": {}, + "execution_count": 8 + } + ], + "source": [ + "round(42.6)" + ] + }, + { + "cell_type": "markdown", + "id": "f5738b4b", + "metadata": { + "id": "f5738b4b" + }, + "source": [ + "The `abs` function computes the absolute value of a number.\n", + "For a positive number, the absolute value is the number itself." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ff742476", + "metadata": { + "id": "ff742476" + }, + "outputs": [], + "source": [ + "abs(42)" + ] + }, + { + "cell_type": "markdown", + "id": "e518494a", + "metadata": { + "id": "e518494a" + }, + "source": [ + "For a negative number, the absolute value is positive." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "9247c1a3", + "metadata": { + "id": "9247c1a3", + "outputId": "4ad5ea0a-51ce-4623-b336-8e2677fa8f2d", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "42" + ] + }, + "metadata": {}, + "execution_count": 9 + } + ], + "source": [ + "abs(-42)" + ] + }, + { + "cell_type": "markdown", + "id": "6969ce45", + "metadata": { + "id": "6969ce45" + }, + "source": [ + "When we use a function like this, we say we're **calling** the function.\n", + "An expression that calls a function is a **function call**.\n", + "\n", + "When you call a function, the parentheses are required.\n", + "If you leave them out, you get an error message." + ] + }, + { + "cell_type": "markdown", + "id": "5a73bfd5", + "metadata": { + "tags": [], + "id": "5a73bfd5" + }, + "source": [ + "NOTE: The following cell uses `%%expect`, which is a Jupyter \"magic command\" that means we expect the code in this cell to produce an error. For more on this topic, see the\n", + "[Jupyter notebook introduction](https://colab.research.google.com/github/AllenDowney/ThinkPython/blob/v3/chapters/jupyter_intro.ipynb)." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "4674b7ca", + "metadata": { + "tags": [], + "id": "4674b7ca", + "outputId": "383b93d4-f916-4205-fdf7-87bb2964681b", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 106 + } + }, + "outputs": [ + { + "output_type": "error", + "ename": "SyntaxError", + "evalue": "invalid syntax (, line 1)", + "traceback": [ + "\u001b[0;36m File \u001b[0;32m\"\"\u001b[0;36m, line \u001b[0;32m1\u001b[0m\n\u001b[0;31m abs 42\u001b[0m\n\u001b[0m ^\u001b[0m\n\u001b[0;31mSyntaxError\u001b[0m\u001b[0;31m:\u001b[0m invalid syntax\n" + ] + } + ], + "source": [ + "%%expect SyntaxError\n", + "\n", + "abs 42" + ] + }, + { + "cell_type": "markdown", + "id": "7d356f1b", + "metadata": { + "id": "7d356f1b" + }, + "source": [ + "You can ignore the first line of this message; it doesn't contain any information we need to understand right now.\n", + "The second line is the code that contains the error, with a caret (`^`) beneath it to indicate where the error was discovered.\n", + "\n", + "The last line indicates that this is a **syntax error**, which means that there is something wrong with the structure of the expression.\n", + "In this example, the problem is that a function call requires parentheses.\n", + "\n", + "Let's see what happens if you leave out the parentheses *and* the value." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "7d3e8127", + "metadata": { + "id": "7d3e8127", + "outputId": "09aa823c-292e-467f-e324-41ac4b32966d", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "" + ] + }, + "metadata": {}, + "execution_count": 11 + } + ], + "source": [ + "abs" + ] + }, + { + "cell_type": "markdown", + "id": "94478885", + "metadata": { + "id": "94478885" + }, + "source": [ + "A function name all by itself is a legal expression that has a value.\n", + "When it's displayed, the value indicates that `abs` is a function, and it includes some additional information I'll explain later." + ] + }, + { + "cell_type": "markdown", + "id": "31a85d17", + "metadata": { + "id": "31a85d17" + }, + "source": [ + "## Strings\n", + "\n", + "In addition to numbers, Python can also represent sequences of letters, which are called **strings** because the letters are strung together like beads on a necklace.\n", + "To write a string, we can put a sequence of letters inside straight quotation marks." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "bd8ae45f", + "metadata": { + "id": "bd8ae45f" + }, + "outputs": [], + "source": [ + "'Hello'" + ] + }, + { + "cell_type": "markdown", + "id": "d20050d8", + "metadata": { + "id": "d20050d8" + }, + "source": [ + "It is also legal to use double quotation marks." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "01d0055e", + "metadata": { + "id": "01d0055e" + }, + "outputs": [], + "source": [ + "\"world\"" + ] + }, + { + "cell_type": "markdown", + "id": "76f5edb7", + "metadata": { + "id": "76f5edb7" + }, + "source": [ + "Double quotes make it easy to write a string that contains an apostrophe, which is the same symbol as a straight quote." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "0295acab", + "metadata": { + "id": "0295acab", + "outputId": "ef44cd7c-99a9-4773-ca5e-2c45a0382df3", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "\"it's a small \"" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 12 + } + ], + "source": [ + "\"it's a small \"" + ] + }, + { + "cell_type": "markdown", + "id": "d62d4b1c", + "metadata": { + "id": "d62d4b1c" + }, + "source": [ + "Strings can also contain spaces, punctuation, and digits." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cf918917", + "metadata": { + "id": "cf918917" + }, + "outputs": [], + "source": [ + "'Well, '" + ] + }, + { + "cell_type": "markdown", + "id": "9ad47f7a", + "metadata": { + "id": "9ad47f7a" + }, + "source": [ + "The `+` operator works with strings; it joins two strings into a single string, which is called **concatenation**" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "aefe6af1", + "metadata": { + "id": "aefe6af1", + "outputId": "f037772b-899a-4341-ccc0-5b313e878cff", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "\"Well, it's a small world.\"" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 13 + } + ], + "source": [ + "'Well, ' + \"it's a small \" + 'world.'" + ] + }, + { + "cell_type": "markdown", + "id": "0ad969a3", + "metadata": { + "id": "0ad969a3" + }, + "source": [ + "The `*` operator also works with strings; it makes multiple copies of a string and concatenates them." + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "id": "42e9e4e2", + "metadata": { + "id": "42e9e4e2", + "outputId": "b596cdab-b859-458a-dabd-8379ed97911a", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'Spam, Spam, Spam, Spam, '" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 14 + } + ], + "source": [ + "'Spam, ' * 4" + ] + }, + { + "cell_type": "markdown", + "id": "dfba16a5", + "metadata": { + "id": "dfba16a5" + }, + "source": [ + "The other arithmetic operators don't work with strings.\n", + "\n", + "Python provides a function called `len` that computes the length of a string." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "a5e837db", + "metadata": { + "id": "a5e837db", + "outputId": "09b3226c-e924-4789-8e85-48e373543408", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "4" + ] + }, + "metadata": {}, + "execution_count": 17 + } + ], + "source": [ + "len('Spam')" + ] + }, + { + "cell_type": "markdown", + "id": "d91e00b3", + "metadata": { + "id": "d91e00b3" + }, + "source": [ + "Notice that `len` counts the letters between the quotes, but not the quotes.\n", + "\n", + "When you create a string, be sure to use straight quotes.\n", + "The back quote, also known as a backtick, causes a syntax error." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e3f65f19", + "metadata": { + "tags": [], + "id": "e3f65f19" + }, + "outputs": [], + "source": [ + "%%expect SyntaxError\n", + "\n", + "`Hello`" + ] + }, + { + "cell_type": "markdown", + "id": "40d893d1", + "metadata": { + "id": "40d893d1" + }, + "source": [ + "Smart quotes, also known as curly quotes, are also illegal." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "a705b980", + "metadata": { + "tags": [], + "id": "a705b980" + }, + "outputs": [], + "source": [ + "%%expect SyntaxError\n", + "\n", + "‘Hello’" + ] + }, + { + "cell_type": "markdown", + "id": "5471d4f8", + "metadata": { + "id": "5471d4f8" + }, + "source": [ + "## Values and types\n", + "\n", + "So far we've seen three kinds of values:\n", + "\n", + "* `2` is an integer,\n", + "\n", + "* `42.0` is a floating-point number, and\n", + "\n", + "* `'Hello'` is a string.\n", + "\n", + "A kind of value is called a **type**.\n", + "Every value has a type -- or we sometimes say it \"belongs to\" a type.\n", + "\n", + "Python provides a function called `type` that tells you the type of any value.\n", + "The type of an integer is `int`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3df8e2c5", + "metadata": { + "id": "3df8e2c5" + }, + "outputs": [], + "source": [ + "type(2)" + ] + }, + { + "cell_type": "markdown", + "id": "b137814c", + "metadata": { + "id": "b137814c" + }, + "source": [ + "The type of a floating-point number is `float`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c4732c8d", + "metadata": { + "id": "c4732c8d" + }, + "outputs": [], + "source": [ + "type(42.0)" + ] + }, + { + "cell_type": "markdown", + "id": "266dea4e", + "metadata": { + "id": "266dea4e" + }, + "source": [ + "And the type of a string is `str`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "8f65ac45", + "metadata": { + "id": "8f65ac45" + }, + "outputs": [], + "source": [ + "type('Hello, World!')" + ] + }, + { + "cell_type": "markdown", + "id": "76d216ed", + "metadata": { + "id": "76d216ed" + }, + "source": [ + "The types `int`, `float`, and `str` can be used as functions.\n", + "For example, `int` can take a floating-point number and convert it to an integer (always rounding down)." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "84b22f2f", + "metadata": { + "id": "84b22f2f" + }, + "outputs": [], + "source": [ + "int(42.9)" + ] + }, + { + "cell_type": "markdown", + "id": "dcd8d114", + "metadata": { + "id": "dcd8d114" + }, + "source": [ + "And `float` can convert an integer to a floating-point value." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "9b66ee21", + "metadata": { + "id": "9b66ee21" + }, + "outputs": [], + "source": [ + "float(42)" + ] + }, + { + "cell_type": "markdown", + "id": "eda70b61", + "metadata": { + "id": "eda70b61" + }, + "source": [ + "Now, here's something that can be confusing.\n", + "What do you get if you put a sequence of digits in quotes?" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "id": "f64e107c", + "metadata": { + "id": "f64e107c", + "outputId": "59519f5d-61ca-4846-d3bf-269ec93fcd45", + "colab": { + "base_uri": "https://localhost:8080/", + "height": 35 + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "'126'" + ], + "application/vnd.google.colaboratory.intrinsic+json": { + "type": "string" + } + }, + "metadata": {}, + "execution_count": 18 + } + ], + "source": [ + "'126'" + ] + }, + { + "cell_type": "markdown", + "id": "fdded653", + "metadata": { + "id": "fdded653" + }, + "source": [ + "It looks like a number, but it is actually a string." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "id": "609a8153", + "metadata": { + "id": "609a8153", + "outputId": "3135f6ae-ecf3-4302-fe82-18e2c1f163df", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "str" + ] + }, + "metadata": {}, + "execution_count": 19 + } + ], + "source": [ + "type('126')" + ] + }, + { + "cell_type": "markdown", + "id": "2683ac35", + "metadata": { + "id": "2683ac35" + }, + "source": [ + "If you try to use it like a number, you might get an error." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1cf21da4", + "metadata": { + "tags": [], + "id": "1cf21da4" + }, + "outputs": [], + "source": [ + "%%expect TypeError\n", + "\n", + "'126' / 3" + ] + }, + { + "cell_type": "markdown", + "id": "32c11cc4", + "metadata": { + "id": "32c11cc4" + }, + "source": [ + "This example generates a `TypeError`, which means that the values in the expression, which are called **operands**, have the wrong type.\n", + "The error message indicates that the `/` operator does not support the types of these values, which are `str` and `int`.\n", + "\n", + "If you have a string that contains digits, you can use `int` to convert it to an integer." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "d45e6a60", + "metadata": { + "id": "d45e6a60" + }, + "outputs": [], + "source": [ + "int('126') / 3" + ] + }, + { + "cell_type": "markdown", + "id": "86935d56", + "metadata": { + "id": "86935d56" + }, + "source": [ + "If you have a string that contains digits and a decimal point, you can use `float` to convert it to a floating-point number." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "db30b719", + "metadata": { + "id": "db30b719" + }, + "outputs": [], + "source": [ + "float('12.6')" + ] + }, + { + "cell_type": "markdown", + "id": "03103ef4", + "metadata": { + "id": "03103ef4" + }, + "source": [ + "When you write a large integer, you might be tempted to use commas\n", + "between groups of digits, as in `1,000,000`.\n", + "This is a legal expression in Python, but the result is not an integer." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "id": "d72b6af1", + "metadata": { + "id": "d72b6af1", + "outputId": "bf1792c1-5b4c-49cb-ff71-ab8010228362", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "(1, 0, 0)" + ] + }, + "metadata": {}, + "execution_count": 20 + } + ], + "source": [ + "1,000,000" + ] + }, + { + "cell_type": "markdown", + "id": "3d24af71", + "metadata": { + "id": "3d24af71" + }, + "source": [ + "Python interprets `1,000,000` as a comma-separated sequence of integers.\n", + "We'll learn more about this kind of sequence later.\n", + "\n", + "You can use underscores to make large numbers easier to read." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "id": "e19bf7e7", + "metadata": { + "id": "e19bf7e7", + "outputId": "bef7e26e-ff4d-48ab-f4aa-125062425928", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "1000000" + ] + }, + "metadata": {}, + "execution_count": 21 + } + ], + "source": [ + "1_000_000" + ] + }, + { + "cell_type": "markdown", + "id": "1761cbac", + "metadata": { + "id": "1761cbac" + }, + "source": [ + "## Formal and natural languages\n", + "\n", + "**Natural languages** are the languages people speak, like English, Spanish, and French. They were not designed by people; they evolved naturally.\n", + "\n", + "**Formal languages** are languages that are designed by people for specific applications.\n", + "For example, the notation that mathematicians use is a formal language that is particularly good at denoting relationships among numbers and symbols.\n", + "Similarly, programming languages are formal languages that have been designed to express computations." + ] + }, + { + "cell_type": "markdown", + "id": "1bf3d2dc", + "metadata": { + "id": "1bf3d2dc" + }, + "source": [ + "Although formal and natural languages have some features in\n", + "common there are important differences:\n", + "\n", + "* Ambiguity: Natural languages are full of ambiguity, which people deal with by\n", + " using contextual clues and other information. Formal languages are\n", + " designed to be nearly or completely unambiguous, which means that\n", + " any program has exactly one meaning, regardless of context.\n", + "\n", + "* Redundancy: In order to make up for ambiguity and reduce misunderstandings,\n", + " natural languages use redundancy. As a result, they are\n", + " often verbose. Formal languages are less redundant and more concise.\n", + "\n", + "* Literalness: Natural languages are full of idiom and metaphor. Formal languages mean exactly what they say." + ] + }, + { + "cell_type": "markdown", + "id": "78a1cec8", + "metadata": { + "id": "78a1cec8" + }, + "source": [ + "Because we all grow up speaking natural languages, it is sometimes hard to adjust to formal languages.\n", + "Formal languages are more dense than natural languages, so it takes longer to read them.\n", + "Also, the structure is important, so it is not always best to read from top to bottom, left to right.\n", + "Finally, the details matter. Small errors in spelling and\n", + "punctuation, which you can get away with in natural languages, can make\n", + "a big difference in a formal language." + ] + }, + { + "cell_type": "markdown", + "id": "4358fa9a", + "metadata": { + "id": "4358fa9a" + }, + "source": [ + "## Debugging\n", + "\n", + "Programmers make mistakes. For whimsical reasons, programming errors are called **bugs** and the process of tracking them down is called **debugging**.\n", + "\n", + "Programming, and especially debugging, sometimes brings out strong emotions. If you are struggling with a difficult bug, you might feel angry, sad, or embarrassed.\n", + "\n", + "Preparing for these reactions might help you deal with them. One approach is to think of the computer as an employee with certain strengths, like speed and precision, and particular weaknesses, like lack of empathy and inability to grasp the big picture.\n", + "\n", + "Your job is to be a good manager: find ways to take advantage of the strengths and mitigate the weaknesses. And find ways to use your emotions to engage with the problem, without letting your reactions interfere with your ability to work effectively.\n", + "\n", + "Learning to debug can be frustrating, but it is a valuable skill that is useful for many activities beyond programming. At the end of each chapter there is a section, like this one, with my suggestions for debugging. I hope they help!" + ] + }, + { + "cell_type": "markdown", + "id": "33b8ad00", + "metadata": { + "id": "33b8ad00" + }, + "source": [ + "## Glossary\n", + "\n", + "**arithmetic operator:**\n", + "A symbol, like `+` and `*`, that denotes an arithmetic operation like addition or multiplication.\n", + "\n", + "**integer:**\n", + "A type that represents numbers with no fractional or decimal part.\n", + "\n", + "**floating-point:**\n", + "A type that represents integers and numbers with decimal parts.\n", + "\n", + "**integer division:**\n", + "An operator, `//`, that divides two numbers and rounds down to an integer.\n", + "\n", + "**expression:**\n", + "A combination of variables, values, and operators.\n", + "\n", + "**value:**\n", + "An integer, floating-point number, or string -- or one of other kinds of values we will see later.\n", + "\n", + "**function:**\n", + "A named sequence of statements that performs some useful operation.\n", + "Functions may or may not take arguments and may or may not produce a result.\n", + "\n", + "**function call:**\n", + "An expression -- or part of an expression -- that runs a function.\n", + "It consists of the function name followed by an argument list in parentheses.\n", + "\n", + "**syntax error:**\n", + "An error in a program that makes it impossible to parse -- and therefore impossible to run.\n", + "\n", + "**string:**\n", + " A type that represents sequences of characters.\n", + "\n", + "**concatenation:**\n", + "Joining two strings end-to-end.\n", + "\n", + "**type:**\n", + "A category of values.\n", + "The types we have seen so far are integers (type `int`), floating-point numbers (type ` float`), and strings (type `str`).\n", + "\n", + "**operand:**\n", + "One of the values on which an operator operates.\n", + "\n", + "**natural language:**\n", + "Any of the languages that people speak that evolved naturally.\n", + "\n", + "**formal language:**\n", + "Any of the languages that people have designed for specific purposes, such as representing mathematical ideas or computer programs.\n", + "All programming languages are formal languages.\n", + "\n", + "**bug:**\n", + "An error in a program.\n", + "\n", + "**debugging:**\n", + "The process of finding and correcting errors." + ] + }, + { + "cell_type": "markdown", + "id": "ed4ec01b", + "metadata": { + "id": "ed4ec01b" + }, + "source": [ + "## Exercises" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "06d3e72c", + "metadata": { + "tags": [], + "id": "06d3e72c" + }, + "outputs": [], + "source": [ + "# This cell tells Jupyter to provide detailed debugging information\n", + "# when a runtime error occurs. Run it before working on the exercises.\n", + "\n", + "%xmode Verbose" + ] + }, + { + "cell_type": "markdown", + "id": "23adf208", + "metadata": { + "id": "23adf208" + }, + "source": [ + "### Ask a virtual assistant\n", + "\n", + "As you work through this book, there are several ways you can use a virtual assistant or chatbot to help you learn.\n", + "\n", + "* If you want to learn more about a topic in the chapter, or anything is unclear, you can ask for an explanation.\n", + "\n", + "* If you are having a hard time with any of the exercises, you can ask for help.\n", + "\n", + "In each chapter, I'll suggest exercises you can do with a virtual assistant, but I encourage you to try things on your own and see what works for you." + ] + }, + { + "cell_type": "markdown", + "id": "ebf1a451", + "metadata": { + "id": "ebf1a451" + }, + "source": [ + "Here are some topics you could ask a virtual assistant about:\n", + "\n", + "* Earlier I mentioned bitwise operators but I didn't explain why the value of `7 ^ 2` is 5. Try asking \"What are the bitwise operators in Python?\" or \"What is the value of `7 XOR 2`?\"\n", + "\n", + "* I also mentioned the order of operations. For more details, ask \"What is the order of operations in Python?\"\n", + "\n", + "* The `round` function, which we used to round a floating-point number to the nearest integer, can take a second argument. Try asking \"What are the arguments of the round function?\" or \"How do I round pi off to three decimal places?\"\n", + "\n", + "* There's one more arithmetic operator I didn't mention; try asking \"What is the modulus operator in Python?\"" + ] + }, + { + "cell_type": "markdown", + "id": "9be3e1c7", + "metadata": { + "id": "9be3e1c7" + }, + "source": [ + "Most virtual assistants know about Python, so they answer questions like this pretty reliably.\n", + "But remember that these tools make mistakes.\n", + "If you get code from a chatbot, test it!" + ] + }, + { + "cell_type": "markdown", + "id": "03c1ef93", + "metadata": { + "id": "03c1ef93" + }, + "source": [ + "### Exercise\n", + "\n", + "You might wonder what `round` does if a number ends in `0.5`.\n", + "The answer is that it sometimes rounds up and sometimes rounds down.\n", + "Try these examples and see if you can figure out what rule it follows." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "5d358f37", + "metadata": { + "id": "5d358f37", + "outputId": "4ec13320-8728-41ca-9fbf-4bd4198bf024", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "42" + ] + }, + "metadata": {}, + "execution_count": 22 + } + ], + "source": [ + "round(42.5)" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "id": "12aa59a3", + "metadata": { + "id": "12aa59a3", + "outputId": "8991c4c2-b69b-41f1-8831-ff06c60ede29", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "44" + ] + }, + "metadata": {}, + "execution_count": 23 + } + ], + "source": [ + "round(43.5)" + ] + }, + { + "cell_type": "markdown", + "id": "dd2f890e", + "metadata": { + "id": "dd2f890e" + }, + "source": [ + "If you are curious, ask a virtual assistant, \"If a number ends in 0.5, does Python round up or down?\"" + ] + }, + { + "cell_type": "markdown", + "id": "2cd03bcb", + "metadata": { + "id": "2cd03bcb" + }, + "source": [ + "### Exercise\n", + "\n", + "When you learn about a new feature, you should try it out and make mistakes on purpose.\n", + "That way, you learn the error messages, and when you see them again, you will know what they mean.\n", + "It is better to make mistakes now and deliberately than later and accidentally.\n", + "\n", + "1. You can use a minus sign to make a negative number like `-2`. What happens if you put a plus sign before a number? What about `2++2`?\n", + "\n", + "2. What happens if you have two values with no operator between them, like `4 2`?\n", + "\n", + "3. If you call a function like `round(42.5)`, what happens if you leave out one or both parentheses?" + ] + }, + { + "cell_type": "markdown", + "id": "1fb0adfe", + "metadata": { + "id": "1fb0adfe" + }, + "source": [ + "### Exercise\n", + "\n", + "Recall that every expression has a value, every value has a type, and we can use the `type` function to find the type of any value.\n", + "\n", + "What is the type of the value of the following expressions? Make your best guess for each one, and then use `type` to find out.\n", + "\n", + "* `765`\n", + "\n", + "* `2.718`\n", + "\n", + "* `'2 pi'`\n", + "\n", + "* `abs(-7)`\n", + "\n", + "* `abs(-7.0)`\n", + "\n", + "* `abs`\n", + "\n", + "* `int`\n", + "\n", + "* `type`" + ] + }, + { + "cell_type": "markdown", + "id": "23762eec", + "metadata": { + "id": "23762eec" + }, + "source": [ + "### Exercise\n", + "\n", + "The following questions give you a chance to practice writing arithmetic expressions.\n", + "\n", + "1. How many seconds are there in 42 minutes 42 seconds?\n", + "\n", + "2. How many miles are there in 10 kilometers? Hint: there are 1.61 kilometers in a mile.\n", + "\n", + "3. If you run a 10 kilometer race in 42 minutes 42 seconds, what is your average pace in seconds per mile?\n", + " \n", + "4. What is your average pace in minutes and seconds per mile?\n", + "\n", + "5. What is your average speed in miles per hour?\n", + "\n", + "If you already know about variables, you can use them for this exercise.\n", + "If you don't, you can do the exercise without them -- and then we'll see them in the next chapter." + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "id": "8fb50f30", + "metadata": { + "id": "8fb50f30", + "outputId": "ac5edc12-ddb0-46b8-bc38-d0e0facfbe28", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "2562" + ] + }, + "metadata": {}, + "execution_count": 24 + } + ], + "source": [ + "# 1 Solution goes here\n", + "(42*60)+42" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "id": "5eceb4fb", + "metadata": { + "id": "5eceb4fb", + "outputId": "e9f342c2-7bec-4974-afe3-5ce1584e2b56", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "6.211180124223602" + ] + }, + "metadata": {}, + "execution_count": 27 + } + ], + "source": [ + "# 2 Solution goes here\n", + "10/1.61" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "id": "fee97d8d", + "metadata": { + "id": "fee97d8d", + "outputId": "802eb676-8db3-4cd7-bce2-bbfbd1c4b74c", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "412.482" + ] + }, + "metadata": {}, + "execution_count": 29 + } + ], + "source": [ + "# 3 Solution goes here\n", + "2562/6.211180124223602" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "id": "a998258c", + "metadata": { + "id": "a998258c", + "outputId": "2866df52-81e4-4264-d1b1-6b8b95cb0e14", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "6.874700000000001" + ] + }, + "metadata": {}, + "execution_count": 37 + } + ], + "source": [ + "# 4 Solution goes here\n", + "(412.482/60)" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "id": "2e0fc7a9", + "metadata": { + "id": "2e0fc7a9", + "outputId": "ed6e7479-3595-4ddc-972f-df820bee2d20", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "52.48200000000006" + ] + }, + "metadata": {}, + "execution_count": 35 + } + ], + "source": [ + "# 4a Solution goes here\n", + "(.874700000000001*60)" + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "id": "d25268d8", + "metadata": { + "id": "d25268d8", + "outputId": "327717c7-11b2-4e31-bba5-5b2f7bf3d01e", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "0.7" + ] + }, + "metadata": {}, + "execution_count": 40 + } + ], + "source": [ + "# 5 Solution goes here\n", + "42/60" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "id": "523d9b0f", + "metadata": { + "id": "523d9b0f", + "outputId": "834770a2-b2b5-4503-8c3b-9124f05e9513", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "0.011666666666666667" + ] + }, + "metadata": {}, + "execution_count": 44 + } + ], + "source": [ + "# 5a Solution goes here\n", + "42/(60*60)" + ] + }, + { + "cell_type": "code", + "execution_count": 46, + "id": "ca083ccf", + "metadata": { + "id": "ca083ccf", + "outputId": "42250d73-c427-4491-e851-20303c890251", + "colab": { + "base_uri": "https://localhost:8080/" + } + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "8.727653570337614" + ] + }, + "metadata": {}, + "execution_count": 46 + } + ], + "source": [ + "# 5c\n", + "6.211180124223602/(0.7+0.011666666666666667)" + ] + }, + { + "cell_type": "markdown", + "id": "a7f4edf8", + "metadata": { + "tags": [], + "id": "a7f4edf8" + }, + "source": [ + "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "\n", + "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "\n", + "Code license: [MIT License](https://mit-license.org/)\n", + "\n", + "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.10.11" + }, + "colab": { + "provenance": [], + "include_colab_link": true + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file From 732767ed86cd43d827eff7caaaca76f7fe2d0382 Mon Sep 17 00:00:00 2001 From: anthonyvantran Date: Thu, 26 Dec 2024 12:29:49 -0500 Subject: [PATCH 2/2] Think Python 3: Chapter 2 chapter and exercises --- chapters/chap02.ipynb | 1732 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 1732 insertions(+) create mode 100644 chapters/chap02.ipynb diff --git a/chapters/chap02.ipynb b/chapters/chap02.ipynb new file mode 100644 index 0000000..5aafc36 --- /dev/null +++ b/chapters/chap02.ipynb @@ -0,0 +1,1732 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "id": "view-in-github", + "colab_type": "text" + }, + "source": [ + "\"Open" + ] + }, + { + "cell_type": "markdown", + "id": "1331faa1", + "metadata": { + "id": "1331faa1" + }, + "source": [ + "You can order print and ebook versions of *Think Python 3e* from\n", + "[Bookshop.org](https://bookshop.org/a/98697/9781098155438) and\n", + "[Amazon](https://www.amazon.com/_/dp/1098155432?smid=ATVPDKIKX0DER&_encoding=UTF8&tag=oreilly20-20&_encoding=UTF8&tag=greenteapre01-20&linkCode=ur2&linkId=e2a529f94920295d27ec8a06e757dc7c&camp=1789&creative=9325)." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "id": "1a0a6ff4", + "metadata": { + "tags": [], + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "1a0a6ff4", + "outputId": "0deb85a3-c505-4cbe-8d48-64c6ac6bf894" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Downloaded thinkpython.py\n", + "Downloaded diagram.py\n" + ] + } + ], + "source": [ + "from os.path import basename, exists\n", + "\n", + "def download(url):\n", + " filename = basename(url)\n", + " if not exists(filename):\n", + " from urllib.request import urlretrieve\n", + "\n", + " local, _ = urlretrieve(url, filename)\n", + " print(\"Downloaded \" + str(local))\n", + " return filename\n", + "\n", + "download('https://github.com/AllenDowney/ThinkPython/raw/v3/thinkpython.py');\n", + "download('https://github.com/AllenDowney/ThinkPython/raw/v3/diagram.py');\n", + "\n", + "import thinkpython" + ] + }, + { + "cell_type": "markdown", + "id": "d0286422", + "metadata": { + "id": "d0286422" + }, + "source": [ + "# Variables and Statements\n", + "\n", + "In the previous chapter, we used operators to write expressions that perform arithmetic computations.\n", + "\n", + "In this chapter, you'll learn about variables and statements, the `import` statement, and the `print` function.\n", + "And I'll introduce more of the vocabulary we use to talk about programs, including \"argument\" and \"module\".\n" + ] + }, + { + "cell_type": "markdown", + "id": "4ac44f0c", + "metadata": { + "id": "4ac44f0c" + }, + "source": [ + "## Variables\n", + "\n", + "A **variable** is a name that refers to a value.\n", + "To create a variable, we can write a **assignment statement** like this." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "59f6db42", + "metadata": { + "id": "59f6db42" + }, + "outputs": [], + "source": [ + "n = 17" + ] + }, + { + "cell_type": "markdown", + "id": "52f187f1", + "metadata": { + "id": "52f187f1" + }, + "source": [ + "An assignment statement has three parts: the name of the variable on the left, the equals operator, `=`, and an expression on the right.\n", + "In this example, the expression is an integer.\n", + "In the following example, the expression is a floating-point number." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1301f6af", + "metadata": { + "id": "1301f6af" + }, + "outputs": [], + "source": [ + "pi = 3.141592653589793" + ] + }, + { + "cell_type": "markdown", + "id": "3e27e65c", + "metadata": { + "id": "3e27e65c" + }, + "source": [ + "And in the following example, the expression is a string." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "id": "f7adb732", + "metadata": { + "id": "f7adb732" + }, + "outputs": [], + "source": [ + "message = 'And now for something completely different'" + ] + }, + { + "cell_type": "markdown", + "source": [], + "metadata": { + "id": "fRudHYtOgDSH" + }, + "id": "fRudHYtOgDSH" + }, + { + "cell_type": "markdown", + "id": "cb5916ea", + "metadata": { + "id": "cb5916ea" + }, + "source": [ + "When you run an assignment statement, there is no output.\n", + "Python creates the variable and gives it a value, but the assignment statement has no visible effect.\n", + "However, after creating a variable, you can use it as an expression.\n", + "So we can display the value of `message` like this:" + ] + }, + { + "cell_type": "markdown", + "source": [], + "metadata": { + "id": "u0skQbxYgCF9" + }, + "id": "u0skQbxYgCF9" + }, + { + "cell_type": "code", + "execution_count": 2, + "id": "6bcc0a66", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 54 + }, + "id": "6bcc0a66", + "outputId": "ad45aca2-3ab6-47a0-ea9b-e57073ecbe22" + }, + "outputs": [ + { + "output_type": "error", + "ename": "NameError", + "evalue": "name 'message' is not defined", + "traceback": [ + "\u001b[0;31mNameError\u001b[0m\u001b[0;31m:\u001b[0m name 'message' is not defined\n" + ] + } + ], + "source": [ + "message" + ] + }, + { + "cell_type": "markdown", + "id": "e3fd81de", + "metadata": { + "id": "e3fd81de" + }, + "source": [ + "You can also use a variable as part of an expression with arithmetic operators." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "3f11f497", + "metadata": { + "id": "3f11f497" + }, + "outputs": [], + "source": [ + "n + 25" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "id": "6b2dafea", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/", + "height": 54 + }, + "id": "6b2dafea", + "outputId": "297cc86a-a6c8-465c-b272-239fd391a580" + }, + "outputs": [ + { + "output_type": "error", + "ename": "NameError", + "evalue": "name 'pi' is not defined", + "traceback": [ + "\u001b[0;31mNameError\u001b[0m\u001b[0;31m:\u001b[0m name 'pi' is not defined\n" + ] + } + ], + "source": [ + "2 * pi" + ] + }, + { + "cell_type": "markdown", + "id": "97396e7d", + "metadata": { + "id": "97396e7d" + }, + "source": [ + "And you can use a variable when you call a function." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "72c45ac5", + "metadata": { + "id": "72c45ac5" + }, + "outputs": [], + "source": [ + "round(pi)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "6bf81c52", + "metadata": { + "id": "6bf81c52" + }, + "outputs": [], + "source": [ + "len(message)" + ] + }, + { + "cell_type": "markdown", + "id": "397d9da3", + "metadata": { + "id": "397d9da3" + }, + "source": [ + "## State diagrams\n", + "\n", + "A common way to represent variables on paper is to write the name with\n", + "an arrow pointing to its value." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "id": "2c25e84e", + "metadata": { + "tags": [], + "id": "2c25e84e" + }, + "outputs": [], + "source": [ + "import math\n", + "\n", + "from diagram import make_binding, Frame\n", + "\n", + "binding = make_binding(\"message\", 'And now for something completely different')\n", + "binding2 = make_binding(\"n\", 17)\n", + "binding3 = make_binding(\"pi\", 3.141592653589793)\n", + "\n", + "frame = Frame([binding2, binding3, binding])" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "id": "5b27a635", + "metadata": { + "tags": [], + "colab": { + "base_uri": "https://localhost:8080/", + "height": 138 + }, + "id": "5b27a635", + "outputId": "3e74e35e-b089-4f9d-a8de-c65256176b39" + }, + "outputs": [ + { + "output_type": "display_data", + "data": { + "text/plain": [ + "
" + ], + "image/png": "iVBORw0KGgoAAAANSUhEUgAAAX4AAAB5CAYAAAA+qErwAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjguMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy81sbWrAAAACXBIWXMAAA9hAAAPYQGoP6dpAAAa9UlEQVR4nO3deVRW1f7H8TcIclVkUFEUU8tUSDRMkeEBHnDCkJtagaal2HA1y8qMTO1iYamVWXidcwhJLXJoQMPlhIkKrsylGaWEAg2EIMpBNAHZvz9YnF/IaFcl7/m+1mKteM7e++yzz34+zz7nwY6FUkohhBDCMCwbuwNCCCFuLQl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGAl+IYQwGA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Q4eUpmnqgw8+UD169FCFhYVq27ZtysLCQj+H1/7MnTtXTZgwodo8qqu/Y8aMUZ6enurs2bMqPz9f3XnnnSo0NFSdO3dO5eTkKCcnJ5Wamlrv/OnUqZNKTk5u0PgtW7ZMDRs2rEHnq127dio9PV1pmqamT59e6/maMWOGCgkJUXl5eVXeIzfq2P38/JTZbFbnzp1Tv//+u+rTp49atWpVtfMXERGhli9frjRNU4WFhWrcuHFqzpw51cppmqZWrVqlxo8fr86fP680TVMrVqxQQ4YM0cfv6aefVpqmqUWLFqmHH35Yr+fu7q4SExOrjUF8fLxydXVVv/zyiyosLFTh4eGqU6dOStM09d133yl7e/sa59y1v2dnZ6vevXvr75MzZ86ojh07qh9//FF99913CtCPsSHzYuLEiXo7dnZ26scff6yxD9f701A37dGLDz30EAB9+vShuLhY/71v376cPn0aqFjFnT59mvvvv1+vZ2lpyc8//4zJZOLf//43xcXFmEwmgoKCADCbzUyfPp0RI0YwYMAAfcV47NgxFixYQEFBAVZWVqSnp3P58mUyMjKwsrIiICAAgICAAO68804AiouL2bdvH3l5efr+L168SHp6erXjOXz4ML/99tuNHqZaubi4cP78eRITE9m9ezdhYWE4OzvXWj4+Pp5Bgwbh4OCAg4MDbdu21a+mAO666y48PT0B6N+/P4sWLQJg3759DB48WG/7iSee4N133611P4MGDdKvNPr3709aWhpQcZtp7Nix2NjYABAREcEHH3zA1KlTCQwMZO/eveTn5zNgwABOnjzJ999/z969ewkNDa13LL755ht69uypX26PGjWKl156ST8fXbp0wc/Pr8a6np6eLF26lJkzZ2IymfTVW139BRg2bBj/+Mc/AOjZsycDBw7E2toaa2trXF1dycjIoFOnTg2eP/WN37XqOl+DBg2iXbt2er/feuutGttITEwkOjpaP8Y2bdrcsGN3c3MDYPTo0fq28PBwkpKSCA8Pr9KPhIQEDh8+rF9NXr58mSZNmtTY523btvHtt9/q79erV6/WWG7UqFG8+eabnD17loyMDCwsLPD19a1Wbt++fYwcOVJfNT/++OOkpKTU2GZdUlNTyczM1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gJPiFEMJgJPiFEMJgJPiFEMJgJPiFEMJgJPiFEMJgJPiFEMJgJPiFEMJg/g+8mhM2m5RHHwAAAABJRU5ErkJggg==\n" + }, + "metadata": {} + } + ], + "source": [ + "from diagram import diagram, adjust\n", + "\n", + "\n", + "width, height, x, y = [3.62, 1.01, 0.6, 0.76]\n", + "ax = diagram(width, height)\n", + "bbox = frame.draw(ax, x, y, dy=-0.25)\n", + "# adjust(x, y, bbox)" + ] + }, + { + "cell_type": "markdown", + "id": "6f40da93", + "metadata": { + "id": "6f40da93" + }, + "source": [ + "This kind of figure is called a **state diagram** because it shows what state each of the variables is in (think of it as the variable's state of mind).\n", + "We'll use state diagrams throughout the book to represent a model of how Python stores variables and their values." + ] + }, + { + "cell_type": "markdown", + "id": "ba252c85", + "metadata": { + "id": "ba252c85" + }, + "source": [ + "## Variable names\n", + "\n", + "Variable names can be as long as you like. They can contain both letters and numbers, but they can't begin with a number.\n", + "It is legal to use uppercase letters, but it is conventional to use only lower case for\n", + "variable names.\n", + "\n", + "The only punctuation that can appear in a variable name is the underscore character, `_`. It is often used in names with multiple words, such as `your_name` or `airspeed_of_unladen_swallow`.\n", + "\n", + "If you give a variable an illegal name, you get a syntax error.\n", + "The name `million!` is illegal because it contains punctuation." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "ac2620ef", + "metadata": { + "tags": [], + "id": "ac2620ef" + }, + "outputs": [], + "source": [ + "%%expect SyntaxError\n", + "\n", + "million! = 1000000" + ] + }, + { + "cell_type": "markdown", + "id": "a1cefe3e", + "metadata": { + "id": "a1cefe3e" + }, + "source": [ + "`76trombones` is illegal because it starts with a number." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "1a8b8382", + "metadata": { + "tags": [], + "id": "1a8b8382" + }, + "outputs": [], + "source": [ + "%%expect SyntaxError\n", + "\n", + "76trombones = 'big parade'" + ] + }, + { + "cell_type": "markdown", + "id": "94aa7e60", + "metadata": { + "id": "94aa7e60" + }, + "source": [ + "`class` is also illegal, but it might not be obvious why." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "b6938851", + "metadata": { + "tags": [], + "id": "b6938851" + }, + "outputs": [], + "source": [ + "%%expect SyntaxError\n", + "\n", + "class = 'Self-Defence Against Fresh Fruit'" + ] + }, + { + "cell_type": "markdown", + "id": "784cfb5c", + "metadata": { + "id": "784cfb5c" + }, + "source": [ + "It turns out that `class` is a **keyword**, which is a special word used to specify the structure of a program.\n", + "Keywords can't be used as variable names.\n", + "\n", + "Here's a complete list of Python's keywords:" + ] + }, + { + "cell_type": "markdown", + "id": "127c07e8", + "metadata": { + "id": "127c07e8" + }, + "source": [ + "```\n", + "False await else import pass\n", + "None break except in raise\n", + "True class finally is return\n", + "and continue for lambda try\n", + "as def from nonlocal while\n", + "assert del global not with\n", + "async elif if or yield\n", + "```" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "id": "4a8f4b3e", + "metadata": { + "tags": [], + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "4a8f4b3e", + "outputId": "ad96d77e-8fd3-480f-db63-cdfecb5349aa" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "35" + ] + }, + "metadata": {}, + "execution_count": 7 + } + ], + "source": [ + "from keyword import kwlist\n", + "\n", + "len(kwlist)" + ] + }, + { + "cell_type": "markdown", + "id": "6f14d301", + "metadata": { + "id": "6f14d301" + }, + "source": [ + "You don't have to memorize this list. In most development environments,\n", + "keywords are displayed in a different color; if you try to use one as a\n", + "variable name, you'll know." + ] + }, + { + "cell_type": "markdown", + "id": "c954a3b0", + "metadata": { + "id": "c954a3b0" + }, + "source": [ + "## The import statement\n", + "\n", + "In order to use some Python features, you have to **import** them.\n", + "For example, the following statement imports the `math` module." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "98c268e9", + "metadata": { + "id": "98c268e9" + }, + "outputs": [], + "source": [ + "import math" + ] + }, + { + "cell_type": "markdown", + "id": "ea4f75ec", + "metadata": { + "id": "ea4f75ec" + }, + "source": [ + "A **module** is a collection of variables and functions.\n", + "The math module provides a variable called `pi` that contains the value of the mathematical constant denoted $\\pi$.\n", + "We can display its value like this." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "47bc17c9", + "metadata": { + "id": "47bc17c9" + }, + "outputs": [], + "source": [ + "math.pi" + ] + }, + { + "cell_type": "markdown", + "id": "c96106e4", + "metadata": { + "id": "c96106e4" + }, + "source": [ + "To use a variable in a module, you have to use the **dot operator** (`.`) between the name of the module and the name of the variable.\n", + "\n", + "The math module also contains functions.\n", + "For example, `sqrt` computes square roots." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "fd1cec63", + "metadata": { + "id": "fd1cec63" + }, + "outputs": [], + "source": [ + "math.sqrt(25)" + ] + }, + { + "cell_type": "markdown", + "id": "185e94a3", + "metadata": { + "id": "185e94a3" + }, + "source": [ + "And `pow` raises one number to the power of a second number." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "87316ddd", + "metadata": { + "id": "87316ddd" + }, + "outputs": [], + "source": [ + "math.pow(5, 2)" + ] + }, + { + "cell_type": "markdown", + "id": "5df25a9a", + "metadata": { + "id": "5df25a9a" + }, + "source": [ + "At this point we've seen two ways to raise a number to a power: we can use the `math.pow` function or the exponentiation operator, `**`.\n", + "Either one is fine, but the operator is used more often than the function." + ] + }, + { + "cell_type": "markdown", + "id": "6538f22b", + "metadata": { + "id": "6538f22b" + }, + "source": [ + "## Expressions and statements\n", + "\n", + "So far, we've seen a few kinds of expressions.\n", + "An expression can be a single value, like an integer, floating-point number, or string.\n", + "It can also be a collection of values and operators.\n", + "And it can include variable names and function calls.\n", + "Here's an expression that includes several of these elements." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7f0b92df", + "metadata": { + "id": "7f0b92df" + }, + "outputs": [], + "source": [ + "19 + n + round(math.pi) * 2" + ] + }, + { + "cell_type": "markdown", + "id": "000dd2ba", + "metadata": { + "id": "000dd2ba" + }, + "source": [ + "We have also seen a few kind of statements.\n", + "A **statement** is a unit of code that has an effect, but no value.\n", + "For example, an assignment statement creates a variable and gives it a value, but the statement itself has no value." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "id": "b882c340", + "metadata": { + "id": "b882c340" + }, + "outputs": [], + "source": [ + "n = 17" + ] + }, + { + "cell_type": "markdown", + "id": "cff0414b", + "metadata": { + "id": "cff0414b" + }, + "source": [ + "Similarly, an import statement has an effect -- it imports a module so we can use the variables and functions it contains -- but it has no visible effect." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "299817d8", + "metadata": { + "id": "299817d8" + }, + "outputs": [], + "source": [ + "import math" + ] + }, + { + "cell_type": "markdown", + "id": "2aeb1000", + "metadata": { + "id": "2aeb1000" + }, + "source": [ + "Computing the value of an expression is called **evaluation**.\n", + "Running a statement is called **execution**." + ] + }, + { + "cell_type": "markdown", + "id": "f61601e4", + "metadata": { + "id": "f61601e4" + }, + "source": [ + "## The print function\n", + "\n", + "When you evaluate an expression, the result is displayed." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "id": "805977c6", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "805977c6", + "outputId": "7cea05f7-2d4e-4d85-e7ee-68ddc354f302" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "18" + ] + }, + "metadata": {}, + "execution_count": 9 + } + ], + "source": [ + "n + 1" + ] + }, + { + "cell_type": "markdown", + "id": "efacf0fa", + "metadata": { + "id": "efacf0fa" + }, + "source": [ + "But if you evaluate more than one expression, only the value of the last one is displayed." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "id": "962e08ab", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "962e08ab", + "outputId": "8167974f-edc2-4e9b-d114-90047ecc3dc5" + }, + "outputs": [ + { + "output_type": "execute_result", + "data": { + "text/plain": [ + "20" + ] + }, + "metadata": {}, + "execution_count": 10 + } + ], + "source": [ + "n + 2\n", + "n + 3" + ] + }, + { + "cell_type": "markdown", + "id": "cf2b991d", + "metadata": { + "id": "cf2b991d" + }, + "source": [ + "To display more than one value, you can use the `print` function." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "id": "a797e44d", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "a797e44d", + "outputId": "9cc22e7a-37ba-4acd-f46e-02cb991dbb64" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "19\n", + "20\n" + ] + } + ], + "source": [ + "print(n+2)\n", + "print(n+3)" + ] + }, + { + "cell_type": "markdown", + "id": "29af1f89", + "metadata": { + "id": "29af1f89" + }, + "source": [ + "It also works with floating-point numbers and strings." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "id": "73428520", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "73428520", + "outputId": "ef2ae78e-5670-4088-b8ee-310b80fe0d38" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "The value of pi is approximately\n", + "3.141592653589793\n" + ] + } + ], + "source": [ + "print('The value of pi is approximately')\n", + "print(math.pi)" + ] + }, + { + "cell_type": "markdown", + "id": "8b4d7f4a", + "metadata": { + "id": "8b4d7f4a" + }, + "source": [ + "You can also use a sequence of expressions separated by commas." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "id": "9ad5bddd", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "9ad5bddd", + "outputId": "e421ccd5-62cf-4bdd-dc53-32d4338d8dc9" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "The value of pi is approximately 3.141592653589793\n" + ] + } + ], + "source": [ + "print('The value of pi is approximately', math.pi)" + ] + }, + { + "cell_type": "code", + "source": [ + "print('Hello',\"World\")" + ], + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "lb6MFnPEjtH-", + "outputId": "12b17999-a732-4966-e641-34712000752e" + }, + "id": "lb6MFnPEjtH-", + "execution_count": 14, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "Hello World\n" + ] + } + ] + }, + { + "cell_type": "markdown", + "id": "af447ec4", + "metadata": { + "id": "af447ec4" + }, + "source": [ + "Notice that the `print` function puts a space between the values." + ] + }, + { + "cell_type": "markdown", + "id": "7c73a2fa", + "metadata": { + "id": "7c73a2fa" + }, + "source": [ + "## Arguments\n", + "\n", + "When you call a function, the expression in parenthesis is called an **argument**.\n", + "Normally I would explain why, but in this case the technical meaning of a term has almost nothing to do with the common meaning of the word, so I won't even try.\n", + "\n", + "Some of the functions we've seen so far take only one argument, like `int`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "060c60cf", + "metadata": { + "id": "060c60cf" + }, + "outputs": [], + "source": [ + "int('101')" + ] + }, + { + "cell_type": "markdown", + "id": "c4ad4f2c", + "metadata": { + "id": "c4ad4f2c" + }, + "source": [ + "Some take two, like `math.pow`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2875d9e0", + "metadata": { + "id": "2875d9e0" + }, + "outputs": [], + "source": [ + "math.pow(5, 2)" + ] + }, + { + "cell_type": "markdown", + "id": "17293749", + "metadata": { + "id": "17293749" + }, + "source": [ + "Some can take additional arguments that are optional.\n", + "For example, `int` can take a second argument that specifies the base of the number." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "43b9cf38", + "metadata": { + "id": "43b9cf38" + }, + "outputs": [], + "source": [ + "int('101', 2)" + ] + }, + { + "cell_type": "markdown", + "id": "c95589a1", + "metadata": { + "id": "c95589a1" + }, + "source": [ + "The sequence of digits `101` in base 2 represents the number 5 in base 10.\n", + "\n", + "`round` also takes an optional second argument, which is the number of decimal places to round off to." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "e8a21d05", + "metadata": { + "id": "e8a21d05" + }, + "outputs": [], + "source": [ + "round(math.pi, 3)" + ] + }, + { + "cell_type": "markdown", + "id": "21e4a448", + "metadata": { + "id": "21e4a448" + }, + "source": [ + "Some functions can take any number of arguments, like `print`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "724128f4", + "metadata": { + "id": "724128f4" + }, + "outputs": [], + "source": [ + "print('Any', 'number', 'of', 'arguments')" + ] + }, + { + "cell_type": "markdown", + "id": "667cff14", + "metadata": { + "id": "667cff14" + }, + "source": [ + "If you call a function and provide too many arguments, that's a `TypeError`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "69295e52", + "metadata": { + "tags": [], + "id": "69295e52" + }, + "outputs": [], + "source": [ + "%%expect TypeError\n", + "\n", + "float('123.0', 2)" + ] + }, + { + "cell_type": "markdown", + "id": "5103368e", + "metadata": { + "id": "5103368e" + }, + "source": [ + "If you provide too few arguments, that's also a `TypeError`." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "edec7064", + "metadata": { + "tags": [], + "id": "edec7064" + }, + "outputs": [], + "source": [ + "%%expect TypeError\n", + "\n", + "math.pow(2)" + ] + }, + { + "cell_type": "markdown", + "id": "5333c416", + "metadata": { + "id": "5333c416" + }, + "source": [ + "And if you provide an argument with a type the function can't handle, that's a `TypeError`, too." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "f86b2896", + "metadata": { + "tags": [], + "id": "f86b2896" + }, + "outputs": [], + "source": [ + "%%expect TypeError\n", + "\n", + "math.sqrt('123')" + ] + }, + { + "cell_type": "markdown", + "id": "548828af", + "metadata": { + "id": "548828af" + }, + "source": [ + "This kind of checking can be annoying when you are getting started, but it helps you detect and correct errors." + ] + }, + { + "cell_type": "markdown", + "id": "be2b6a9b", + "metadata": { + "id": "be2b6a9b" + }, + "source": [ + "## Comments\n", + "\n", + "As programs get bigger and more complicated, they get more difficult to read.\n", + "Formal languages are dense, and it is often difficult to look at a piece of code and figure out what it is doing and why.\n", + "\n", + "For this reason, it is a good idea to add notes to your programs to explain in natural language what the program is doing.\n", + "These notes are called **comments**, and they start with the `#` symbol." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "607893a6", + "metadata": { + "id": "607893a6" + }, + "outputs": [], + "source": [ + "# number of seconds in 42:42\n", + "seconds = 42 * 60 + 42" + ] + }, + { + "cell_type": "markdown", + "id": "519c83a9", + "metadata": { + "id": "519c83a9" + }, + "source": [ + "In this case, the comment appears on a line by itself. You can also put\n", + "comments at the end of a line:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "615a11e7", + "metadata": { + "id": "615a11e7" + }, + "outputs": [], + "source": [ + "miles = 10 / 1.61 # 10 kilometers in miles" + ] + }, + { + "cell_type": "markdown", + "id": "87c8d10c", + "metadata": { + "id": "87c8d10c" + }, + "source": [ + "Everything from the `#` to the end of the line is ignored---it has no\n", + "effect on the execution of the program.\n", + "\n", + "Comments are most useful when they document non-obvious features of the code.\n", + "It is reasonable to assume that the reader can figure out *what* the code does; it is more useful to explain *why*.\n", + "\n", + "This comment is redundant with the code and useless:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "cc7fe2e6", + "metadata": { + "id": "cc7fe2e6" + }, + "outputs": [], + "source": [ + "v = 8 # assign 8 to v" + ] + }, + { + "cell_type": "markdown", + "id": "eb83b14a", + "metadata": { + "id": "eb83b14a" + }, + "source": [ + "This comment contains useful information that is not in the code:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "7c93a00d", + "metadata": { + "id": "7c93a00d" + }, + "outputs": [], + "source": [ + "v = 8 # velocity in miles per hour" + ] + }, + { + "cell_type": "markdown", + "id": "6cd60d4f", + "metadata": { + "id": "6cd60d4f" + }, + "source": [ + "Good variable names can reduce the need for comments, but long names can\n", + "make complex expressions hard to read, so there is a tradeoff." + ] + }, + { + "cell_type": "markdown", + "id": "7d61e416", + "metadata": { + "id": "7d61e416" + }, + "source": [ + "## Debugging\n", + "\n", + "Three kinds of errors can occur in a program: syntax errors, runtime errors, and semantic errors.\n", + "It is useful to distinguish between them in order to track them down more quickly.\n", + "\n", + "* **Syntax error**: \"Syntax\" refers to the structure of a program and the rules about that structure. If there is a syntax error anywhere in your program, Python does not run the program. It displays an error message immediately.\n", + "\n", + "* **Runtime error**: If there are no syntax errors in your program, it can start running. But if something goes wrong, Python displays an error message and stops. This type of error is called a runtime error. It is also called an **exception** because it indicates that something exceptional has happened.\n", + "\n", + "* **Semantic error**: The third type of error is \"semantic\", which means related to meaning. If there is a semantic error in your program, it runs without generating error messages, but it does not do what you intended. Identifying semantic errors can be tricky because it requires you to work backward by looking at the output of the program and trying to figure out what it is doing." + ] + }, + { + "cell_type": "markdown", + "id": "6cd52721", + "metadata": { + "id": "6cd52721" + }, + "source": [ + "As we've seen, an illegal variable name is a syntax error." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "86f07f6e", + "metadata": { + "tags": [], + "id": "86f07f6e" + }, + "outputs": [], + "source": [ + "%%expect SyntaxError\n", + "\n", + "million! = 1000000" + ] + }, + { + "cell_type": "markdown", + "id": "b8971d33", + "metadata": { + "id": "b8971d33" + }, + "source": [ + "If you use an operator with a type it doesn't support, that's a runtime error." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "682395ea", + "metadata": { + "tags": [], + "id": "682395ea" + }, + "outputs": [], + "source": [ + "%%expect TypeError\n", + "\n", + "'126' / 3" + ] + }, + { + "cell_type": "markdown", + "id": "e51fa6e2", + "metadata": { + "id": "e51fa6e2" + }, + "source": [ + "Finally, here's an example of a semantic error.\n", + "Suppose we want to compute the average of `1` and `3`, but we forget about the order of operations and write this:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "2ff25bda", + "metadata": { + "id": "2ff25bda" + }, + "outputs": [], + "source": [ + "1 + 3 / 2" + ] + }, + { + "cell_type": "markdown", + "id": "0828afc0", + "metadata": { + "id": "0828afc0" + }, + "source": [ + "When this expression is evaluated, it does not produce an error message, so there is no syntax error or runtime error.\n", + "But the result is not the average of `1` and `3`, so the program is not correct.\n", + "This is a semantic error because the program runs but it doesn't do what's intended." + ] + }, + { + "cell_type": "markdown", + "id": "07396f3d", + "metadata": { + "id": "07396f3d" + }, + "source": [ + "## Glossary\n", + "\n", + "**variable:**\n", + "A name that refers to a value.\n", + "\n", + "**assignment statement:**\n", + "A statement that assigns a value to a variable.\n", + "\n", + "**state diagram:**\n", + "A graphical representation of a set of variables and the values they refer to.\n", + "\n", + "**keyword:**\n", + "A special word used to specify the structure of a program.\n", + "\n", + "**import statement:**\n", + "A statement that reads a module file so we can use the variables and functions it contains.\n", + "\n", + "**module:**\n", + "A file that contains Python code, including function definitions and sometimes other statements.\n", + "\n", + "**dot operator:**\n", + "The operator, `.`, used to access a function in another module by specifying the module name followed by a dot and the function name.\n", + "\n", + "**evaluate:**\n", + "Perform the operations in an expression in order to compute a value.\n", + "\n", + "**statement:**\n", + "One or more lines of code that represent a command or action.\n", + "\n", + "**execute:**\n", + "Run a statement and do what it says.\n", + "\n", + "**argument:**\n", + "A value provided to a function when the function is called.\n", + "\n", + "**comment:**\n", + "Text included in a program that provides information about the program but has no effect on its execution.\n", + "\n", + "**runtime error:**\n", + "An error that causes a program to display an error message and exit.\n", + "\n", + "**exception:**\n", + "An error that is detected while the program is running.\n", + "\n", + "**semantic error:**\n", + "An error that causes a program to do the wrong thing, but not to display an error message." + ] + }, + { + "cell_type": "markdown", + "id": "70ee273d", + "metadata": { + "id": "70ee273d" + }, + "source": [ + "## Exercises" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "c9e6cab4", + "metadata": { + "tags": [], + "id": "c9e6cab4" + }, + "outputs": [], + "source": [ + "# This cell tells Jupyter to provide detailed debugging information\n", + "# when a runtime error occurs. Run it before working on the exercises.\n", + "\n", + "%xmode Verbose" + ] + }, + { + "cell_type": "markdown", + "id": "7256a9b2", + "metadata": { + "id": "7256a9b2" + }, + "source": [ + "### Ask a virtual assistant\n", + "\n", + "Again, I encourage you to use a virtual assistant to learn more about any of the topics in this chapter.\n", + "\n", + "If you are curious about any of keywords I listed, you could ask \"Why is class a keyword?\" or \"Why can't variable names be keywords?\"\n", + "\n", + "You might have noticed that `int`, `float`, and `str` are not Python keywords.\n", + "They are variables that represent types, and they can be used as functions.\n", + "So it is *legal* to have a variable or function with one of those names, but it is strongly discouraged. Ask an assistant \"Why is it bad to use int, float, and str as variable names?\"\n", + "\n", + "Also ask, \"What are the built-in functions in Python?\"\n", + "If you are curious about any of them, ask for more information.\n", + "\n", + "In this chapter we imported the `math` module and used some of the variable and functions it provides. Ask an assistant, \"What variables and functions are in the math module?\" and \"Other than math, what modules are considered core Python?\"" + ] + }, + { + "cell_type": "markdown", + "id": "f92afde0", + "metadata": { + "id": "f92afde0" + }, + "source": [ + "### Exercise\n", + "\n", + "Repeating my advice from the previous chapter, whenever you learn a new feature, you should make errors on purpose to see what goes wrong.\n", + "\n", + "- We've seen that `n = 17` is legal. What about `17 = n`?\n", + "\n", + "- How about `x = y = 1`?\n", + "\n", + "- In some languages every statement ends with a semi-colon (`;`). What\n", + " happens if you put a semi-colon at the end of a Python statement?\n", + "\n", + "- What if you put a period at the end of a statement?\n", + "\n", + "- What happens if you spell the name of a module wrong and try to import `maath`?" + ] + }, + { + "cell_type": "markdown", + "id": "9d562609", + "metadata": { + "id": "9d562609" + }, + "source": [ + "### Exercise\n", + "Practice using the Python interpreter as a calculator:\n", + "\n", + "**Part 1.** The volume of a sphere with radius $r$ is $\\frac{4}{3} \\pi r^3$.\n", + "What is the volume of a sphere with radius 5? Start with a variable named `radius` and then assign the result to a variable named `volume`. Display the result. Add comments to indicate that `radius` is in centimeters and `volume` in cubic centimeters." + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "id": "18de7d96", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "18de7d96", + "outputId": "63e59a61-06fa-4ac4-9920-6d47d46da6dd" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "523.5987755982989\n" + ] + } + ], + "source": [ + "# Solution goes here\n", + "\n", + "import math\n", + "#radius is in centimeters\n", + "radius = 5\n", + "volume = (4/3)*math.pi*math.pow(radius, 3)\n", + "#volume is in cubic centimeters\n", + "print(volume)" + ] + }, + { + "cell_type": "markdown", + "id": "6449b12b", + "metadata": { + "id": "6449b12b" + }, + "source": [ + "**Part 2.** A rule of trigonometry says that for any value of $x$, $(\\cos x)^2 + (\\sin x)^2 = 1$. Let's see if it's true for a specific value of $x$ like 42.\n", + "\n", + "Create a variable named `x` with this value.\n", + "Then use `math.cos` and `math.sin` to compute the sine and cosine of $x$, and the sum of their squared.\n", + "\n", + "The result should be close to 1. It might not be exactly 1 because floating-point arithmetic is not exact---it is only approximately correct." + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "id": "de812cff", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "de812cff", + "outputId": "ffb98b20-e9f5-4579-e198-842a9e0d3a37" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "1.0\n" + ] + } + ], + "source": [ + "# Solution goes here\n", + "\n", + "import math\n", + "x=42\n", + "answer = math.pow(math.cos(x),2) + math.pow(math.sin(x),2)\n", + "print(answer)\n" + ] + }, + { + "cell_type": "markdown", + "id": "4986801f", + "metadata": { + "id": "4986801f" + }, + "source": [ + "**Part 3.** In addition to `pi`, the other variable defined in the `math` module is `e`, which represents the base of the natural logarithm, written in math notation as $e$. If you are not familiar with this value, ask a virtual assistant \"What is `math.e`?\" Now let's compute $e^2$ three ways:\n", + "\n", + "* Use `math.e` and the exponentiation operator (`**`).\n", + "\n", + "* Use `math.pow` to raise `math.e` to the power `2`.\n", + "\n", + "* Use `math.exp`, which takes as an argument a value, $x$, and computes $e^x$.\n", + "\n", + "You might notice that the last result is slightly different from the other two.\n", + "See if you can find out which is correct." + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "id": "b4ada618", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "b4ada618", + "outputId": "c88e184e-a922-43df-ce94-88286c663d0c" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "7.3890560989306495\n" + ] + } + ], + "source": [ + "# Solution goes here\n", + "\n", + "import math\n", + "x = math.e ** 2\n", + "print(x)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "id": "4424940f", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "4424940f", + "outputId": "da11e887-d6d1-4bc4-bfe9-d78181514bb5" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "7.3890560989306495\n" + ] + } + ], + "source": [ + "# Solution goes here\n", + "\n", + "import math\n", + "y = math.pow(math.e, 2)\n", + "print(y)" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "id": "50e8393a", + "metadata": { + "colab": { + "base_uri": "https://localhost:8080/" + }, + "id": "50e8393a", + "outputId": "9e36899f-fbaa-4478-bfef-769f6169a207" + }, + "outputs": [ + { + "output_type": "stream", + "name": "stdout", + "text": [ + "7.38905609893065\n" + ] + } + ], + "source": [ + "# Solution goes here\n", + "\n", + "import math\n", + "z = math.exp(2)\n", + "print(z)\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "id": "91e5a869", + "metadata": { + "id": "91e5a869" + }, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "id": "a7f4edf8", + "metadata": { + "tags": [], + "id": "a7f4edf8" + }, + "source": [ + "[Think Python: 3rd Edition](https://allendowney.github.io/ThinkPython/index.html)\n", + "\n", + "Copyright 2024 [Allen B. Downey](https://allendowney.com)\n", + "\n", + "Code license: [MIT License](https://mit-license.org/)\n", + "\n", + "Text license: [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International](https://creativecommons.org/licenses/by-nc-sa/4.0/)" + ] + } + ], + "metadata": { + "celltoolbar": "Tags", + "kernelspec": { + "display_name": "Python 3 (ipykernel)", + "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.10.11" + }, + "vscode": { + "interpreter": { + "hash": "357b915890fbc73e00b3ee3cc7035b34e6189554c2854644fe780ff20c2fdfc0" + } + }, + "colab": { + "provenance": [], + "include_colab_link": true + } + }, + "nbformat": 4, + "nbformat_minor": 5 +} \ No newline at end of file