{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "\"Open " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python basics\n", "In this section, we will cover some basic python concepts. Python is an extremely quick language to learn, but like most programming languages, can take a long time to master. In this class, we'll focus on a different style of programming than typical software development, programming with data. This will but less of a burden on us to be expert software developers in python, but some amount of base language knowledge is unavoidable. So, let's get started learning some of the python programming basics. I'm going to assume you've programmed before in some language. If that isn't the case, consider starting with a basic programming course of study before trying this book.\n", "\n", "A great resource for learning basic python is the python.org documentation [https://docs.python.org/3/tutorial/index.html](https://docs.python.org/3/tutorial/index.html). My favorite programming resource of all time is the \"Learn X in Y\" tutorials. Here's one for python [https://learnxinyminutes.com/docs/python/](https://learnxinyminutes.com/docs/python/)." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Some of the basic programming types in python are ints, floats, complex and Boolean. The command `type` tells us which. Here's an example with 10 represented in 4 ways (int, float, string and complex) and the logical value `True`. Note, we're using `print` to print out the result of the `type` command. If you're typing directly into the python command line (called the repl, for read, evaluate, print, loop), you won't need the print statements. But, if you're using a notebook you probably will.\n", "\n", "If you want an easy repl environment to program in, try [https://replit.com/](https://replit.com/). For an easy notebook solution to try out, look at google colab, [https://colab.research.google.com](https://colab.research.google.com) ." ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n", "\n", "\n" ] } ], "source": [ "print(type(10))\n", "print(type(10.0))\n", "print(type(10+0j))\n", "print(type(\"10\"))\n", "print(type(True))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "These types are our basic building blocks. There's some other important basic types that build on these. We'll cover these later, but to give you a teaser:" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n", "\n" ] } ], "source": [ "print(type([1, 2]))\n", "print(type((1, 2))) \n", "print(type({1, 2}))" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Types can be converted from one to another. For example, we might want to change our 10 into different types. Here's some examples of converting the integer 10 into a float. First, we use the `float` function. Next we define a variable `a` that takes the integer value 10, then use a method associated with `a` to convert the type. If you're unfamiliar with the second notation, don't worry about that now, you'll get very used to it as we work more in python." ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "\n" ] } ], "source": [ "print(type(float(10)))\n", "a = 10\n", "print(type( a.__float__() ))\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python's repl does all of the basic numerical calculations that you'd like. It does dynamic typing so that you can do things like add ints and floats. Here we show the basic operators, and note `#` is a comment in python." ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "20.0\n", "100\n", "20\n", "5.0\n", "5.0\n", "0.09999999999999964\n" ] } ], "source": [ "print(10 + 10.0) ## addition, in this case an int and float\n", "print(10 ** 2) ## exponent\n", "print(10 * 2) ## multiplication\n", "print(10 / 2) ## division\n", "print(10.1 // 2) ## integer division\n", "print(10.1 % 2) ## modulo\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Strings are easy to work with in python. Type `print(\"Hello World\")` in the repl just to get that out of the way. Otherwise, `+` concatenates strings and brackets reference string elements. Here's some examples. Remember counting starts at 0 and negative numbers count from the back." ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "ds4bio is great\n", "d\n", "o\n" ] } ], "source": [ "word = \"ds4bio\"\n", "print(word + \" is great\") #concatenation \n", "print(word[0])\n", "print(word[-1])" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "The strings `True` and `False` are reserved for the respective Boolean values. The operators `==`, `>`, `<`, `>=`, `<=` and `!=` are the testing operators while `and`, `or` and `is` are Boolean operators. Here are some examples. " ] }, { "cell_type": "code", "execution_count": 6, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "True\n", "False\n", "True\n" ] } ], "source": [ "a = 5 < 4 # sets a to False\n", "b = 5 == 5 # sets b to True\n", "print(a or b)\n", "print(a and b)\n", "print(not a)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Don't define new variables called `TRUE` or `FALSE` or `tRuE` or `FaLsE`, or whatever, even though you can. Just get used to typing True and False the way python likes and don't use similar named things for other reasons. Als, python as bitwise logical operators `|`, `&` and `~`. On Boolean values, they work the same but differ in other circumstances. So, if you are unfamliar with bitwise operations, it's probably better to stick to the word logical operators above. " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Data structures\n", "Python has some more advanced data structures that build on its primitive types. \n", "\n", "* Lists: ordered collections of objects\n", "* Sets: like lists but only have unique elements\n", "* Tuples: like lists, but not mutable, i.e. need to create a new one to modify\n", "* Dictionaries: named elements that you can reference by their name rather than position\n", "\n", "First, let's look at some list operations.\n" ] }, { "cell_type": "code", "execution_count": 7, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1\n", "[8, 10]\n", "[8, 10]\n", "[1, 4]\n", "[[1, 4, 8, 10], [1, 4, 8, 10]]\n", "8\n", "[[[1, 4, 8, 10], [1, 4, 8, 10]], 'string1']\n", "[1, 4, 8, 10, 1, 4, 8, 10]\n" ] } ], "source": [ "dat = [1, 4, 8, 10] # define a list\n", "print(dat[0]) # reference an element\n", "print(dat[2 : 4]) # reference elements\n", "print(dat[2 : ]) \n", "print(dat[:2])\n", "dat2 = [dat, dat] # creating a list of lists\n", "print(dat2)\n", "print(dat2[1][2]) # referencing an item in a nested list\n", "dat3 = [dat2, \"string1\"] # mixed types\n", "print(dat3)\n", "dat4 = dat + dat # list concatenation\n", "print(dat4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Now, let's look at dictionaries. " ] }, { "cell_type": "code", "execution_count": 8, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'a': 1, 'b': 2}\n", "1\n" ] } ], "source": [ "dict = {\"a\" : 1, \"b\" : 2} # Create a dictionary of two elements named a and b taking values 1 and 2 respectively\n", "print(dict)\n", "print(dict['a']) # reference the element named a" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Sets and tuples are similar to lists, however with some important distinctions. Sets, contain only unique elements and tuples are immutable lists." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'a', 'c', 'b'}\n", "{'a', 1}\n", "{'a', 'c', 'b'}\n" ] } ], "source": [ "set1 = {\"a\", \"b\", \"c\"}\n", "set2 = {\"a\", 1, True}\n", "set3 = {\"a\", \"b\", \"c\", \"c\"}\n", "print(set1)\n", "print(set2)\n", "print(set3)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Here's an example to illustrate a tuple." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "data": { "text/plain": [ "['aa', 'b', 'c']" ] }, "execution_count": 10, "metadata": {}, "output_type": "execute_result" } ], "source": [ "list1 = [\"a\", \"b\", \"c\"]\n", "tuple1 = (\"a\", \"b\", \"c\")\n", "list1[0] = \"aa\" #Works just fine\n", "list1\n", "#tuple1[0] = \"aa\" #doesn't work" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Mutable in immutable entities\n", "\n", "When working with objects in python, mutable and immutable elements act differently. Lists are mutable. So, below, the element `y` gets appended along with `x`." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[10, 20]\n", "[21, 20]\n" ] } ], "source": [ "x = [10]\n", "y = x\n", "x.append(20)\n", "## Notice y has the appended element\n", "print(y)\n", "## let's try again, as of now x = [10, 20] \n", "x[0] = x[0] + 11\n", "## Now x = [21, 20], but did y change?\n", "print(y)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "Things like numbers and strings are immutable. Notice that changing `y` does not change `x`." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(20, 10)\n" ] } ], "source": [ "x = 10\n", "y = x\n", "x = x + 10\n", "print((x, y))" ] } ], "metadata": { "interpreter": { "hash": "c8fe39b8276bd4dd408fb5b678f9da77600a6c71547a4eba0709a9a0b29332d6" }, "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.13" } }, "nbformat": 4, "nbformat_minor": 4 }