{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "## Python Introduction with some detours\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python created by Guido von Rossum in early 1990s (later at Google,Dropbox)\n", "## Language reference: https://docs.python.org/3/index.html\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Why Python? " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Why Python but not Julia or R or some other language or even VBA in Excel?\n", "### Readability, Glue Language(APIs), From Startups to Google and Facebook, Pipeline\n", "\n", "Prime numbers in J language used at some finance institutions **1: I. 2= +/ 0= (] |/ ]) i.y**" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python is now programming language # 3 in TIOBE language index (as of September 2018)\n", "https://www.tiobe.com/tiobe-index/\n", "\n", "https://developers.slashdot.org/story/18/09/08/1722213/python-displaces-c-in-tiobe-index-top-3" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "https://www.anaconda.com/download/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Jupyter Basics\n", "\n", "* Esc-M turns cell into Markdown cell for formatting (https://guides.github.com/pdfs/markdown-cheatsheet-online.pdf)\n", "* Esc-Y turns cell into code cell(default)\n", "\n", "\n", "* Ctrl-Enter runs code of cell in place\n", "* Alt-Enter runs code for current cell and creates a new cell below\n", "* Esc-A creates a new cell above current cell\n", "* Esc-B creates a new cell below current cell\n", "* Esc-dd deletes current cell" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What is Programming? \n", "\n", "* Egg algorithm\n", "* Computers are stupid, they only do what they are told to do\n", "* If it is stupid but it works, then it is not stupid\n", "* Make it work, make it right, make it fast(last two steps often not required in real life)\n", "* GIGO principle\n", "\n", "* Error messages are nothing to be afraid of, usually the message will explain what needs fixing!" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(\"Hello World!\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Our first comment\n", "# Real Program Comments should generally describe why\n", "# Here comments will describe extra information not covered or needed for starting out\n", "# REPL(Read,Eval,Print, Loop) \n", "# Python - Interpreted Language(commands executed as they come)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Most important Python ideas\n", "* dir(myobject) to find what can be done (most decent text editors/IDEs will offer autocompletion and hints though)\n", "* help(myobject) general help\n", "* type(myobject) what type it is\n", "\n", "## : indicates a new indentation level " ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## id(object)\n", "\n", "Return the “identity” of an object. \n", "\n", "This is an integer which is guaranteed to be unique and constant for this object during its lifetime. \n", "Two objects with non-overlapping lifetimes may have the same id() value.\n", "\n", "#### CPython implementation detail: This is the address of the object in memory." ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myname=\"Valdis\"\n", "# Creating our first variable will persist through this workbook once it is run" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Strings\n", "* immutable" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "ename": "NameError", "evalue": "name 'myname' is not defined", "output_type": "error", "traceback": [ "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", "\u001b[1;32m<ipython-input-5-f8604fe2a0f6>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mmyname\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[1;31m#print is a function that takes at least one argument\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;31m# 2.7 and older Python was print without parenthesis\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", "\u001b[1;31mNameError\u001b[0m: name 'myname' is not defined" ] } ], "source": [ "print(myname)\n", "#print is a function that takes at least one argument\n", "# 2.7 and older Python was print without parenthesis" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "favfood=\"potatoes\"" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## \"f-strings\", “formatted string literals”\n", "\n", "In some other languages also known as string interpolation" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(f\"My name is {myname} and my favorite food is {favfood} \")\n", "# f strings in Python 3.6+ older formatting methods not covered in this course\n", "# https://realpython.com/python-f-strings/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## What is a function?\n", "* A function is a block of organized, reusable code that is used to perform a single, related action.\n", "* Single, organized, related always ? :)\n", "### DRY - Do not Repeat Yourself principle\n", "* Every piece of knowledge must have a single, unambiguous, authoritative representation within a system. http://wiki.c2.com/?DontRepeatYourself\n", "\n", "* Contrast WET - We Enjoy Typing, Write Everything Twice, Waste Everyone's Time" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def printName(name):\n", " print(f\"Maybe my name is: {name}\")\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "printName(\"Voldemars\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "#Functions can also return values\n", "def combinedName(name,last):\n", " return name+\" \"+last" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "fullname=combinedName(\"Valdis\",\"Saulespurens\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "sometext=\"It's a string which allows single quotes\"\n", "anothertext='This string allows \"double quotes\" without escaping'\n", "longstring='''This is a multiline string\n", "Seriously long string with many lines\n", "lots of text covered'''" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(longstring)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Some strings might need escaping such as \\\\, \\\", \\', \\t" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Everything in Python is an Object\n", "## can use id(myobject) to find its identity - place in memory\n", "## each object has a value with a type and can be mutable/immutable" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Data types in Python 3.x\n", "\n", "* Integers type(42) int\n", "* Floating Point type(3.14) float\n", "* Boolean type(True),type(False) bool\n", "* String(ordered, immutable char sequence) type(\"OyCaramba\") str\n", "* List type([1,2,63,\"aha\",\"youcanmixtypeinsidelist\", [\"even\",\"nest\"]]) list\n", "* Dictionary(key:value pairs) type({\"foo\":\"bar\", \"favoriteday\":\"Friday\"}) dict\n", "* Tuple - ordered immutable sequence type(\"sup\",7,\"dwarves\") tup\n", "* Set (unordered collection of uniques) (\"k\",\"a\",\"r\",\"t\",\"u\",\"p\",\"e\",\"l\",\"i\",\"s\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Variables\n", "a = 5 # Integer\n", "b = 5.6 # Float\n", "c = \"sometext\" # String\n", "print(type(a),type(b),type(c))\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "a = \"42\" # now a is a String\n", "type(a) # notice how without print the output is a bit different" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# Naming conventions\n", "# start with lowercase\n", "# _ between words or camelCase\n", "# style guide: https://www.python.org/dev/peps/pep-0008/" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Arithmetic Operators\n", "## + - * / \n", "## **(power) \n", "## % modulus \n", "## //(integer division)\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "5+4*3-(6/2)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "5//2\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "4%3" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(1)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "type(14.0)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "5**33" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "11**120 # no maximum anymore" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Python Lists\n", "\n", "* Ordered\n", "* Mutable(can change individual members!)\n", "* Comma separated between brackets [1,3,2,5,6,2]\n", "* Can have duplicates\n", "* Can be nested\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mylist = list(range(11,21,1)) \n", "# mylist = [11, 12, 13, 14, 15, 16, 17, 18, 19, 20] would work too but not practical for longer ranges...\n", "print(mylist)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### Slice notation\n", "\n", "somestring[start:end:step]\n", "\n", "somelist[start:end:step]\n", "\n", "start is at index 0(first element), end is -1 the actual index\n", "#### Examples below" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mylist[0]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mylist[3:]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mylist[:-2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mylist[::2]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"Valdis\"[2:5]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myname[-1]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myname[::-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "\n", "### Common list methods.\n", "* list.append(elem) -- adds a single element to the end of the list. Common error: does not return the new list, just modifies the original.\n", "* list.insert(index, elem) -- inserts the element at the given index, shifting elements to the right.\n", "* list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is similar to using extend().\n", "* list.index(elem) -- searches for the given element from the start of the list and returns its index. Throws a ValueError if the element does not appear (use \"in\" to check without a ValueError).\n", "* list.remove(elem) -- searches for the first instance of the given element and removes it (throws ValueError if not present)\n", "* list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is preferred.)\n", "* list.reverse() -- reverses the list in place (does not return it)\n", "* list.pop(index)-- removes and returns the element at the given index. Returns the rightmost element if index is omitted (roughly the opposite of append())." ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Dictionaries\n", "\n", "* Collection of Key - Value pairs\n", "* also known as associative array\n", "* unordered\n", "* keys unique in one dictionary\n", "* storing, extracting" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mydict = {\"country\":\"Latvia\"} #Key-Value store, also knows as Hashmaps, Keys must be unique" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mydict[\"food\"]=\"potatoes\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mydict[\"food\"]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mydict[\"country\"]" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mydict.keys()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mydict.values()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "\"potatoes\" in mydict.values()" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Sets\n", "\n", "* unordered\n", "* uniques only\n", "* curly braces {3, 6, 7}" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "s={3,3,6,1,3,6,7}\n", "print(s)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tuples\n", "\n", "* ordered\n", "* immutable (cannot be changed!)\n", "* Can be used as a collection of fields" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "mytuple = 6, 4, 9\n", "print(mytuple)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Conditional operators \n", "### < > <= >= == != and or not" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "if 5 >= 5:\n", " print(\"hello\")\n", "if 5 <= 5:\n", " print(\"hello\")\n", "if 5 == 6:\n", " print(\"hello thats magic\")\n", "if 5 != 6:\n", " print(\"hello thats not magic\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def printnum(num):\n", " if num > 10:\n", " print(f\"This number {num} is too unwieldy for me to print\")\n", " else:\n", " print(f\"This {num} is a nice number\")" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def isEven(num):\n", " if num%2 == 0:\n", " print(f\"{num} is even\")\n", " else:\n", " print(f\"{num} is odd\")\n", "\n", "isEven(3)\n", "isEven(4)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Loops" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for x in range(10):\n", " print(x)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "### in Python 3.X range returns an iterable(Lazy, values on demand, saves memory on longer iteration)\n", "#### in Python 2.7 range returned a list ! (xrange was the iterator version, not as fully featured as the current range)\n", "Full list of differences: http://treyhunner.com/2018/02/python-3-s-range-better-than-python-2-s-xrange/" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for c in \"Valdis\":\n", " print(c)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "for k,v in mydict.items():\n", " print(k,v)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "printnum(3)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Splitting a line of text into words\n", "mytext = \"A quick brown fox jumped over a sleeping dog\"\n", "words = mytext.split()\n" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "print(words)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "## Print first letter of each word\n", "for w in words:\n", " print(w[0], w[0].isupper(), w.istitle()) ## istitle() checks every word in a string so not good for unsplit strings" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myline=\"Mr. Sherlock Holmes, who was usually very late in the mornings\"" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "words=myline.split()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "words" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "words[1][0].isupper()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "def processLine(line):\n", " words = line.split()\n", " linegood=False\n", " for word in words: \n", " if word[0].isupper():\n", " print(word, end='\\t')\n", " linegood=True\n", " if linegood == True:\n", " print('')" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class MyClass:\n", " \"\"\"A simple example class\"\"\"\n", " i = 12345\n", "\n", " def f(self): #this is important! similar to this in other languages object itself\n", " return f'Hello'\n", "dir(MyClass)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "myc=MyClass()\n", "#?myc\n", "print(myc.i)\n", "print(myc.f())" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "class Complex:\n", " def __init__(self, realpart, imagpart, name):\n", " self.r = realpart\n", " self.i = imagpart\n", " self.name = name\n", " def calcDistance(self, mult):\n", " return (self.r**2+self.i**2)**0.5*mult\n", "x = Complex(3.0, -4.5, \"Complekss\")\n", "print(x.r, x.i)\n", "print(x.calcDistance(5))\n", "print(x.name)\n", "# dir(x)\n", "dir(Complex)" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [ "# TODO List Comprehensions, Dictionary Comperehensions\n", "# Generators\n", "# File IO\n", "# Filter,Map,Apply\n", "\n", "# Imports, modules\n", "# Decorators !\n", "\n" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "# Python Resources" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Tutorials Begginner to Intermediate\n", "\n", "* https://automatetheboringstuff.com/ - Anything by Al Sweigart is great\n", "* http://newcoder.io/tutorials/ - 5 sets of practical tutorials\n", "* [Think Like a Computer Scientist](http://interactivepython.org/runestone/static/thinkcspy/index.html) full tutorial\n", "* [Non-Programmers Tutorial for Python 3](https://en.wikibooks.org/wiki/Non-Programmer%27s_Tutorial_for_Python_3) quite good for wikibooks\n", "* [Real Python](https://realpython.com/) Python Tutorials for all levels\n", "\n", "\n", "* [Learn Python 3 the Hard Way](https://learnpythonthehardway.org/python3/intro.html) controversial author but very exhaustive, some like this approach" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## More Advanced Python Specific Books\n", "\n", "* [Python Cookbook](https://www.amazon.com/Python-Cookbook-Third-David-Beazley/dp/1449340377) Recipes for specific situations\n", "\n", "* [Effective Python](https://effectivepython.com/) best practices\n", "* [Fluent Python](http://shop.oreilly.com/product/0636920032519.do) **highly recommended**, shows Python's advantages" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## General Best Practices Books\n", "#### (not Python specific)\n", "\n", "* [Code Complete 2](https://www.goodreads.com/book/show/4845.Code_Complete) - Fantastic best practices\n", "* [The Mythical Man-Month](https://en.wikipedia.org/wiki/The_Mythical_Man-Month) - No silver bullet even after 40 years.\n", "* [The Pragmatic Programmer](https://www.amazon.com/Pragmatic-Programmer-Journeyman-Master/dp/020161622X) - More practical advice\n", "* [Clean Code](https://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882) - more towards agile" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Blogs / Personalities / forums\n", "\n", "* [Dan Bader](https://dbader.org/)\n", "* [Reddit Python](https://www.reddit.com/r/python)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Exercises/Challenges\n", "* http://www.pythonchallenge.com/ - first one is easy but after that...\n", "* [Advent of Code](https://adventofcode.com/) - yearly programming challenges\n", "* https://projecteuler.net/ - gets very mathematical but first problems are great for testing (Prof. Arnicans used to give extra credit for these...)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Questions / Suggestions ? \n", "feel free to pull request" ] } ], "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.6.4" } }, "nbformat": 4, "nbformat_minor": 2 }