{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Basics\n", "This notebook will walk through some of the basics of Python:\n", "\n", "* hello world program\n", "* literal types\n", "* variables\n", "* operators and expressions" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Hello World\n", "This is typically the first program you'll write in any language. The goal is to get the language to run a program that prints out the string `Hello World!`. In python, we can print using a function called `print()`. We'll talk more about functions later, but for now, just think of it like a function in math that takes an input and does something with it (in this case it prints it out)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Hello World!\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Basic Types\n", "In the hello world example above, the input to the function was a string, but it could have just as easily been a number." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(5)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Both numbers and strings are basic types, and any instance of these is known as a literal. The basic types in python and a few corresponding literal values are:\n", "\n", "* int: `1`, `-2`, `-1000`\n", "* float: `0.5`, `2.73`, `-18.945`\n", "* complex: `5j` \n", "* str: `'abc', \"hello\"`\n", "* bool: `True`, `False`\n", "* NoneType: `None` (this one is special - you'll understand it's purpose more later)\n", "\n", "So, let's look at the value -2. We can type this in, print it, etc. We can check what type it is by using the `type()` function." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(-2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Let's look at these for some of the others:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(5j)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "#### Important Notes\n", "* If you are paying close attention, you'll notice the output from `type()` looks a little different from the what you may see elsewhere. This is an artifact of jupyter notebooks. We're never actually printing the output of `type()`, but the default for a notebook is to display the output of the last command in the code block, and it displays it using a slightly different function. You can see the exact output you'd likely see elsewhere\n", "by using `print()` as well (though there's really no need to *unless you want the output for more than one line in a single code block*)." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(type(-2))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "* Numerical types (`int`, `float`, `complex`) cannot contains strings, but strings can have numbers if they are enclosed in quotes" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(\"2.73\")" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Strings can use either single `'hi'` or double `\"hi\"` quotes, but you cannot mix them in a single string" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'hi\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Strings that need to have quotes inside should use the other kind to denote them as a string (or escape using `\\`)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "'won\\'t'" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"won't\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "* Don't include commas in numbers in Python (they'll mean something different)\n", "* You can use scientific notation via `e` in the number (no spaces)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "1.1e5" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "1e-3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Variables\n", "Just entering the values isn't very helpful, sometimes we want to store a value and manipulate it. A **variable** is a name that refers to a value. We can create variables with assignment statements:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "var1 = 5\n", "var2 = \"hello\"\n", "var3 = 7.8" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Notice there was no output, because all that happened was binding of the names on the left to the literal values on the right. The same way we could `print()` a literal, we can `print()` a variable to see it's value. This is far more helpful than printing the value of a literal!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(var1)\n", "print(var2)\n", "print(var3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The value a variable refers to can change over the course of the program. Let's change the value of one of our variables." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(var1)\n", "var1 = 10\n", "print(var1)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Note that we can change more than just the value, the variable can be changed to refer to a different type. If you've used a different programming language before, this is a little different." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(var1)\n", "print(type(var1))\n", "var1 = \"goodbye\"\n", "print(var1)\n", "print(type(var1))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Variable Names\n", "Consider the following block of code. What do you think it does? Is it obvious? If this was your code and you didn't use it for 6 months, would you have any idea it's purpose when you came back to it? If someone else gave you this, how would you know what it means? " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "b = 4\n", "c = 1\n", "d = 6\n", "a = b + c*d" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, consider the same exact code with different variable names. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "init_velocity = 4\n", "acceleration = 1\n", "time = 6\n", "velocity = init_velocity + acceleration*time" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Quite a bit easier to understand, right? Using descriptive variable names is crucial. The general consensus is to use short, but still descriptive variable names. They should be document the actual purpose of the variable. However, because programmers are often lazy (and you'll be typing your variable names a lot), it's not uncommon to abbreviate them slightly. For instance we could have used `t` instead of `time` and still easily understood what it meant." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "##### Requirements for Variable Names\n", "Descriptive variable names are extremely important, but not required by the python itself. There are some rules and conventions for variable names, however:\n", "\n", "* can contain only uppercase and lowercase letters, numbers, and underscores\n", "* cannot start with a number\n", "* cannot contain other characters\n", "* cannot be any of [python's keywords](https://docs.python.org/3/reference/lexical_analysis.html#keywords)\n", "\n", "\n", "##### Conventions for Variable Names\n", "* descriptive, but concise\n", "* choose either all lowercase with underscores separating words or camelCase (first word lowercase, all other start with capital letters)\n", "* only start a variable with an underscore in very specific cases (if you are creating a python package others will use and you want it to be an internal variable)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "string_of_vowels = \"aeiou\"\n", "stringOfVowels = \"aeiou\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Basics\n", "Now that we've covered the basic types and variables provided by Python, let's go through some of the basic operations that can be performed. We'll get into far more advanced operations that can be performed through functions later -- for now we'll just take a look at a few of the basic operators.\n", "\n", "## Operators\n", "Python has the standard operators:\n", "\n", "* `+` : addition\n", "* `-` : subtraction\n", "* `*` : multiplication\n", "* `/` : division\n", "* `**` : exponentiation\n", "\n", "Operators are used in the general form ` `, where each `` can be either a variable name or a literal. When acting on `int` and `float` types, these operators behave as expected. For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "1 + 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 7\n", "x + 1" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "y = 8\n", "x + y" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "p = 2\n", "q = 5\n", "p**q" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "If desired (more often than not it is), the result can be assigned to a variable." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "z = x + y\n", "print(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The variable being assigned to can also be one of the operators, which modifies the value of that variable:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 7\n", "y = 8\n", "print(x)\n", "x = x+y\n", "print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "This can also be done in shorthand via the use of ` += `, which is equivalent to ` = + `. Likewise, this can also be done with `*=`, `/=` and `-=`." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "x = 7\n", "y = 8.0\n", "print(x)\n", "x += y\n", "print(x)\n", "print(type(y))\n", "print(type(x))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Order of Operations\n", "\n", "Operations can be chained together, much like you would write a larger expression in math. When chained together, they follow the same precedence rules you are familiar with (\"please excuse my dear aunt sally\"), and you can use parentheses to force the expression to evaluate in a specific order. " ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "z = (x*2 + y*3)/3\n", "print(z)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Type after Operations\n", "If you've been paying close attention, you may have noticed that sometimes the output is `.0` when other times there is no decimal place. This corresponds to it's type (so above `z` which has value 18.0 is of type `float` while `x` which has value 15 is of type `int`). The type is inherited from the types of the operands. If an operand is of type `float`, then the result after one of the operations above with another operand is of type `float` (which will cascade through sequences of many operations). However, if they are all of type `int`, the result will also be an `int` unless division is involved. For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(z)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(x)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(3/2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(3.0*2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(3**2)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Additional Operators\n", "In addition to the operators described above, there are 2 additional common operators (with the same precedence as multiplication and division):\n", " \n", "* `//` : integer division -- this operates on integers and performs division where the result is rounded down \n", "* `%` : modulo -- this operates on integers and gives the remainder after integer division\n", "\n", "For example:" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "num_batches = 3\n", "cookies_per_batch = 16\n", "cookies_per_person = 5\n", "leftover = num_batches * cookies_per_batch % cookies_per_person\n", "num_people_fed = num_batches * cookies_per_batch // cookies_per_person\n", "\n", "print(leftover)\n", "print(num_people_fed)" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.8.6" } }, "nbformat": 4, "nbformat_minor": 4 }