diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/01-Variable Assignment-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/01-Variable Assignment-checkpoint.ipynb new file mode 100644 index 0000000..c5af87b --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/01-Variable Assignment-checkpoint.ipynb @@ -0,0 +1,437 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Variable Assignment\n", + "\n", + "## Rules for variable names\n", + "* names can not start with a number\n", + "* names can not contain spaces, use _ intead\n", + "* names can not contain any of these symbols:\n", + "\n", + " :'\",<>/?|\\!@#%^&*~-+\n", + " \n", + "* it's considered best practice ([PEP8](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names)) that names are lowercase with underscores\n", + "* avoid using Python built-in keywords like `list` and `str`\n", + "* avoid using the single characters `l` (lowercase letter el), `O` (uppercase letter oh) and `I` (uppercase letter eye) as they can be confused with `1` and `0`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dynamic Typing\n", + "\n", + "Python uses *dynamic typing*, meaning you can reassign variables to different data types. This makes Python very flexible in assigning data types; it differs from other languages that are *statically typed*." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "my_dogs = 2" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dogs" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "my_dogs = ['Sammy', 'Frankie']" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Sammy', 'Frankie']" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dogs" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Pros and Cons of Dynamic Typing\n", + "#### Pros of Dynamic Typing\n", + "* very easy to work with\n", + "* faster development time\n", + "\n", + "#### Cons of Dynamic Typing\n", + "* may result in unexpected bugs!\n", + "* you need to be aware of `type()`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Assigning Variables\n", + "Variable assignment follows `name = object`, where a single equals sign `=` is an *assignment operator*" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "a = 5" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we assigned the integer object `5` to the variable name `a`.
Let's assign `a` to something else:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "a = 10" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can now use `a` in place of the number `10`:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "20" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a + a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Reassigning Variables\n", + "Python lets you reassign variables with a reference to the same object." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "a = a + 10" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "20" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There's actually a shortcut for this. Python lets you add, subtract, multiply and divide numbers with reassignment using `+=`, `-=`, `*=`, and `/=`." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "a += 10" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "30" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "a *= 2" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "60" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Determining variable type with `type()`\n", + "You can check what type of object is assigned to a variable using Python's built-in `type()` function. Common data types include:\n", + "* **int** (for integer)\n", + "* **float**\n", + "* **str** (for string)\n", + "* **list**\n", + "* **tuple**\n", + "* **dict** (for dictionary)\n", + "* **set**\n", + "* **bool** (for Boolean True/False)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "int" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [], + "source": [ + "a = (1,2)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "tuple" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Simple Exercise\n", + "This shows how variables make calculations more readable and easier to follow." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [], + "source": [ + "my_income = 100\n", + "tax_rate = 0.1\n", + "my_taxes = my_income * tax_rate" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10.0" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_taxes" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! You should now understand the basics of variable assignment and reassignment in Python.
Up next, we'll learn about strings!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/02-Strings-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/02-Strings-checkpoint.ipynb new file mode 100644 index 0000000..1ef2117 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/02-Strings-checkpoint.ipynb @@ -0,0 +1,1003 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Strings are used in Python to record text information, such as names. Strings in Python are actually a *sequence*, which basically means Python keeps track of every element in the string as a sequence. For example, Python understands the string \"hello' to be a sequence of letters in a specific order. This means we will be able to use indexing to grab particular letters (like the first letter, or the last letter).\n", + "\n", + "This idea of a sequence is an important one in Python and we will touch upon it later on in the future.\n", + "\n", + "In this lecture we'll learn about the following:\n", + "\n", + " 1.) Creating Strings\n", + " 2.) Printing Strings\n", + " 3.) String Indexing and Slicing\n", + " 4.) String Properties\n", + " 5.) String Methods\n", + " 6.) Print Formatting" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating a String\n", + "To create a string in Python you need to use either single quotes or double quotes. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Single word\n", + "'hello'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is also a string'" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Entire phrase \n", + "'This is also a string'" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'String built with double quotes'" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# We can also use double quote\n", + "\"String built with double quotes\"" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "invalid syntax (, line 2)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m ' I'm using single quotes, but this will create an error'\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" + ] + } + ], + "source": [ + "# Be careful with quotes!\n", + "' I'm using single quotes, but this will create an error'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The reason for the error above is because the single quote in I'm stopped the string. You can use combinations of double and single quotes to get the complete statement." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "\"Now I'm ready to use the single quotes inside a string!\"" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"Now I'm ready to use the single quotes inside a string!\"" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now let's learn about printing strings!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Printing a String\n", + "\n", + "Using Jupyter notebook with just a string in a cell will automatically output strings, but the correct way to display strings in your output is by using a print function." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# We can simply declare a string\n", + "'Hello World'" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World 2'" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Note that we can't output multiple strings this way\n", + "'Hello World 1'\n", + "'Hello World 2'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use a print statement to print a string." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello World 1\n", + "Hello World 2\n", + "Use \n", + " to print a new line\n", + "\n", + "\n", + "See what I mean?\n" + ] + } + ], + "source": [ + "print('Hello World 1')\n", + "print('Hello World 2')\n", + "print('Use \\n to print a new line')\n", + "print('\\n')\n", + "print('See what I mean?')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## String Basics" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use a function called len() to check the length of a string!" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "11" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len('Hello World')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Python's built-in len() function counts all of the characters in the string, including spaces and punctuation." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## String Indexing\n", + "We know strings are a sequence, which means Python can use indexes to call parts of the sequence. Let's learn how this works.\n", + "\n", + "In Python, we use brackets [] after an object to call its index. We should also note that indexing starts at 0 for Python. Let's create a new object called s and then walk through a few examples of indexing." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "# Assign s as a string\n", + "s = 'Hello World'" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Check\n", + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello World\n" + ] + } + ], + "source": [ + "# Print the object\n", + "print(s) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's start indexing!" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'H'" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Show first element (in this case a letter)\n", + "s[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'e'" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[1]" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'l'" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[2]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use a : to perform *slicing* which grabs everything up to a designated point. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'ello World'" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything past the first term all the way to the length of s which is len(s)\n", + "s[1:]" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Note that there is no change to the original s\n", + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hel'" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything UP TO the 3rd index\n", + "s[:3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note the above slicing. Here we're telling Python to grab everything from 0 up to 3. It doesn't include the 3rd index. You'll notice this a lot in Python, where statements and are usually in the context of \"up to, but not including\"." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Everything\n", + "s[:]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use negative indexing to go backwards." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'d'" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Last letter (one index behind 0 so it loops back around)\n", + "s[-1]" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello Worl'" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything but the last letter\n", + "s[:-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use index and slice notation to grab elements of a sequence by a specified step size (the default is 1). For instance we can use two colons in a row and then a number specifying the frequency to grab elements. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything, but go in steps size of 1\n", + "s[::1]" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'HloWrd'" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything, but go in step sizes of 2\n", + "s[::2]" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'dlroW olleH'" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# We can use this to print a string backwards\n", + "s[::-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## String Properties\n", + "It's important to note that strings have an important property known as *immutability*. This means that once a string is created, the elements within it can not be changed or replaced. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "ename": "TypeError", + "evalue": "'str' object does not support item assignment", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# Let's try to change the first letter to 'x'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ms\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'x'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: 'str' object does not support item assignment" + ] + } + ], + "source": [ + "# Let's try to change the first letter to 'x'\n", + "s[0] = 'x'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how the error tells us directly what we can't do, change the item assignment!\n", + "\n", + "Something we *can* do is concatenate strings!" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World concatenate me!'" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Concatenate strings!\n", + "s + ' concatenate me!'" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [], + "source": [ + "# We can reassign s completely though!\n", + "s = s + ' concatenate me!'" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello World concatenate me!\n" + ] + } + ], + "source": [ + "print(s)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World concatenate me!'" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use the multiplication symbol to create repetition!" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "letter = 'z'" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'zzzzzzzzzz'" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "letter*10" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Basic Built-in String methods\n", + "\n", + "Objects in Python usually have built-in methods. These methods are functions inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself.\n", + "\n", + "We call methods with a period and then the method name. Methods are in the form:\n", + "\n", + "object.method(parameters)\n", + "\n", + "Where parameters are extra arguments we can pass into the method. Don't worry if the details don't make 100% sense right now. Later on we will be creating our own objects and functions!\n", + "\n", + "Here are some examples of built-in methods in strings:" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World concatenate me!'" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'HELLO WORLD CONCATENATE ME!'" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Upper Case a string\n", + "s.upper()" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello world concatenate me!'" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Lower case\n", + "s.lower()" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Hello', 'World', 'concatenate', 'me!']" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Split a string by blank space (this is the default)\n", + "s.split()" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Hello ', 'orld concatenate me!']" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Split by a specific element (doesn't include the element that was split on)\n", + "s.split('W')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are many more methods than the ones covered here. Visit the Advanced String section to find out more!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Print Formatting\n", + "\n", + "We can use the .format() method to add formatted objects to printed string statements. \n", + "\n", + "The easiest way to show this is through an example:" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Insert another string with curly brackets: The inserted string'" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'Insert another string with curly brackets: {}'.format('The inserted string')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We will revisit this string formatting topic in later sections when we are building our projects!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Next up: Lists!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/03-Print Formatting with Strings-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/03-Print Formatting with Strings-checkpoint.ipynb new file mode 100644 index 0000000..7661e9f --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/03-Print Formatting with Strings-checkpoint.ipynb @@ -0,0 +1,713 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# String Formatting\n", + "\n", + "String formatting lets you inject items into a string rather than trying to chain items together using commas or string concatenation. As a quick comparison, consider:\n", + "\n", + " player = 'Thomas'\n", + " points = 33\n", + " \n", + " 'Last night, '+player+' scored '+str(points)+' points.' # concatenation\n", + " \n", + " f'Last night, {player} scored {points} points.' # string formatting\n", + "\n", + "\n", + "There are three ways to perform string formatting.\n", + "* The oldest method involves placeholders using the modulo `%` character.\n", + "* An improved technique uses the `.format()` string method.\n", + "* The newest method, introduced with Python 3.6, uses formatted string literals, called *f-strings*.\n", + "\n", + "Since you will likely encounter all three versions in someone else's code, we describe each of them here." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Formatting with placeholders\n", + "You can use %s to inject strings into your print statements. The modulo `%` is referred to as a \"string formatting operator\"." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm going to inject something here.\n" + ] + } + ], + "source": [ + "print(\"I'm going to inject %s here.\" %'something')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can pass multiple items by placing them inside a tuple after the `%` operator." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm going to inject some text here, and more text here.\n" + ] + } + ], + "source": [ + "print(\"I'm going to inject %s text here, and %s text here.\" %('some','more'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also pass variable names:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm going to inject some text here, and more text here.\n" + ] + } + ], + "source": [ + "x, y = 'some', 'more'\n", + "print(\"I'm going to inject %s text here, and %s text here.\"%(x,y))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Format conversion methods.\n", + "It should be noted that two methods %s and %r convert any python object to a string using two separate methods: `str()` and `repr()`. We will learn more about these functions later on in the course, but you should note that `%r` and `repr()` deliver the *string representation* of the object, including quotation marks and any escape characters." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He said his name was Fred.\n", + "He said his name was 'Fred'.\n" + ] + } + ], + "source": [ + "print('He said his name was %s.' %'Fred')\n", + "print('He said his name was %r.' %'Fred')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As another example, `\\t` inserts a tab into a string." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I once caught a fish this \tbig.\n", + "I once caught a fish 'this \\tbig'.\n" + ] + } + ], + "source": [ + "print('I once caught a fish %s.' %'this \\tbig')\n", + "print('I once caught a fish %r.' %'this \\tbig')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `%s` operator converts whatever it sees into a string, including integers and floats. The `%d` operator converts numbers to integers first, without rounding. Note the difference below:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I wrote 3.75 programs today.\n", + "I wrote 3 programs today.\n" + ] + } + ], + "source": [ + "print('I wrote %s programs today.' %3.75)\n", + "print('I wrote %d programs today.' %3.75) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Padding and Precision of Floating Point Numbers\n", + "Floating point numbers use the format %5.2f. Here, 5 would be the minimum number of characters the string should contain; these may be padded with whitespace if the entire number does not have this many digits. Next to this, .2f stands for how many numbers to show past the decimal point. Let's see some examples:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13.14\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %5.2f' %(13.144))" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %1.0f' %(13.144))" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13.14400\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %1.5f' %(13.144))" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13.14\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %10.2f' %(13.144))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13.14\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %25.2f' %(13.144))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For more information on string formatting with placeholders visit https://docs.python.org/3/library/stdtypes.html#old-string-formatting" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Multiple Formatting\n", + "Nothing prohibits using more than one conversion tool in the same print statement:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First: hi!, Second: 3.14, Third: 'bye!'\n" + ] + } + ], + "source": [ + "print('First: %s, Second: %5.2f, Third: %r' %('hi!',3.1415,'bye!'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Formatting with the `.format()` method\n", + "A better way to format objects into your strings for print statements is with the string `.format()` method. The syntax is:\n", + "\n", + " 'String here {} then also {}'.format('something1','something2')\n", + " \n", + "For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a string with an insert\n" + ] + } + ], + "source": [ + "print('This is a string with an {}'.format('insert'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### The .format() method has several advantages over the %s placeholder method:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 1. Inserted objects can be called by index position:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The quick brown fox\n" + ] + } + ], + "source": [ + "print('The {2} {1} {0}'.format('fox','brown','quick'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 2. Inserted objects can be assigned keywords:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First Object: 1, Second Object: Two, Third Object: 12.3\n" + ] + } + ], + "source": [ + "print('First Object: {a}, Second Object: {b}, Third Object: {c}'.format(a=1,b='Two',c=12.3))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 3. Inserted objects can be reused, avoiding duplication:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A penny saved is a penny earned.\n", + "A penny saved is a penny earned.\n" + ] + } + ], + "source": [ + "print('A %s saved is a %s earned.' %('penny','penny'))\n", + "# vs.\n", + "print('A {p} saved is a {p} earned.'.format(p='penny'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Alignment, padding and precision with `.format()`\n", + "Within the curly braces you can assign field lengths, left/right alignments, rounding parameters and more" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Fruit | Quantity \n", + "Apples | 3.0\n", + "Oranges | 10\n" + ] + } + ], + "source": [ + "print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))\n", + "print('{0:8} | {1:9}'.format('Apples', 3.))\n", + "print('{0:8} | {1:9}'.format('Oranges', 10))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By default, `.format()` aligns text to the left, numbers to the right. You can pass an optional `<`,`^`, or `>` to set a left, center or right alignment:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Left | Center | Right\n", + "11 | 22 | 33\n" + ] + } + ], + "source": [ + "print('{0:<8} | {1:^8} | {2:>8}'.format('Left','Center','Right'))\n", + "print('{0:<8} | {1:^8} | {2:>8}'.format(11,22,33))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can precede the aligment operator with a padding character" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Left==== | -Center- | ...Right\n", + "11====== | ---22--- | ......33\n" + ] + } + ], + "source": [ + "print('{0:=<8} | {1:-^8} | {2:.>8}'.format('Left','Center','Right'))\n", + "print('{0:=<8} | {1:-^8} | {2:.>8}'.format(11,22,33))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Field widths and float precision are handled in a way similar to placeholders. The following two print statements are equivalent:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is my ten-character, two-decimal number: 13.58\n", + "This is my ten-character, two-decimal number: 13.58\n" + ] + } + ], + "source": [ + "print('This is my ten-character, two-decimal number:%10.2f' %13.579)\n", + "print('This is my ten-character, two-decimal number:{0:10.2f}'.format(13.579))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that there are 5 spaces following the colon, and 5 characters taken up by 13.58, for a total of ten characters.\n", + "\n", + "For more information on the string `.format()` method visit https://docs.python.org/3/library/string.html#formatstrings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Formatted String Literals (f-strings)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Introduced in Python 3.6, f-strings offer several benefits over the older `.format()` string method described above. For one, you can bring outside variables immediately into to the string rather than pass them as arguments through `.format(var)`." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He said his name is Fred.\n" + ] + } + ], + "source": [ + "name = 'Fred'\n", + "\n", + "print(f\"He said his name is {name}.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Pass `!r` to get the string representation:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He said his name is 'Fred'\n" + ] + } + ], + "source": [ + "print(f\"He said his name is {name!r}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Float formatting follows `\"result: {value:{width}.{precision}}\"`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Where with the `.format()` method you might see `{value:10.4f}`, with f-strings this can become `{value:{10}.{6}}`\n" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "My 10 character, four decimal number is: 23.4568\n", + "My 10 character, four decimal number is: 23.4568\n" + ] + } + ], + "source": [ + "num = 23.45678\n", + "print(\"My 10 character, four decimal number is:{0:10.4f}\".format(num))\n", + "print(f\"My 10 character, four decimal number is:{num:{10}.{6}}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that with f-strings, *precision* refers to the total number of digits, not just those following the decimal. This fits more closely with scientific notation and statistical analysis. Unfortunately, f-strings do not pad to the right of the decimal, even if precision allows it:" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "My 10 character, four decimal number is: 23.4500\n", + "My 10 character, four decimal number is: 23.45\n" + ] + } + ], + "source": [ + "num = 23.45\n", + "print(\"My 10 character, four decimal number is:{0:10.4f}\".format(num))\n", + "print(f\"My 10 character, four decimal number is:{num:{10}.{6}}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If this becomes important, you can always use `.format()` method syntax inside an f-string:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "My 10 character, four decimal number is: 23.4500\n", + "My 10 character, four decimal number is: 23.4500\n" + ] + } + ], + "source": [ + "num = 23.45\n", + "print(\"My 10 character, four decimal number is:{0:10.4f}\".format(num))\n", + "print(f\"My 10 character, four decimal number is:{num:10.4f}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For more info on formatted string literals visit https://docs.python.org/3/reference/lexical_analysis.html#f-strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That is the basics of string formatting!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/07-Sets and Booleans-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/07-Sets and Booleans-checkpoint.ipynb new file mode 100644 index 0000000..f0749fd --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/07-Sets and Booleans-checkpoint.ipynb @@ -0,0 +1,311 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Set and Booleans\n", + "\n", + "There are two other object types in Python that we should quickly cover: Sets and Booleans. \n", + "\n", + "## Sets\n", + "\n", + "Sets are an unordered collection of *unique* elements. We can construct them by using the set() function. Let's go ahead and make a set to see how it works" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "x = set()" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# We add to sets with the add() method\n", + "x.add(1)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1}" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note the curly brackets. This does not indicate a dictionary! Although you can draw analogies as a set being a dictionary with only keys.\n", + "\n", + "We know that a set has only unique entries. So what happens when we try to add something that is already in a set?" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Add a different element\n", + "x.add(2)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2}" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "x" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Try to add the same element\n", + "x.add(1)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2}" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how it won't place another 1 there. That's because a set is only concerned with unique elements! We can cast a list with multiple repeat elements to a set to get the unique elements. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Create a list with repeats\n", + "list1 = [1,1,2,2,3,4,5,6,1,1]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2, 3, 4, 5, 6}" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Cast as set to get unique values\n", + "set(list1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Booleans\n", + "\n", + "Python comes with Booleans (with predefined True and False displays that are basically just the integers 1 and 0). It also has a placeholder object called None. Let's walk through a few quick examples of Booleans (we will dive deeper into them later in this course)." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Set object to be a boolean\n", + "a = True" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use comparison operators to create booleans. We will go over all the comparison operators later on in the course." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Output is boolean\n", + "1 > 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use None as a placeholder for an object that we don't want to reassign yet:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# None placeholder\n", + "b = None" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "# Show\n", + "print(b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Thats it! You should now have a basic understanding of Python objects and data structure types. Next, go ahead and do the assessment test!" + ] + } + ], + "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.1" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/08-Files-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/08-Files-checkpoint.ipynb new file mode 100644 index 0000000..1932220 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/08-Files-checkpoint.ipynb @@ -0,0 +1,556 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Files\n", + "\n", + "Python uses file objects to interact with external files on your computer. These file objects can be any sort of file you have on your computer, whether it be an audio file, a text file, emails, Excel documents, etc. Note: You will probably need to install certain libraries or modules to interact with those various file types, but they are easily available. (We will cover downloading modules later on in the course).\n", + "\n", + "Python has a built-in open function that allows us to open and play with basic file types. First we will need a file though. We're going to use some IPython magic to create a text file!\n", + "\n", + "## IPython Writing a File \n", + "#### This function is specific to jupyter notebooks! Alternatively, quickly create a simple .txt file with sublime text editor." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting test.txt\n" + ] + } + ], + "source": [ + "%%writefile test.txt\n", + "Hello, this is a quick test file." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Python Opening a file\n", + "\n", + "Let's being by opening the file test.txt that is located in the same directory as this notebook. For now we will work with files located in the same directory as the notebook or .py script you are using.\n", + "\n", + "It is very easy to get an error on this step:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "FileNotFoundError", + "evalue": "[Errno 2] No such file or directory: 'whoops.txt'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmyfile\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'whoops.txt'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'whoops.txt'" + ] + } + ], + "source": [ + "myfile = open('whoops.txt')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To avoid this error,make sure your .txt file is saved in the same location as your notebook, to check your notebook location, use **pwd**:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'C:\\\\Users\\\\Marcial\\\\Pierian-Data-Courses\\\\Complete-Python-3-Bootcamp\\\\00-Python Object and Data Structure Basics'" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pwd" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Alternatively, to grab files from any location on your computer, simply pass in the entire file path. **\n", + "\n", + "For Windows you need to use double \\ so python doesn't treat the second \\ as an escape character, a file path is in the form:\n", + "\n", + " myfile = open(\"C:\\\\Users\\\\YourUserName\\\\Home\\\\Folder\\\\myfile.txt\")\n", + "\n", + "For MacOS and Linux you use slashes in the opposite direction:\n", + "\n", + " myfile = open(\"/Users/YouUserName/Folder/myfile.txt\")" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Open the text.txt we made earlier\n", + "my_file = open('test.txt')" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello, this is a quick test file.'" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# We can now read the file\n", + "my_file.read()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "''" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# But what happens if we try to read it again?\n", + "my_file.read()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This happens because you can imagine the reading \"cursor\" is at the end of the file after having read it. So there is nothing left to read. We can reset the \"cursor\" like this:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Seek to the start of file (index 0)\n", + "my_file.seek(0)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello, this is a quick test file.'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Now read again\n", + "my_file.read()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can read a file line by line using the readlines method. Use caution with large files, since everything will be held in memory. We will learn how to iterate over large files later in the course." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Hello, this is a quick test file.']" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Readlines returns a list of the lines in the file\n", + "my_file.seek(0)\n", + "my_file.readlines()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When you have finished using a file, it is always good practice to close it." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_file.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Writing to a File\n", + "\n", + "By default, the `open()` function will only allow us to read the file. We need to pass the argument `'w'` to write over the file. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Add a second argument to the function, 'w' which stands for write.\n", + "# Passing 'w+' lets us read and write to the file\n", + "\n", + "my_file = open('test.txt','w+')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Use caution! \n", + "Opening a file with `'w'` or `'w+'` truncates the original, meaning that anything that was in the original file **is deleted**!" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "18" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Write to the file\n", + "my_file.write('This is a new line')" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a new line'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Read the file\n", + "my_file.seek(0)\n", + "my_file.read()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_file.close() # always do this when you're done with a file" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Appending to a File\n", + "Passing the argument `'a'` opens the file and puts the pointer at the end, so anything written is appended. Like `'w+'`, `'a+'` lets us read and write to a file. If the file does not exist, one will be created." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "23" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_file = open('test.txt','a+')\n", + "my_file.write('\\nThis is text being appended to test.txt')\n", + "my_file.write('\\nAnd another line here.')" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a new line\n", + "This is text being appended to test.txt\n", + "And another line here.\n" + ] + } + ], + "source": [ + "my_file.seek(0)\n", + "print(my_file.read())" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_file.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Appending with `%%writefile`\n", + "We can do the same thing using IPython cell magic:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Appending to test.txt\n" + ] + } + ], + "source": [ + "%%writefile -a test.txt\n", + "\n", + "This is text being appended to test.txt\n", + "And another line here." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Add a blank space if you want the first line to begin on its own line, as Jupyter won't recognize escape sequences like `\\n`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterating through a File\n", + "\n", + "Lets get a quick preview of a for loop by iterating over a text file. First let's make a new text file with some IPython Magic:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting test.txt\n" + ] + } + ], + "source": [ + "%%writefile test.txt\n", + "First Line\n", + "Second Line" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we can use a little bit of flow to tell the program to for through every line of the file and do something:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First Line\n", + "\n", + "Second Line\n" + ] + } + ], + "source": [ + "for line in open('test.txt'):\n", + " print(line)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Don't worry about fully understanding this yet, for loops are coming up soon. But we'll break down what we did above. We said that for every line in this text file, go ahead and print that line. It's important to note a few things here:\n", + "\n", + "1. We could have called the \"line\" object anything (see example below).\n", + "2. By not calling `.read()` on the file, the whole text file was not stored in memory.\n", + "3. Notice the indent on the second line for print. This whitespace is required in Python." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First Line\n", + "\n", + "Second Line\n" + ] + } + ], + "source": [ + "# Pertaining to the first point above\n", + "for asdf in open('test.txt'):\n", + " print(asdf)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We'll learn a lot more about this later, but up next: Sets and Booleans!" + ] + } + ], + "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.1" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/09-Objects and Data Structures Assessment Test-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/09-Objects and Data Structures Assessment Test-checkpoint.ipynb new file mode 100644 index 0000000..149e61a --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/09-Objects and Data Structures Assessment Test-checkpoint.ipynb @@ -0,0 +1,528 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Objects and Data Structures Assessment Test" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Test your knowledge. \n", + "\n", + "** Answer the following questions **" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Write a brief description of all the following Object Types and Data Structures we've learned about: " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Numbers:\n", + "\n", + "Strings:\n", + "\n", + "Lists:\n", + "\n", + "Tuples:\n", + "\n", + "Dictionaries:\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Numbers\n", + "\n", + "Write an equation that uses multiplication, division, an exponent, addition, and subtraction that is equal to 100.25.\n", + "\n", + "Hint: This is just to test your memory of the basic arithmetic commands, work backwards from 100.25" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Answer these 3 questions without typing code. Then type code to check your answer.\n", + "\n", + " What is the value of the expression 4 * (6 + 5)\n", + " \n", + " What is the value of the expression 4 * 6 + 5 \n", + " \n", + " What is the value of the expression 4 + 6 * 5 " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is the *type* of the result of the expression 3 + 1.5 + 4?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What would you use to find a number’s square root, as well as its square? " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Square root:\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Square:\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Given the string 'hello' give an index command that returns 'e'. Enter your code in the cell below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "s = 'hello'\n", + "# Print out 'e' using indexing\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Reverse the string 'hello' using slicing:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "s ='hello'\n", + "# Reverse the string using slicing\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Given the string hello, give two methods of producing the letter 'o' using indexing." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "s ='hello'\n", + "# Print out the 'o'\n", + "\n", + "# Method 1:\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Method 2:\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Lists" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Build this list [0,0,0] two separate ways." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Method 1:\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Method 2:\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Reassign 'hello' in this nested list to say 'goodbye' instead:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list3 = [1,2,[3,4,'hello']]\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Sort the list below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list4 = [5,3,4,6,1]\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionaries" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using keys and indexing, grab the 'hello' from the following dictionaries:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "d = {'simple_key':'hello'}\n", + "# Grab 'hello'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "d = {'k1':{'k2':'hello'}}\n", + "# Grab 'hello'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Getting a little tricker\n", + "d = {'k1':[{'nest_key':['this is deep',['hello']]}]}\n", + "\n", + "#Grab hello\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# This will be hard and annoying!\n", + "d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Can you sort a dictionary? Why or why not?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Tuples" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is the major difference between tuples and lists?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "How do you create a tuple?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Sets " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is unique about a set?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use a set to find the unique values of the list below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list5 = [1,2,2,33,4,4,11,22,3,3,2]\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Booleans" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the following quiz questions, we will get a preview of comparison operators. In the table below, a=3 and b=4.\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!=If values of two operands are not equal, then condition becomes true. (a != b) is true.
>If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What will be the resulting Boolean of the following pieces of code (answer fist then check by typing it in!)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "2 > 3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "3 <= 2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "3 == 2.0" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "3.0 == 3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "4**0.5 != 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Final Question: What is the boolean output of the cell block below?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# two nested lists\n", + "l_one = [1,2,[3,4]]\n", + "l_two = [1,2,{'k1':4}]\n", + "\n", + "# True or False?\n", + "l_one[2][0] >= l_two[2]['k1']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job on your first assessment! " + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/10-Objects and Data Structures Assessment Test-Solution-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/10-Objects and Data Structures Assessment Test-Solution-checkpoint.ipynb new file mode 100644 index 0000000..952dfa0 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/.ipynb_checkpoints/10-Objects and Data Structures Assessment Test-Solution-checkpoint.ipynb @@ -0,0 +1,951 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Objects and Data Structures Assessment Test" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Test your knowledge. \n", + "\n", + "** Answer the following questions **" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Write a brief description of all the following Object Types and Data Structures we've learned about: " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**For the full answers, review the Jupyter notebook introductions of each topic!**\n", + "\n", + "[Numbers](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Numbers.ipynb)\n", + "\n", + "[Strings](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Strings.ipynb)\n", + "\n", + "[Lists](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Lists.ipynb)\n", + "\n", + "[Tuples](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Tuples.ipynb)\n", + "\n", + "[Dictionaries](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Dictionaries.ipynb)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Numbers\n", + "\n", + "Write an equation that uses multiplication, division, an exponent, addition, and subtraction that is equal to 100.25.\n", + "\n", + "Hint: This is just to test your memory of the basic arithmetic commands, work backwards from 100.25" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100.25" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Your answer is probably different\n", + "(60 + (10 ** 2) / 4 * 7) - 134.75" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Answer these 3 questions without typing code. Then type code to check your answer.\n", + "\n", + " What is the value of the expression 4 * (6 + 5)\n", + " \n", + " What is the value of the expression 4 * 6 + 5 \n", + " \n", + " What is the value of the expression 4 + 6 * 5 " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "44" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "4 * (6 + 5)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "29" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "4 * 6 + 5 " + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "34" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "4 + 6 * 5 " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is the *type* of the result of the expression 3 + 1.5 + 4?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Answer: Floating Point Number**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What would you use to find a number’s square root, as well as its square? " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10.0" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Square root:\n", + "100 ** 0.5" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Square:\n", + "10 ** 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Given the string 'hello' give an index command that returns 'e'. Enter your code in the cell below:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'e'" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s = 'hello'\n", + "# Print out 'e' using indexing\n", + "\n", + "s[1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Reverse the string 'hello' using slicing:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'olleh'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s ='hello'\n", + "# Reverse the string using slicing\n", + "\n", + "s[::-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Given the string 'hello', give two methods of producing the letter 'o' using indexing." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'o'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s ='hello'\n", + "# Print out the 'o'\n", + "\n", + "# Method 1:\n", + "\n", + "s[-1]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'o'" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 2:\n", + "\n", + "s[4]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Lists" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Build this list [0,0,0] two separate ways." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 0, 0]" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 1:\n", + "[0]*3" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 0, 0]" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 2:\n", + "list2 = [0,0,0]\n", + "list2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Reassign 'hello' in this nested list to say 'goodbye' instead:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "list3 = [1,2,[3,4,'hello']]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "list3[2][2] = 'goodbye'" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, [3, 4, 'goodbye']]" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Sort the list below:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "list4 = [5,3,4,6,1]" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 3, 4, 5, 6]" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 1:\n", + "sorted(list4)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 3, 4, 5, 6]" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 2:\n", + "list4.sort()\n", + "list4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionaries" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using keys and indexing, grab the 'hello' from the following dictionaries:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d = {'simple_key':'hello'}\n", + "# Grab 'hello'\n", + "\n", + "d['simple_key']" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d = {'k1':{'k2':'hello'}}\n", + "# Grab 'hello'\n", + "\n", + "d['k1']['k2']" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "# Getting a little tricker\n", + "d = {'k1':[{'nest_key':['this is deep',['hello']]}]}" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# This was harder than I expected...\n", + "d['k1'][0]['nest_key'][1][0]" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "# This will be hard and annoying!\n", + "d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]}" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Phew!\n", + "d['k1'][2]['k2'][1]['tough'][2][0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Can you sort a dictionary? Why or why not?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Answer: No! Because normal dictionaries are *mappings* not a sequence. **" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Tuples" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is the major difference between tuples and lists?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Tuples are immutable!**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "How do you create a tuple?" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [], + "source": [ + "t = (1,2,3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Sets " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is unique about a set?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Answer: They don't allow for duplicate items!**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use a set to find the unique values of the list below:" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [], + "source": [ + "list5 = [1,2,2,33,4,4,11,22,3,3,2]" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2, 3, 4, 11, 22, 33}" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set(list5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Booleans" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the following quiz questions, we will get a preview of comparison operators. In the table below, a=3 and b=4.\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!=If values of two operands are not equal, then condition becomes true. (a != b) is true.
>If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What will be the resulting Boolean of the following pieces of code (answer fist then check by typing it in!)" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "2 > 3" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "3 <= 2" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "3 == 2.0" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "3.0 == 3" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "4**0.5 != 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Final Question: What is the boolean output of the cell block below?" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# two nested lists\n", + "l_one = [1,2,[3,4]]\n", + "l_two = [1,2,{'k1':4}]\n", + "\n", + "# True or False?\n", + "l_one[2][0] >= l_two[2]['k1']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job on your first assessment! " + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/01-Numbers.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/01-Numbers.ipynb new file mode 100644 index 0000000..bc8e78a --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/01-Numbers.ipynb @@ -0,0 +1,545 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Numbers and more in Python!\n", + "\n", + "In this lecture, we will learn about numbers in Python and how to use them.\n", + "\n", + "We'll learn about the following topics:\n", + "\n", + " 1.) Types of Numbers in Python\n", + " 2.) Basic Arithmetic\n", + " 3.) Differences between classic division and floor division\n", + " 4.) Object Assignment in Python" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Types of numbers\n", + "\n", + "Python has various \"types\" of numbers (numeric literals). We'll mainly focus on integers and floating point numbers.\n", + "\n", + "Integers are just whole numbers, positive or negative. For example: 2 and -2 are examples of integers.\n", + "\n", + "Floating point numbers in Python are notable because they have a decimal point in them, or use an exponential (e) to define the number. For example 2.0 and -2.1 are examples of floating point numbers. 4E2 (4 times 10 to the power of 2) is also an example of a floating point number in Python.\n", + "\n", + "Throughout this course we will be mainly working with integers or simple float number types.\n", + "\n", + "Here is a table of the two main types we will spend most of our time working with some examples:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "\n", + "\n", + " \n", + " \n", + "\n", + "\n", + "\n", + " \n", + " \n", + "\n", + "\n", + "\n", + " \n", + " \n", + "\n", + "
ExamplesNumber \"Type\"
1,2,-5,1000Integers
1.2,-0.5,2e2,3E2Floating-point numbers
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " \n", + " \n", + "Now let's start with some basic arithmetic." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Basic Arithmetic" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Addition\n", + "2+1" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Subtraction\n", + "2-1" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Multiplication\n", + "2*2" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1.5" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Division\n", + "3/2" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Floor Division\n", + "7//4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Whoa! What just happened? Last time I checked, 7 divided by 4 equals 1.75 not 1!**\n", + "\n", + "The reason we get this result is because we are using \"*floor*\" division. The // operator (two forward slashes) truncates the decimal without rounding, and returns an integer result." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**So what if we just want the remainder after division?**" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Modulo\n", + "7%4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "4 goes into 7 once, with a remainder of 3. The % operator returns the remainder after division." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Arithmetic continued" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "8" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Powers\n", + "2**3" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2.0" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Can also do roots this way\n", + "4**0.5" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "105" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Order of Operations followed in Python\n", + "2 + 10 * 10 + 3" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "156" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Can use parentheses to specify orders\n", + "(2+10) * (10+3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Variable Assignments\n", + "\n", + "Now that we've seen how to use numbers in Python as a calculator let's see how we can assign names and create variables.\n", + "\n", + "We use a single equals sign to assign labels to variables. Let's see a few examples of how we can do this." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "# Let's create an object called \"a\" and assign it the number 5\n", + "a = 5" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now if I call *a* in my Python script, Python will treat it as the number 5." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Adding the objects\n", + "a+a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What happens on reassignment? Will Python let us write it over?" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "# Reassignment\n", + "a = 10" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Yes! Python allows you to write over assigned variable names. We can also use the variables themselves when doing the reassignment. Here is an example of what I mean:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "a" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "# Use A to redefine A\n", + "a = a + a" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "20" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check \n", + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The names you use when creating these labels need to follow a few rules:\n", + "\n", + " 1. Names can not start with a number.\n", + " 2. There can be no spaces in the name, use _ instead.\n", + " 3. Can't use any of these symbols :'\",<>/?|\\()!@#$%^&*~-+\n", + " 4. It's considered best practice (PEP8) that names are lowercase.\n", + " 5. Avoid using the characters 'l' (lowercase letter el), 'O' (uppercase letter oh), \n", + " or 'I' (uppercase letter eye) as single character variable names.\n", + " 6. Avoid using words that have special meaning in Python like \"list\" and \"str\"\n", + "\n", + "\n", + "Using variable names can be a very useful way to keep track of different variables in Python. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [], + "source": [ + "# Use object names to keep better track of what's going on in your code!\n", + "my_income = 100\n", + "\n", + "tax_rate = 0.1\n", + "\n", + "my_taxes = my_income*tax_rate" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10.0" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Show my taxes!\n", + "my_taxes" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So what have we learned? We learned some of the basics of numbers in Python. We also learned how to do arithmetic and use Python as a basic calculator. We then wrapped it up with learning about Variable Assignment in Python.\n", + "\n", + "Up next we'll learn about Strings!" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/01-Variable Assignment.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/01-Variable Assignment.ipynb new file mode 100644 index 0000000..c5af87b --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/01-Variable Assignment.ipynb @@ -0,0 +1,437 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Variable Assignment\n", + "\n", + "## Rules for variable names\n", + "* names can not start with a number\n", + "* names can not contain spaces, use _ intead\n", + "* names can not contain any of these symbols:\n", + "\n", + " :'\",<>/?|\\!@#%^&*~-+\n", + " \n", + "* it's considered best practice ([PEP8](https://www.python.org/dev/peps/pep-0008/#function-and-variable-names)) that names are lowercase with underscores\n", + "* avoid using Python built-in keywords like `list` and `str`\n", + "* avoid using the single characters `l` (lowercase letter el), `O` (uppercase letter oh) and `I` (uppercase letter eye) as they can be confused with `1` and `0`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dynamic Typing\n", + "\n", + "Python uses *dynamic typing*, meaning you can reassign variables to different data types. This makes Python very flexible in assigning data types; it differs from other languages that are *statically typed*." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "my_dogs = 2" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dogs" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "my_dogs = ['Sammy', 'Frankie']" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Sammy', 'Frankie']" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dogs" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Pros and Cons of Dynamic Typing\n", + "#### Pros of Dynamic Typing\n", + "* very easy to work with\n", + "* faster development time\n", + "\n", + "#### Cons of Dynamic Typing\n", + "* may result in unexpected bugs!\n", + "* you need to be aware of `type()`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Assigning Variables\n", + "Variable assignment follows `name = object`, where a single equals sign `=` is an *assignment operator*" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "a = 5" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we assigned the integer object `5` to the variable name `a`.
Let's assign `a` to something else:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "a = 10" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can now use `a` in place of the number `10`:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "20" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a + a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Reassigning Variables\n", + "Python lets you reassign variables with a reference to the same object." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "a = a + 10" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "20" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There's actually a shortcut for this. Python lets you add, subtract, multiply and divide numbers with reassignment using `+=`, `-=`, `*=`, and `/=`." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "a += 10" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "30" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "a *= 2" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "60" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Determining variable type with `type()`\n", + "You can check what type of object is assigned to a variable using Python's built-in `type()` function. Common data types include:\n", + "* **int** (for integer)\n", + "* **float**\n", + "* **str** (for string)\n", + "* **list**\n", + "* **tuple**\n", + "* **dict** (for dictionary)\n", + "* **set**\n", + "* **bool** (for Boolean True/False)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "int" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [], + "source": [ + "a = (1,2)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "tuple" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "type(a)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Simple Exercise\n", + "This shows how variables make calculations more readable and easier to follow." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [], + "source": [ + "my_income = 100\n", + "tax_rate = 0.1\n", + "my_taxes = my_income * tax_rate" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10.0" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_taxes" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! You should now understand the basics of variable assignment and reassignment in Python.
Up next, we'll learn about strings!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/02-Strings.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/02-Strings.ipynb new file mode 100644 index 0000000..1ef2117 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/02-Strings.ipynb @@ -0,0 +1,1003 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Strings are used in Python to record text information, such as names. Strings in Python are actually a *sequence*, which basically means Python keeps track of every element in the string as a sequence. For example, Python understands the string \"hello' to be a sequence of letters in a specific order. This means we will be able to use indexing to grab particular letters (like the first letter, or the last letter).\n", + "\n", + "This idea of a sequence is an important one in Python and we will touch upon it later on in the future.\n", + "\n", + "In this lecture we'll learn about the following:\n", + "\n", + " 1.) Creating Strings\n", + " 2.) Printing Strings\n", + " 3.) String Indexing and Slicing\n", + " 4.) String Properties\n", + " 5.) String Methods\n", + " 6.) Print Formatting" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Creating a String\n", + "To create a string in Python you need to use either single quotes or double quotes. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Single word\n", + "'hello'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is also a string'" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Entire phrase \n", + "'This is also a string'" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'String built with double quotes'" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# We can also use double quote\n", + "\"String built with double quotes\"" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "invalid syntax (, line 2)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m2\u001b[0m\n\u001b[1;33m ' I'm using single quotes, but this will create an error'\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m invalid syntax\n" + ] + } + ], + "source": [ + "# Be careful with quotes!\n", + "' I'm using single quotes, but this will create an error'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The reason for the error above is because the single quote in I'm stopped the string. You can use combinations of double and single quotes to get the complete statement." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "\"Now I'm ready to use the single quotes inside a string!\"" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "\"Now I'm ready to use the single quotes inside a string!\"" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now let's learn about printing strings!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Printing a String\n", + "\n", + "Using Jupyter notebook with just a string in a cell will automatically output strings, but the correct way to display strings in your output is by using a print function." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# We can simply declare a string\n", + "'Hello World'" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World 2'" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Note that we can't output multiple strings this way\n", + "'Hello World 1'\n", + "'Hello World 2'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use a print statement to print a string." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello World 1\n", + "Hello World 2\n", + "Use \n", + " to print a new line\n", + "\n", + "\n", + "See what I mean?\n" + ] + } + ], + "source": [ + "print('Hello World 1')\n", + "print('Hello World 2')\n", + "print('Use \\n to print a new line')\n", + "print('\\n')\n", + "print('See what I mean?')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## String Basics" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use a function called len() to check the length of a string!" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "11" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len('Hello World')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Python's built-in len() function counts all of the characters in the string, including spaces and punctuation." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## String Indexing\n", + "We know strings are a sequence, which means Python can use indexes to call parts of the sequence. Let's learn how this works.\n", + "\n", + "In Python, we use brackets [] after an object to call its index. We should also note that indexing starts at 0 for Python. Let's create a new object called s and then walk through a few examples of indexing." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "# Assign s as a string\n", + "s = 'Hello World'" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Check\n", + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello World\n" + ] + } + ], + "source": [ + "# Print the object\n", + "print(s) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's start indexing!" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'H'" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Show first element (in this case a letter)\n", + "s[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'e'" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[1]" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'l'" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s[2]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use a : to perform *slicing* which grabs everything up to a designated point. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'ello World'" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything past the first term all the way to the length of s which is len(s)\n", + "s[1:]" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Note that there is no change to the original s\n", + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hel'" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything UP TO the 3rd index\n", + "s[:3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note the above slicing. Here we're telling Python to grab everything from 0 up to 3. It doesn't include the 3rd index. You'll notice this a lot in Python, where statements and are usually in the context of \"up to, but not including\"." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Everything\n", + "s[:]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use negative indexing to go backwards." + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'d'" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Last letter (one index behind 0 so it loops back around)\n", + "s[-1]" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello Worl'" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything but the last letter\n", + "s[:-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use index and slice notation to grab elements of a sequence by a specified step size (the default is 1). For instance we can use two colons in a row and then a number specifying the frequency to grab elements. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything, but go in steps size of 1\n", + "s[::1]" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'HloWrd'" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything, but go in step sizes of 2\n", + "s[::2]" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'dlroW olleH'" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# We can use this to print a string backwards\n", + "s[::-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## String Properties\n", + "It's important to note that strings have an important property known as *immutability*. This means that once a string is created, the elements within it can not be changed or replaced. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "ename": "TypeError", + "evalue": "'str' object does not support item assignment", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;31m# Let's try to change the first letter to 'x'\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0ms\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;34m'x'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: 'str' object does not support item assignment" + ] + } + ], + "source": [ + "# Let's try to change the first letter to 'x'\n", + "s[0] = 'x'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how the error tells us directly what we can't do, change the item assignment!\n", + "\n", + "Something we *can* do is concatenate strings!" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World'" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World concatenate me!'" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Concatenate strings!\n", + "s + ' concatenate me!'" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [], + "source": [ + "# We can reassign s completely though!\n", + "s = s + ' concatenate me!'" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello World concatenate me!\n" + ] + } + ], + "source": [ + "print(s)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World concatenate me!'" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use the multiplication symbol to create repetition!" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "letter = 'z'" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'zzzzzzzzzz'" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "letter*10" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Basic Built-in String methods\n", + "\n", + "Objects in Python usually have built-in methods. These methods are functions inside the object (we will learn about these in much more depth later) that can perform actions or commands on the object itself.\n", + "\n", + "We call methods with a period and then the method name. Methods are in the form:\n", + "\n", + "object.method(parameters)\n", + "\n", + "Where parameters are extra arguments we can pass into the method. Don't worry if the details don't make 100% sense right now. Later on we will be creating our own objects and functions!\n", + "\n", + "Here are some examples of built-in methods in strings:" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello World concatenate me!'" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'HELLO WORLD CONCATENATE ME!'" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Upper Case a string\n", + "s.upper()" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello world concatenate me!'" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Lower case\n", + "s.lower()" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Hello', 'World', 'concatenate', 'me!']" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Split a string by blank space (this is the default)\n", + "s.split()" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Hello ', 'orld concatenate me!']" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Split by a specific element (doesn't include the element that was split on)\n", + "s.split('W')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are many more methods than the ones covered here. Visit the Advanced String section to find out more!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Print Formatting\n", + "\n", + "We can use the .format() method to add formatted objects to printed string statements. \n", + "\n", + "The easiest way to show this is through an example:" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Insert another string with curly brackets: The inserted string'" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'Insert another string with curly brackets: {}'.format('The inserted string')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We will revisit this string formatting topic in later sections when we are building our projects!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Next up: Lists!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/03-Print Formatting with Strings.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/03-Print Formatting with Strings.ipynb new file mode 100644 index 0000000..7661e9f --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/03-Print Formatting with Strings.ipynb @@ -0,0 +1,713 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# String Formatting\n", + "\n", + "String formatting lets you inject items into a string rather than trying to chain items together using commas or string concatenation. As a quick comparison, consider:\n", + "\n", + " player = 'Thomas'\n", + " points = 33\n", + " \n", + " 'Last night, '+player+' scored '+str(points)+' points.' # concatenation\n", + " \n", + " f'Last night, {player} scored {points} points.' # string formatting\n", + "\n", + "\n", + "There are three ways to perform string formatting.\n", + "* The oldest method involves placeholders using the modulo `%` character.\n", + "* An improved technique uses the `.format()` string method.\n", + "* The newest method, introduced with Python 3.6, uses formatted string literals, called *f-strings*.\n", + "\n", + "Since you will likely encounter all three versions in someone else's code, we describe each of them here." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Formatting with placeholders\n", + "You can use %s to inject strings into your print statements. The modulo `%` is referred to as a \"string formatting operator\"." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm going to inject something here.\n" + ] + } + ], + "source": [ + "print(\"I'm going to inject %s here.\" %'something')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can pass multiple items by placing them inside a tuple after the `%` operator." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm going to inject some text here, and more text here.\n" + ] + } + ], + "source": [ + "print(\"I'm going to inject %s text here, and %s text here.\" %('some','more'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can also pass variable names:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm going to inject some text here, and more text here.\n" + ] + } + ], + "source": [ + "x, y = 'some', 'more'\n", + "print(\"I'm going to inject %s text here, and %s text here.\"%(x,y))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Format conversion methods.\n", + "It should be noted that two methods %s and %r convert any python object to a string using two separate methods: `str()` and `repr()`. We will learn more about these functions later on in the course, but you should note that `%r` and `repr()` deliver the *string representation* of the object, including quotation marks and any escape characters." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He said his name was Fred.\n", + "He said his name was 'Fred'.\n" + ] + } + ], + "source": [ + "print('He said his name was %s.' %'Fred')\n", + "print('He said his name was %r.' %'Fred')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As another example, `\\t` inserts a tab into a string." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I once caught a fish this \tbig.\n", + "I once caught a fish 'this \\tbig'.\n" + ] + } + ], + "source": [ + "print('I once caught a fish %s.' %'this \\tbig')\n", + "print('I once caught a fish %r.' %'this \\tbig')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The `%s` operator converts whatever it sees into a string, including integers and floats. The `%d` operator converts numbers to integers first, without rounding. Note the difference below:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I wrote 3.75 programs today.\n", + "I wrote 3 programs today.\n" + ] + } + ], + "source": [ + "print('I wrote %s programs today.' %3.75)\n", + "print('I wrote %d programs today.' %3.75) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Padding and Precision of Floating Point Numbers\n", + "Floating point numbers use the format %5.2f. Here, 5 would be the minimum number of characters the string should contain; these may be padded with whitespace if the entire number does not have this many digits. Next to this, .2f stands for how many numbers to show past the decimal point. Let's see some examples:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13.14\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %5.2f' %(13.144))" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %1.0f' %(13.144))" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13.14400\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %1.5f' %(13.144))" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13.14\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %10.2f' %(13.144))" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Floating point numbers: 13.14\n" + ] + } + ], + "source": [ + "print('Floating point numbers: %25.2f' %(13.144))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For more information on string formatting with placeholders visit https://docs.python.org/3/library/stdtypes.html#old-string-formatting" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Multiple Formatting\n", + "Nothing prohibits using more than one conversion tool in the same print statement:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First: hi!, Second: 3.14, Third: 'bye!'\n" + ] + } + ], + "source": [ + "print('First: %s, Second: %5.2f, Third: %r' %('hi!',3.1415,'bye!'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Formatting with the `.format()` method\n", + "A better way to format objects into your strings for print statements is with the string `.format()` method. The syntax is:\n", + "\n", + " 'String here {} then also {}'.format('something1','something2')\n", + " \n", + "For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a string with an insert\n" + ] + } + ], + "source": [ + "print('This is a string with an {}'.format('insert'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### The .format() method has several advantages over the %s placeholder method:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 1. Inserted objects can be called by index position:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The quick brown fox\n" + ] + } + ], + "source": [ + "print('The {2} {1} {0}'.format('fox','brown','quick'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 2. Inserted objects can be assigned keywords:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First Object: 1, Second Object: Two, Third Object: 12.3\n" + ] + } + ], + "source": [ + "print('First Object: {a}, Second Object: {b}, Third Object: {c}'.format(a=1,b='Two',c=12.3))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### 3. Inserted objects can be reused, avoiding duplication:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A penny saved is a penny earned.\n", + "A penny saved is a penny earned.\n" + ] + } + ], + "source": [ + "print('A %s saved is a %s earned.' %('penny','penny'))\n", + "# vs.\n", + "print('A {p} saved is a {p} earned.'.format(p='penny'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Alignment, padding and precision with `.format()`\n", + "Within the curly braces you can assign field lengths, left/right alignments, rounding parameters and more" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Fruit | Quantity \n", + "Apples | 3.0\n", + "Oranges | 10\n" + ] + } + ], + "source": [ + "print('{0:8} | {1:9}'.format('Fruit', 'Quantity'))\n", + "print('{0:8} | {1:9}'.format('Apples', 3.))\n", + "print('{0:8} | {1:9}'.format('Oranges', 10))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By default, `.format()` aligns text to the left, numbers to the right. You can pass an optional `<`,`^`, or `>` to set a left, center or right alignment:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Left | Center | Right\n", + "11 | 22 | 33\n" + ] + } + ], + "source": [ + "print('{0:<8} | {1:^8} | {2:>8}'.format('Left','Center','Right'))\n", + "print('{0:<8} | {1:^8} | {2:>8}'.format(11,22,33))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can precede the aligment operator with a padding character" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Left==== | -Center- | ...Right\n", + "11====== | ---22--- | ......33\n" + ] + } + ], + "source": [ + "print('{0:=<8} | {1:-^8} | {2:.>8}'.format('Left','Center','Right'))\n", + "print('{0:=<8} | {1:-^8} | {2:.>8}'.format(11,22,33))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Field widths and float precision are handled in a way similar to placeholders. The following two print statements are equivalent:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is my ten-character, two-decimal number: 13.58\n", + "This is my ten-character, two-decimal number: 13.58\n" + ] + } + ], + "source": [ + "print('This is my ten-character, two-decimal number:%10.2f' %13.579)\n", + "print('This is my ten-character, two-decimal number:{0:10.2f}'.format(13.579))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that there are 5 spaces following the colon, and 5 characters taken up by 13.58, for a total of ten characters.\n", + "\n", + "For more information on the string `.format()` method visit https://docs.python.org/3/library/string.html#formatstrings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Formatted String Literals (f-strings)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Introduced in Python 3.6, f-strings offer several benefits over the older `.format()` string method described above. For one, you can bring outside variables immediately into to the string rather than pass them as arguments through `.format(var)`." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He said his name is Fred.\n" + ] + } + ], + "source": [ + "name = 'Fred'\n", + "\n", + "print(f\"He said his name is {name}.\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Pass `!r` to get the string representation:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "He said his name is 'Fred'\n" + ] + } + ], + "source": [ + "print(f\"He said his name is {name!r}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Float formatting follows `\"result: {value:{width}.{precision}}\"`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Where with the `.format()` method you might see `{value:10.4f}`, with f-strings this can become `{value:{10}.{6}}`\n" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "My 10 character, four decimal number is: 23.4568\n", + "My 10 character, four decimal number is: 23.4568\n" + ] + } + ], + "source": [ + "num = 23.45678\n", + "print(\"My 10 character, four decimal number is:{0:10.4f}\".format(num))\n", + "print(f\"My 10 character, four decimal number is:{num:{10}.{6}}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that with f-strings, *precision* refers to the total number of digits, not just those following the decimal. This fits more closely with scientific notation and statistical analysis. Unfortunately, f-strings do not pad to the right of the decimal, even if precision allows it:" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "My 10 character, four decimal number is: 23.4500\n", + "My 10 character, four decimal number is: 23.45\n" + ] + } + ], + "source": [ + "num = 23.45\n", + "print(\"My 10 character, four decimal number is:{0:10.4f}\".format(num))\n", + "print(f\"My 10 character, four decimal number is:{num:{10}.{6}}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If this becomes important, you can always use `.format()` method syntax inside an f-string:" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "My 10 character, four decimal number is: 23.4500\n", + "My 10 character, four decimal number is: 23.4500\n" + ] + } + ], + "source": [ + "num = 23.45\n", + "print(\"My 10 character, four decimal number is:{0:10.4f}\".format(num))\n", + "print(f\"My 10 character, four decimal number is:{num:10.4f}\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For more info on formatted string literals visit https://docs.python.org/3/reference/lexical_analysis.html#f-strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That is the basics of string formatting!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/04-Lists.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/04-Lists.ipynb new file mode 100644 index 0000000..332c404 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/04-Lists.ipynb @@ -0,0 +1,758 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lists\n", + "\n", + "Earlier when discussing strings we introduced the concept of a *sequence* in Python. Lists can be thought of the most general version of a *sequence* in Python. Unlike strings, they are mutable, meaning the elements inside a list can be changed!\n", + "\n", + "In this section we will learn about:\n", + " \n", + " 1.) Creating lists\n", + " 2.) Indexing and Slicing Lists\n", + " 3.) Basic List Methods\n", + " 4.) Nesting Lists\n", + " 5.) Introduction to List Comprehensions\n", + "\n", + "Lists are constructed with brackets [] and commas separating every element in the list.\n", + "\n", + "Let's go ahead and see how we can construct lists!" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Assign a list to an variable named my_list\n", + "my_list = [1,2,3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We just created a list of integers, but lists can actually hold different object types. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "my_list = ['A string',23,100.232,'o']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Just like strings, the len() function will tell you how many items are in the sequence of the list." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len(my_list)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Indexing and Slicing\n", + "Indexing and slicing work just like in strings. Let's make a new list to remind ourselves of how this works:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "my_list = ['one','two','three',4,5]" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'one'" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab element at index 0\n", + "my_list[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['two', 'three', 4, 5]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab index 1 and everything past it\n", + "my_list[1:]" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['one', 'two', 'three']" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab everything UP TO index 3\n", + "my_list[:3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use + to concatenate lists, just like we did for strings." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['one', 'two', 'three', 4, 5, 'new item']" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_list + ['new item']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note: This doesn't actually change the original list!" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['one', 'two', 'three', 4, 5]" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_list" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You would have to reassign the list to make the change permanent." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "# Reassign\n", + "my_list = my_list + ['add new item permanently']" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['one', 'two', 'three', 4, 5, 'add new item permanently']" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_list" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use the * for a duplication method similar to strings:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['one',\n", + " 'two',\n", + " 'three',\n", + " 4,\n", + " 5,\n", + " 'add new item permanently',\n", + " 'one',\n", + " 'two',\n", + " 'three',\n", + " 4,\n", + " 5,\n", + " 'add new item permanently']" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Make the list double\n", + "my_list * 2" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['one', 'two', 'three', 4, 5, 'add new item permanently']" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Again doubling not permanent\n", + "my_list" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Basic List Methods\n", + "\n", + "If you are familiar with another programming language, you might start to draw parallels between arrays in another language and lists in Python. Lists in Python however, tend to be more flexible than arrays in other languages for a two good reasons: they have no fixed size (meaning we don't have to specify how big a list will be), and they have no fixed type constraint (like we've seen above).\n", + "\n", + "Let's go ahead and explore some more special methods for lists:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "# Create a new list\n", + "list1 = [1,2,3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use the **append** method to permanently add an item to the end of a list:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "# Append\n", + "list1.append('append me!')" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 'append me!']" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Show\n", + "list1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use **pop** to \"pop off\" an item from the list. By default pop takes off the last index, but you can also specify which index to pop off. Let's see an example:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Pop off the 0 indexed item\n", + "list1.pop(0)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 3, 'append me!']" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Show\n", + "list1" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [], + "source": [ + "# Assign the popped element, remember default popped index is -1\n", + "popped_item = list1.pop()" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'append me!'" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "popped_item" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[2, 3]" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Show remaining list\n", + "list1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It should also be noted that lists indexing will return an error if there is no element at that index. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "ename": "IndexError", + "evalue": "list index out of range", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mIndexError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mlist1\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m100\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mIndexError\u001b[0m: list index out of range" + ] + } + ], + "source": [ + "list1[100]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use the **sort** method and the **reverse** methods to also effect your lists:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "new_list = ['a','e','x','b','c']" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'e', 'x', 'b', 'c']" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "new_list" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [], + "source": [ + "# Use reverse to reverse order (this is permanent!)\n", + "new_list.reverse()" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['c', 'b', 'x', 'e', 'a']" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "new_list" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [], + "source": [ + "# Use sort to sort the list (in this case alphabetical order, but for numbers it will go ascending)\n", + "new_list.sort()" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['a', 'b', 'c', 'e', 'x']" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "new_list" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nesting Lists\n", + "A great feature of of Python data structures is that they support *nesting*. This means we can have data structures within data structures. For example: A list inside a list.\n", + "\n", + "Let's see how this works!" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [], + "source": [ + "# Let's make three lists\n", + "lst_1=[1,2,3]\n", + "lst_2=[4,5,6]\n", + "lst_3=[7,8,9]\n", + "\n", + "# Make a list of lists to form a matrix\n", + "matrix = [lst_1,lst_2,lst_3]" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[[1, 2, 3], [4, 5, 6], [7, 8, 9]]" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Show\n", + "matrix" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can again use indexing to grab elements, but now there are two levels for the index. The items in the matrix object, and then the items inside that list!" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3]" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab first item in matrix object\n", + "matrix[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Grab first item of the first item in the matrix object\n", + "matrix[0][0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# List Comprehensions\n", + "Python has an advanced feature called list comprehensions. They allow for quick construction of lists. To fully understand list comprehensions we need to understand for loops. So don't worry if you don't completely understand this section, and feel free to just skip it since we will return to this topic later.\n", + "\n", + "But in case you want to know now, here are a few examples!" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [], + "source": [ + "# Build a list comprehension by deconstructing a for loop within a []\n", + "first_col = [row[0] for row in matrix]" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 4, 7]" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "first_col" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We used a list comprehension here to grab the first element of every row in the matrix object. We will cover this in much more detail later on!\n", + "\n", + "For more advanced methods and features of lists in Python, check out the Advanced Lists section later on in this course!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/05-Dictionaries.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/05-Dictionaries.ipynb new file mode 100644 index 0000000..3207f01 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/05-Dictionaries.ipynb @@ -0,0 +1,440 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Dictionaries\n", + "\n", + "We've been learning about *sequences* in Python but now we're going to switch gears and learn about *mappings* in Python. If you're familiar with other languages you can think of these Dictionaries as hash tables. \n", + "\n", + "This section will serve as a brief introduction to dictionaries and consist of:\n", + "\n", + " 1.) Constructing a Dictionary\n", + " 2.) Accessing objects from a dictionary\n", + " 3.) Nesting Dictionaries\n", + " 4.) Basic Dictionary Methods\n", + "\n", + "So what are mappings? Mappings are a collection of objects that are stored by a *key*, unlike a sequence that stored objects by their relative position. This is an important distinction, since mappings won't retain order since they have objects defined by a key.\n", + "\n", + "A Python dictionary consists of a key and then an associated value. That value can be almost any Python object.\n", + "\n", + "\n", + "## Constructing a Dictionary\n", + "Let's see how we can construct dictionaries to get a better understanding of how they work!" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Make a dictionary with {} and : to signify a key and a value\n", + "my_dict = {'key1':'value1','key2':'value2'}" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'value2'" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Call values by their key\n", + "my_dict['key2']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Its important to note that dictionaries are very flexible in the data types they can hold. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "my_dict = {'key1':123,'key2':[12,23,33],'key3':['item0','item1','item2']}" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['item0', 'item1', 'item2']" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Let's call items from the dictionary\n", + "my_dict['key3']" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'item0'" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Can call an index on that value\n", + "my_dict['key3'][0]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'ITEM0'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Can then even call methods on that value\n", + "my_dict['key3'][0].upper()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can affect the values of a key as well. For instance:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "123" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_dict['key1']" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "# Subtract 123 from the value\n", + "my_dict['key1'] = my_dict['key1'] - 123" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Check\n", + "my_dict['key1']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A quick note, Python has a built-in method of doing a self subtraction or addition (or multiplication or division). We could have also used += or -= for the above statement. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-123" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Set the object equal to itself minus 123 \n", + "my_dict['key1'] -= 123\n", + "my_dict['key1']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also create keys by assignment. For instance if we started off with an empty dictionary, we could continually add to it:" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "# Create a new dictionary\n", + "d = {}" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "# Create a new key through assignment\n", + "d['animal'] = 'Dog'" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "# Can do this with any object\n", + "d['answer'] = 42" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{'animal': 'Dog', 'answer': 42}" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "d" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Nesting with Dictionaries\n", + "\n", + "Hopefully you're starting to see how powerful Python is with its flexibility of nesting objects and calling methods on them. Let's see a dictionary nested inside a dictionary:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "# Dictionary nested inside a dictionary nested inside a dictionary\n", + "d = {'key1':{'nestkey':{'subnestkey':'value'}}}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Wow! That's a quite the inception of dictionaries! Let's see how we can grab that value:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'value'" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Keep calling the keys\n", + "d['key1']['nestkey']['subnestkey']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## A few Dictionary Methods\n", + "\n", + "There are a few methods we can call on a dictionary. Let's get a quick introduction to a few of them:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [], + "source": [ + "# Create a typical dictionary\n", + "d = {'key1':1,'key2':2,'key3':3}" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_keys(['key1', 'key2', 'key3'])" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method to return a list of all keys \n", + "d.keys()" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_values([1, 2, 3])" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method to grab all values\n", + "d.values()" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_items([('key1', 1), ('key2', 2), ('key3', 3)])" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method to return tuples of all items (we'll learn about tuples soon)\n", + "d.items()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hopefully you now have a good basic understanding how to construct dictionaries. There's a lot more to go into here, but we will revisit dictionaries at later time. After this section all you need to know is how to create a dictionary and how to retrieve values from it." + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/06-Tuples.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/06-Tuples.ipynb new file mode 100644 index 0000000..96907b1 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/06-Tuples.ipynb @@ -0,0 +1,266 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Tuples\n", + "\n", + "In Python tuples are very similar to lists, however, unlike lists they are *immutable* meaning they can not be changed. You would use tuples to present things that shouldn't be changed, such as days of the week, or dates on a calendar. \n", + "\n", + "In this section, we will get a brief overview of the following:\n", + "\n", + " 1.) Constructing Tuples\n", + " 2.) Basic Tuple Methods\n", + " 3.) Immutability\n", + " 4.) When to Use Tuples\n", + "\n", + "You'll have an intuition of how to use tuples based on what you've learned about lists. We can treat them very similarly with the major distinction being that tuples are immutable.\n", + "\n", + "## Constructing Tuples\n", + "\n", + "The construction of a tuples use () with elements separated by commas. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Create a tuple\n", + "t = (1,2,3)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check len just like a list\n", + "len(t)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "('one', 2)" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Can also mix object types\n", + "t = ('one',2)\n", + "\n", + "# Show\n", + "t" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'one'" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Use indexing just like we did in lists\n", + "t[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Slicing just like a list\n", + "t[-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Basic Tuple Methods\n", + "\n", + "Tuples have built-in methods, but not as many as lists do. Let's look at two of them:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Use .index to enter a value and return the index\n", + "t.index('one')" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Use .count to count the number of times a value appears\n", + "t.count('one')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Immutability\n", + "\n", + "It can't be stressed enough that tuples are immutable. To drive that point home:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "ename": "TypeError", + "evalue": "'tuple' object does not support item assignment", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mt\u001b[0m\u001b[1;33m[\u001b[0m\u001b[1;36m0\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m=\u001b[0m \u001b[1;34m'change'\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: 'tuple' object does not support item assignment" + ] + } + ], + "source": [ + "t[0]= 'change'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Because of this immutability, tuples can't grow. Once a tuple is made we can not add to it." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "ename": "AttributeError", + "evalue": "'tuple' object has no attribute 'append'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mt\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mappend\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'nope'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mAttributeError\u001b[0m: 'tuple' object has no attribute 'append'" + ] + } + ], + "source": [ + "t.append('nope')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## When to use Tuples\n", + "\n", + "You may be wondering, \"Why bother using tuples when they have fewer available methods?\" To be honest, tuples are not used as often as lists in programming, but are used when immutability is necessary. If in your program you are passing around an object and need to make sure it does not get changed, then a tuple becomes your solution. It provides a convenient source of data integrity.\n", + "\n", + "You should now be able to create and use tuples in your programming as well as have an understanding of their immutability.\n", + "\n", + "Up next Sets and Booleans!!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/07-Sets and Booleans.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/07-Sets and Booleans.ipynb new file mode 100644 index 0000000..f0749fd --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/07-Sets and Booleans.ipynb @@ -0,0 +1,311 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Set and Booleans\n", + "\n", + "There are two other object types in Python that we should quickly cover: Sets and Booleans. \n", + "\n", + "## Sets\n", + "\n", + "Sets are an unordered collection of *unique* elements. We can construct them by using the set() function. Let's go ahead and make a set to see how it works" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "x = set()" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# We add to sets with the add() method\n", + "x.add(1)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1}" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note the curly brackets. This does not indicate a dictionary! Although you can draw analogies as a set being a dictionary with only keys.\n", + "\n", + "We know that a set has only unique entries. So what happens when we try to add something that is already in a set?" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Add a different element\n", + "x.add(2)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2}" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "x" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Try to add the same element\n", + "x.add(1)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2}" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "x" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how it won't place another 1 there. That's because a set is only concerned with unique elements! We can cast a list with multiple repeat elements to a set to get the unique elements. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Create a list with repeats\n", + "list1 = [1,1,2,2,3,4,5,6,1,1]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2, 3, 4, 5, 6}" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Cast as set to get unique values\n", + "set(list1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Booleans\n", + "\n", + "Python comes with Booleans (with predefined True and False displays that are basically just the integers 1 and 0). It also has a placeholder object called None. Let's walk through a few quick examples of Booleans (we will dive deeper into them later in this course)." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Set object to be a boolean\n", + "a = True" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Show\n", + "a" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can also use comparison operators to create booleans. We will go over all the comparison operators later on in the course." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Output is boolean\n", + "1 > 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use None as a placeholder for an object that we don't want to reassign yet:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# None placeholder\n", + "b = None" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "None\n" + ] + } + ], + "source": [ + "# Show\n", + "print(b)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Thats it! You should now have a basic understanding of Python objects and data structure types. Next, go ahead and do the assessment test!" + ] + } + ], + "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.1" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/08-Files.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/08-Files.ipynb new file mode 100644 index 0000000..e5aa6cb --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/08-Files.ipynb @@ -0,0 +1,556 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Files\n", + "\n", + "Python uses file objects to interact with external files on your computer. These file objects can be any sort of file you have on your computer, whether it be an audio file, a text file, emails, Excel documents, etc. Note: You will probably need to install certain libraries or modules to interact with those various file types, but they are easily available. (We will cover downloading modules later on in the course).\n", + "\n", + "Python has a built-in open function that allows us to open and play with basic file types. First we will need a file though. We're going to use some IPython magic to create a text file!\n", + "\n", + "## IPython Writing a File \n", + "#### This function is specific to jupyter notebooks! Alternatively, quickly create a simple .txt file with sublime text editor." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting test.txt\n" + ] + } + ], + "source": [ + "%%writefile test.txt\n", + "Hello, this is a quick test file." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Python Opening a file\n", + "\n", + "Let's being by opening the file test.txt that is located in the same directory as this notebook. For now we will work with files located in the same directory as the notebook or .py script you are using.\n", + "\n", + "It is very easy to get an error on this step:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "FileNotFoundError", + "evalue": "[Errno 2] No such file or directory: 'whoops.txt'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mFileNotFoundError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mmyfile\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mopen\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'whoops.txt'\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: 'whoops.txt'" + ] + } + ], + "source": [ + "myfile = open('whoops.txt')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To avoid this error,make sure your .txt file is saved in the same location as your notebook, to check your notebook location, use **pwd**:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'C:\\\\Users\\\\Marcial\\\\Pierian-Data-Courses\\\\Complete-Python-3-Bootcamp\\\\00-Python Object and Data Structure Basics'" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "pwd" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Alternatively, to grab files from any location on your computer, simply pass in the entire file path. **\n", + "\n", + "For Windows you need to use double \\ so python doesn't treat the second \\ as an escape character, a file path is in the form:\n", + "\n", + " myfile = open(\"C:\\\\Users\\\\YourUserName\\\\Home\\\\Folder\\\\myfile.txt\")\n", + "\n", + "For MacOS and Linux you use slashes in the opposite direction:\n", + "\n", + " myfile = open(\"/Users/YouUserName/Folder/myfile.txt\")" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Open the text.txt we made earlier\n", + "my_file = open('test.txt')" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello, this is a quick test file.'" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# We can now read the file\n", + "my_file.read()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "''" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# But what happens if we try to read it again?\n", + "my_file.read()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This happens because you can imagine the reading \"cursor\" is at the end of the file after having read it. So there is nothing left to read. We can reset the \"cursor\" like this:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Seek to the start of file (index 0)\n", + "my_file.seek(0)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Hello, this is a quick test file.'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Now read again\n", + "my_file.read()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can read a file line by line using the readlines method. Use caution with large files, since everything will be held in memory. We will learn how to iterate over large files later in the course." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['Hello, this is a quick test file.']" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Readlines returns a list of the lines in the file\n", + "my_file.seek(0)\n", + "my_file.readlines()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When you have finished using a file, it is always good practice to close it." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_file.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Writing to a File\n", + "\n", + "By default, the `open()` function will only allow us to read the file. We need to pass the argument `'w'` to write over the file. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Add a second argument to the function, 'w' which stands for write.\n", + "# Passing 'w+' lets us read and write to the file\n", + "\n", + "my_file = open('test.txt','w+')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Use caution! \n", + "Opening a file with `'w'` or `'w+'` truncates the original, meaning that anything that was in the original file **is deleted**!" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "18" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Write to the file\n", + "my_file.write('This is a new line')" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'This is a new line'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Read the file\n", + "my_file.seek(0)\n", + "my_file.read()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_file.close() # always do this when you're done with a file" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Appending to a File\n", + "Passing the argument `'a'` opens the file and puts the pointer at the end, so anything written is appended. Like `'w+'`, `'a+'` lets us read and write to a file. If the file does not exist, one will be created." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "23" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "my_file = open('test.txt','a+')\n", + "my_file.write('\\nThis is text being appended to test.txt')\n", + "my_file.write('\\nAnd another line here.')" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a new line\n", + "This is text being appended to test.txt\n", + "And another line here.\n" + ] + } + ], + "source": [ + "my_file.seek(0)\n", + "print(my_file.read())" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_file.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Appending with `%%writefile`\n", + "We can do the same thing using IPython cell magic:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Appending to test.txt\n" + ] + } + ], + "source": [ + "%%writefile -a test.txt\n", + "\n", + "This is text being appended to test.txt\n", + "And another line here." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Add a blank space if you want the first line to begin on its own line, as Jupyter won't recognize escape sequences like `\\n`" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Iterating through a File\n", + "\n", + "Lets get a quick preview of a for loop by iterating over a text file. First let's make a new text file with some IPython Magic:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting test.txt\n" + ] + } + ], + "source": [ + "%%writefile test.txt\n", + "First Line\n", + "Second Line" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we can use a little bit of flow to tell the program to for through every line of the file and do something:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First Line\n", + "\n", + "Second Line\n" + ] + } + ], + "source": [ + "for line in open('test.txt'):\n", + " print(line)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Don't worry about fully understanding this yet, for loops are coming up soon. But we'll break down what we did above. We said that for every line in this text file, go ahead and print that line. It's important to note a few things here:\n", + "\n", + "1. We could have called the \"line\" object anything (see example below).\n", + "2. By not calling `.read()` on the file, the whole text file was not stored in memory.\n", + "3. Notice the indent on the second line for print. This whitespace is required in Python." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "First Line\n", + "\n", + "Second Line\n" + ] + } + ], + "source": [ + "# Pertaining to the first point above\n", + "for asdf in open('test.txt'):\n", + " print(asdf)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We'll learn a lot more about this later, but up next: Sets and Booleans!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/09-Objects and Data Structures Assessment Test.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/09-Objects and Data Structures Assessment Test.ipynb new file mode 100644 index 0000000..149e61a --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/09-Objects and Data Structures Assessment Test.ipynb @@ -0,0 +1,528 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Objects and Data Structures Assessment Test" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Test your knowledge. \n", + "\n", + "** Answer the following questions **" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Write a brief description of all the following Object Types and Data Structures we've learned about: " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Numbers:\n", + "\n", + "Strings:\n", + "\n", + "Lists:\n", + "\n", + "Tuples:\n", + "\n", + "Dictionaries:\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Numbers\n", + "\n", + "Write an equation that uses multiplication, division, an exponent, addition, and subtraction that is equal to 100.25.\n", + "\n", + "Hint: This is just to test your memory of the basic arithmetic commands, work backwards from 100.25" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Answer these 3 questions without typing code. Then type code to check your answer.\n", + "\n", + " What is the value of the expression 4 * (6 + 5)\n", + " \n", + " What is the value of the expression 4 * 6 + 5 \n", + " \n", + " What is the value of the expression 4 + 6 * 5 " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is the *type* of the result of the expression 3 + 1.5 + 4?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What would you use to find a number’s square root, as well as its square? " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Square root:\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Square:\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Given the string 'hello' give an index command that returns 'e'. Enter your code in the cell below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "s = 'hello'\n", + "# Print out 'e' using indexing\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Reverse the string 'hello' using slicing:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "s ='hello'\n", + "# Reverse the string using slicing\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Given the string hello, give two methods of producing the letter 'o' using indexing." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "s ='hello'\n", + "# Print out the 'o'\n", + "\n", + "# Method 1:\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Method 2:\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Lists" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Build this list [0,0,0] two separate ways." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Method 1:\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Method 2:\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Reassign 'hello' in this nested list to say 'goodbye' instead:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list3 = [1,2,[3,4,'hello']]\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Sort the list below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list4 = [5,3,4,6,1]\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionaries" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using keys and indexing, grab the 'hello' from the following dictionaries:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "d = {'simple_key':'hello'}\n", + "# Grab 'hello'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "d = {'k1':{'k2':'hello'}}\n", + "# Grab 'hello'\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Getting a little tricker\n", + "d = {'k1':[{'nest_key':['this is deep',['hello']]}]}\n", + "\n", + "#Grab hello\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# This will be hard and annoying!\n", + "d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]}" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Can you sort a dictionary? Why or why not?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Tuples" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is the major difference between tuples and lists?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "How do you create a tuple?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Sets " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is unique about a set?

" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use a set to find the unique values of the list below:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "list5 = [1,2,2,33,4,4,11,22,3,3,2]\n", + "\n", + "\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Booleans" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the following quiz questions, we will get a preview of comparison operators. In the table below, a=3 and b=4.\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!=If values of two operands are not equal, then condition becomes true. (a != b) is true.
>If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What will be the resulting Boolean of the following pieces of code (answer fist then check by typing it in!)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "2 > 3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "3 <= 2" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "3 == 2.0" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "3.0 == 3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Answer before running cell\n", + "4**0.5 != 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Final Question: What is the boolean output of the cell block below?" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# two nested lists\n", + "l_one = [1,2,[3,4]]\n", + "l_two = [1,2,{'k1':4}]\n", + "\n", + "# True or False?\n", + "l_one[2][0] >= l_two[2]['k1']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job on your first assessment! " + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/10-Objects and Data Structures Assessment Test-Solution.ipynb b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/10-Objects and Data Structures Assessment Test-Solution.ipynb new file mode 100644 index 0000000..952dfa0 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/10-Objects and Data Structures Assessment Test-Solution.ipynb @@ -0,0 +1,951 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Objects and Data Structures Assessment Test" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Test your knowledge. \n", + "\n", + "** Answer the following questions **" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Write a brief description of all the following Object Types and Data Structures we've learned about: " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**For the full answers, review the Jupyter notebook introductions of each topic!**\n", + "\n", + "[Numbers](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Numbers.ipynb)\n", + "\n", + "[Strings](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Strings.ipynb)\n", + "\n", + "[Lists](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Lists.ipynb)\n", + "\n", + "[Tuples](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Tuples.ipynb)\n", + "\n", + "[Dictionaries](http://nbviewer.ipython.org/github/jmportilla/Complete-Python-Bootcamp/blob/master/Dictionaries.ipynb)\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Numbers\n", + "\n", + "Write an equation that uses multiplication, division, an exponent, addition, and subtraction that is equal to 100.25.\n", + "\n", + "Hint: This is just to test your memory of the basic arithmetic commands, work backwards from 100.25" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100.25" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Your answer is probably different\n", + "(60 + (10 ** 2) / 4 * 7) - 134.75" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Answer these 3 questions without typing code. Then type code to check your answer.\n", + "\n", + " What is the value of the expression 4 * (6 + 5)\n", + " \n", + " What is the value of the expression 4 * 6 + 5 \n", + " \n", + " What is the value of the expression 4 + 6 * 5 " + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "44" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "4 * (6 + 5)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "29" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "4 * 6 + 5 " + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "34" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "4 + 6 * 5 " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is the *type* of the result of the expression 3 + 1.5 + 4?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Answer: Floating Point Number**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What would you use to find a number’s square root, as well as its square? " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10.0" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Square root:\n", + "100 ** 0.5" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Square:\n", + "10 ** 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Strings" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Given the string 'hello' give an index command that returns 'e'. Enter your code in the cell below:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'e'" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s = 'hello'\n", + "# Print out 'e' using indexing\n", + "\n", + "s[1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Reverse the string 'hello' using slicing:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'olleh'" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s ='hello'\n", + "# Reverse the string using slicing\n", + "\n", + "s[::-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Given the string 'hello', give two methods of producing the letter 'o' using indexing." + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'o'" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s ='hello'\n", + "# Print out the 'o'\n", + "\n", + "# Method 1:\n", + "\n", + "s[-1]" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'o'" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 2:\n", + "\n", + "s[4]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Lists" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Build this list [0,0,0] two separate ways." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 0, 0]" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 1:\n", + "[0]*3" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 0, 0]" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 2:\n", + "list2 = [0,0,0]\n", + "list2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Reassign 'hello' in this nested list to say 'goodbye' instead:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "list3 = [1,2,[3,4,'hello']]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "list3[2][2] = 'goodbye'" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, [3, 4, 'goodbye']]" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Sort the list below:" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "list4 = [5,3,4,6,1]" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 3, 4, 5, 6]" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 1:\n", + "sorted(list4)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 3, 4, 5, 6]" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Method 2:\n", + "list4.sort()\n", + "list4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Dictionaries" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Using keys and indexing, grab the 'hello' from the following dictionaries:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d = {'simple_key':'hello'}\n", + "# Grab 'hello'\n", + "\n", + "d['simple_key']" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "d = {'k1':{'k2':'hello'}}\n", + "# Grab 'hello'\n", + "\n", + "d['k1']['k2']" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "# Getting a little tricker\n", + "d = {'k1':[{'nest_key':['this is deep',['hello']]}]}" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# This was harder than I expected...\n", + "d['k1'][0]['nest_key'][1][0]" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "# This will be hard and annoying!\n", + "d = {'k1':[1,2,{'k2':['this is tricky',{'tough':[1,2,['hello']]}]}]}" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'hello'" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Phew!\n", + "d['k1'][2]['k2'][1]['tough'][2][0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Can you sort a dictionary? Why or why not?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Answer: No! Because normal dictionaries are *mappings* not a sequence. **" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Tuples" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is the major difference between tuples and lists?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Tuples are immutable!**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "How do you create a tuple?" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [], + "source": [ + "t = (1,2,3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Sets " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What is unique about a set?" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Answer: They don't allow for duplicate items!**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Use a set to find the unique values of the list below:" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [], + "source": [ + "list5 = [1,2,2,33,4,4,11,22,3,3,2]" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "{1, 2, 3, 4, 11, 22, 33}" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "set(list5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Booleans" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "For the following quiz questions, we will get a preview of comparison operators. In the table below, a=3 and b=4.\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!=If values of two operands are not equal, then condition becomes true. (a != b) is true.
>If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What will be the resulting Boolean of the following pieces of code (answer fist then check by typing it in!)" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 28, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "2 > 3" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "3 <= 2" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "3 == 2.0" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "3.0 == 3" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Answer before running cell\n", + "4**0.5 != 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Final Question: What is the boolean output of the cell block below?" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# two nested lists\n", + "l_one = [1,2,[3,4]]\n", + "l_two = [1,2,{'k1':4}]\n", + "\n", + "# True or False?\n", + "l_one[2][0] >= l_two[2]['k1']" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job on your first assessment! " + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/test.txt b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/test.txt new file mode 100644 index 0000000..48d4c52 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/00-Python Object and Data Structure Basics/test.txt @@ -0,0 +1,2 @@ +First Line +Second Line \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/.ipynb_checkpoints/01-Comparison Operators-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/.ipynb_checkpoints/01-Comparison Operators-checkpoint.ipynb new file mode 100644 index 0000000..d14ff8c --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/.ipynb_checkpoints/01-Comparison Operators-checkpoint.ipynb @@ -0,0 +1,376 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Comparison Operators \n", + "\n", + "In this lecture we will be learning about Comparison Operators in Python. These operators will allow us to compare variables and output a Boolean value (True or False). \n", + "\n", + "If you have any sort of background in Math, these operators should be very straight forward.\n", + "\n", + "First we'll present a table of the comparison operators and then work through some examples:\n", + "\n", + "

Table of Comparison Operators

In the table below, a=3 and b=4.

\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!=If values of two operands are not equal, then condition becomes true.(a != b) is true
>If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's now work through quick examples of each of these.\n", + "\n", + "#### Equal" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 == 2" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1 == 0" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that == is a comparison operator, while = is an assignment operator." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Not Equal" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 != 1" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 != 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Greater Than" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 > 1" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 > 4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Less Than" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 < 4" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 < 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Greater Than or Equal to" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 >= 2" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 >= 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Less than or Equal to" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 <= 2" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 <= 4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Great! Go over each comparison operator to make sure you understand what each one is saying. But hopefully this was straightforward for you.**\n", + "\n", + "Next we will cover chained comparison operators" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/.ipynb_checkpoints/02-Chained Comparison Operators-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/.ipynb_checkpoints/02-Chained Comparison Operators-checkpoint.ipynb new file mode 100644 index 0000000..7a567d9 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/.ipynb_checkpoints/02-Chained Comparison Operators-checkpoint.ipynb @@ -0,0 +1,202 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Chained Comparison Operators\n", + "\n", + "An interesting feature of Python is the ability to *chain* multiple comparisons to perform a more complex test. You can use these chained comparisons as shorthand for larger Boolean Expressions.\n", + "\n", + "In this lecture we will learn how to chain comparison operators and we will also introduce two other important statements in Python: **and** and **or**.\n", + "\n", + "Let's look at a few examples of using chains:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1 < 2 < 3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The above statement checks if 1 was less than 2 **and** if 2 was less than 3. We could have written this using an **and** statement in Python:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1<2 and 2<3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The **and** is used to make sure two checks have to be true in order for the total check to be true. Let's see another example:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1 < 3 > 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The above checks if 3 is larger than both of the other numbers, so you could use **and** to rewrite it as:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1<3 and 3>2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It's important to note that Python is checking both instances of the comparisons. We can also use **or** to write comparisons in Python. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1==2 or 2<3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how it was true; this is because with the **or** operator, we only need one *or* the other to be true. Let's see one more example to drive this home:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1==1 or 100==1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! For an overview of this quick lesson: You should have a comfortable understanding of using **and** and **or** statements as well as reading chained comparison code.\n", + "\n", + "Go ahead and go to the quiz for this section to check your understanding!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/01-Comparison Operators.ipynb b/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/01-Comparison Operators.ipynb new file mode 100644 index 0000000..d14ff8c --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/01-Comparison Operators.ipynb @@ -0,0 +1,376 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Comparison Operators \n", + "\n", + "In this lecture we will be learning about Comparison Operators in Python. These operators will allow us to compare variables and output a Boolean value (True or False). \n", + "\n", + "If you have any sort of background in Math, these operators should be very straight forward.\n", + "\n", + "First we'll present a table of the comparison operators and then work through some examples:\n", + "\n", + "

Table of Comparison Operators

In the table below, a=3 and b=4.

\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "\n", + "
OperatorDescriptionExample
==If the values of two operands are equal, then the condition becomes true. (a == b) is not true.
!=If values of two operands are not equal, then condition becomes true.(a != b) is true
>If the value of left operand is greater than the value of right operand, then condition becomes true. (a > b) is not true.
<If the value of left operand is less than the value of right operand, then condition becomes true. (a < b) is true.
>=If the value of left operand is greater than or equal to the value of right operand, then condition becomes true. (a >= b) is not true.
<=If the value of left operand is less than or equal to the value of right operand, then condition becomes true. (a <= b) is true.
" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's now work through quick examples of each of these.\n", + "\n", + "#### Equal" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 == 2" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1 == 0" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that == is a comparison operator, while = is an assignment operator." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Not Equal" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 != 1" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 != 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Greater Than" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 > 1" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 > 4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Less Than" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 < 4" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 < 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Greater Than or Equal to" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 >= 2" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 >= 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Less than or Equal to" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 <= 2" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "2 <= 4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Great! Go over each comparison operator to make sure you understand what each one is saying. But hopefully this was straightforward for you.**\n", + "\n", + "Next we will cover chained comparison operators" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/02-Chained Comparison Operators.ipynb b/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/02-Chained Comparison Operators.ipynb new file mode 100644 index 0000000..7a567d9 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/01-Python Comparison Operators/02-Chained Comparison Operators.ipynb @@ -0,0 +1,202 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Chained Comparison Operators\n", + "\n", + "An interesting feature of Python is the ability to *chain* multiple comparisons to perform a more complex test. You can use these chained comparisons as shorthand for larger Boolean Expressions.\n", + "\n", + "In this lecture we will learn how to chain comparison operators and we will also introduce two other important statements in Python: **and** and **or**.\n", + "\n", + "Let's look at a few examples of using chains:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1 < 2 < 3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The above statement checks if 1 was less than 2 **and** if 2 was less than 3. We could have written this using an **and** statement in Python:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1<2 and 2<3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The **and** is used to make sure two checks have to be true in order for the total check to be true. Let's see another example:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1 < 3 > 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The above checks if 3 is larger than both of the other numbers, so you could use **and** to rewrite it as:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1<3 and 3>2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It's important to note that Python is checking both instances of the comparisons. We can also use **or** to write comparisons in Python. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1==2 or 2<3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how it was true; this is because with the **or** operator, we only need one *or* the other to be true. Let's see one more example to drive this home:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "1==1 or 100==1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! For an overview of this quick lesson: You should have a comfortable understanding of using **and** and **or** statements as well as reading chained comparison code.\n", + "\n", + "Go ahead and go to the quiz for this section to check your understanding!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/01-Introduction to Python Statements-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/01-Introduction to Python Statements-checkpoint.ipynb new file mode 100644 index 0000000..4de998b --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/01-Introduction to Python Statements-checkpoint.ipynb @@ -0,0 +1,125 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Introduction to Python Statements\n", + "\n", + "In this lecture we will be doing a quick overview of Python Statements. This lecture will emphasize differences between Python and other languages such as C++. \n", + "\n", + "There are two reasons we take this approach for learning the context of Python Statements:\n", + "\n", + " 1.) If you are coming from a different language this will rapidly accelerate your understanding of Python.\n", + " 2.) Learning about statements will allow you to be able to read other languages more easily in the future." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "## Python vs Other Languages\n", + "\n", + "Let's create a simple statement that says:\n", + "\"If a is greater than b, assign 2 to a and 4 to b\"\n", + "\n", + "Take a look at these two if statements (we will learn about building out if statements soon).\n", + "\n", + "**Version 1 (Other Languages)**\n", + "\n", + " if (a>b){\n", + " a = 2;\n", + " b = 4;\n", + " }\n", + " \n", + "**Version 2 (Python)** \n", + "\n", + " if a>b:\n", + " a = 2\n", + " b = 4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You'll notice that Python is less cluttered and much more readable than the first version. How does Python manage this?\n", + "\n", + "Let's walk through the main differences:\n", + "\n", + "Python gets rid of () and {} by incorporating two main factors: a *colon* and *whitespace*. The statement is ended with a colon, and whitespace is used (indentation) to describe what takes place in case of the statement.\n", + "\n", + "Another major difference is the lack of semicolons in Python. Semicolons are used to denote statement endings in many other languages, but in Python, the end of a line is the same as the end of a statement.\n", + "\n", + "Lastly, to end this brief overview of differences, let's take a closer look at indentation syntax in Python vs other languages:\n", + "\n", + "## Indentation\n", + "\n", + "Here is some pseudo-code to indicate the use of whitespace and indentation in Python:\n", + "\n", + "**Other Languages**\n", + "\n", + " if (x)\n", + " if(y)\n", + " code-statement;\n", + " else\n", + " another-code-statement;\n", + " \n", + "**Python**\n", + " \n", + " if x:\n", + " if y:\n", + " code-statement\n", + " else:\n", + " another-code-statement" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how Python is so heavily driven by code indentation and whitespace. This means that code readability is a core part of the design of the Python language.\n", + "\n", + "Now let's start diving deeper by coding these sort of statements in Python!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Time to code!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/02-if, elif, and else Statements-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/02-if, elif, and else Statements-checkpoint.ipynb new file mode 100644 index 0000000..262bd64 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/02-if, elif, and else Statements-checkpoint.ipynb @@ -0,0 +1,208 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# if, elif, else Statements\n", + "\n", + "if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results.\n", + "\n", + "Verbally, we can imagine we are telling the computer:\n", + "\n", + "\"Hey if this case happens, perform some action\"\n", + "\n", + "We can then expand the idea further with elif and else statements, which allow us to tell the computer:\n", + "\n", + "\"Hey if this case happens, perform some action. Else, if another case happens, perform some other action. Else, if *none* of the above cases happened, perform this action.\"\n", + "\n", + "Let's go ahead and look at the syntax format for if statements to get a better idea of this:\n", + "\n", + " if case1:\n", + " perform action1\n", + " elif case2:\n", + " perform action2\n", + " else: \n", + " perform action3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## First Example\n", + "\n", + "Let's see a quick example of this:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "It was true!\n" + ] + } + ], + "source": [ + "if True:\n", + " print('It was true!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's add in some else logic:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I will be printed in any case where x is not true\n" + ] + } + ], + "source": [ + "x = False\n", + "\n", + "if x:\n", + " print('x was True!')\n", + "else:\n", + " print('I will be printed in any case where x is not true')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Multiple Branches\n", + "\n", + "Let's get a fuller picture of how far if, elif, and else can take us!\n", + "\n", + "We write this out in a nested structure. Take note of how the if, elif, and else line up in the code. This can help you see what if is related to what elif or else statements.\n", + "\n", + "We'll reintroduce a comparison syntax for Python." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to the bank!\n" + ] + } + ], + "source": [ + "loc = 'Bank'\n", + "\n", + "if loc == 'Auto Shop':\n", + " print('Welcome to the Auto Shop!')\n", + "elif loc == 'Bank':\n", + " print('Welcome to the bank!')\n", + "else:\n", + " print('Where are you?')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how the nested if statements are each checked until a True boolean causes the nested code below it to run. You should also note that you can put in as many elif statements as you want before you close off with an else.\n", + "\n", + "Let's create two more simple examples for the if, elif, and else statements:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome Sammy!\n" + ] + } + ], + "source": [ + "person = 'Sammy'\n", + "\n", + "if person == 'Sammy':\n", + " print('Welcome Sammy!')\n", + "else:\n", + " print(\"Welcome, what's your name?\")" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome George!\n" + ] + } + ], + "source": [ + "person = 'George'\n", + "\n", + "if person == 'Sammy':\n", + " print('Welcome Sammy!')\n", + "elif person =='George':\n", + " print('Welcome George!')\n", + "else:\n", + " print(\"Welcome, what's your name?\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Indentation\n", + "\n", + "It is important to keep a good understanding of how indentation works in Python to maintain the structure and order of your code. We will touch on this topic again when we start building out functions!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/03-for Loops-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/03-for Loops-checkpoint.ipynb new file mode 100644 index 0000000..61f54fe --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/03-for Loops-checkpoint.ipynb @@ -0,0 +1,627 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# for Loops\n", + "\n", + "A for loop acts as an iterator in Python; it goes through items that are in a *sequence* or any other iterable item. Objects that we've learned about that we can iterate over include strings, lists, tuples, and even built-in iterables for dictionaries, such as keys or values.\n", + "\n", + "We've already seen the for statement a little bit in past lectures but now let's formalize our understanding.\n", + "\n", + "Here's the general format for a for loop in Python:\n", + "\n", + " for item in object:\n", + " statements to do stuff\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The variable name used for the item is completely up to the coder, so use your best judgment for choosing a name that makes sense and you will be able to understand when revisiting your code. This item name can then be referenced inside your loop, for example if you wanted to use if statements to perform checks.\n", + "\n", + "Let's go ahead and work through several example of for loops using a variety of data object types. We'll start simple and build more complexity later on.\n", + "\n", + "## Example 1\n", + "Iterating through a list" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# We'll learn how to automate this sort of list in the next lecture\n", + "list1 = [1,2,3,4,5,6,7,8,9,10]" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "10\n" + ] + } + ], + "source": [ + "for num in list1:\n", + " print(num)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Hopefully this makes sense. Now let's add an if statement to check for even numbers. We'll first introduce a new concept here--the modulo.\n", + "### Modulo\n", + "The modulo allows us to get the remainder in a division and uses the % symbol. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "17 % 5" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This makes sense since 17 divided by 5 is 3 remainder 2. Let's see a few more quick examples:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 3 Remainder 1\n", + "10 % 3" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 2 Remainder 4\n", + "18 % 7" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 2 no remainder\n", + "4 % 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice that if a number is fully divisible with no remainder, the result of the modulo call is 0. We can use this to test for even numbers, since if a number modulo 2 is equal to 0, that means it is an even number!\n", + "\n", + "Back to the for loops!\n", + "\n", + "## Example 2\n", + "Let's print only the even numbers from that list!" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "4\n", + "6\n", + "8\n", + "10\n" + ] + } + ], + "source": [ + "for num in list1:\n", + " if num % 2 == 0:\n", + " print(num)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We could have also put an else statement in there:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Odd number\n", + "2\n", + "Odd number\n", + "4\n", + "Odd number\n", + "6\n", + "Odd number\n", + "8\n", + "Odd number\n", + "10\n" + ] + } + ], + "source": [ + "for num in list1:\n", + " if num % 2 == 0:\n", + " print(num)\n", + " else:\n", + " print('Odd number')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 3\n", + "Another common idea during a for loop is keeping some sort of running tally during multiple loops. For example, let's create a for loop that sums up the list:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "55\n" + ] + } + ], + "source": [ + "# Start sum at zero\n", + "list_sum = 0 \n", + "\n", + "for num in list1:\n", + " list_sum = list_sum + num\n", + "\n", + "print(list_sum)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Read over the above cell and make sure you understand fully what is going on. Also we could have implemented a += to perform the addition towards the sum. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "55\n" + ] + } + ], + "source": [ + "# Start sum at zero\n", + "list_sum = 0 \n", + "\n", + "for num in list1:\n", + " list_sum += num\n", + "\n", + "print(list_sum)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 4\n", + "We've used for loops with lists, how about with strings? Remember strings are a sequence so when we iterate through them we will be accessing each item in that string." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "T\n", + "h\n", + "i\n", + "s\n", + " \n", + "i\n", + "s\n", + " \n", + "a\n", + " \n", + "s\n", + "t\n", + "r\n", + "i\n", + "n\n", + "g\n", + ".\n" + ] + } + ], + "source": [ + "for letter in 'This is a string.':\n", + " print(letter)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 5\n", + "Let's now look at how a for loop can be used with a tuple:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n" + ] + } + ], + "source": [ + "tup = (1,2,3,4,5)\n", + "\n", + "for t in tup:\n", + " print(t)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 6\n", + "Tuples have a special quality when it comes to for loops. If you are iterating through a sequence that contains tuples, the item can actually be the tuple itself, this is an example of *tuple unpacking*. During the for loop we will be unpacking the tuple inside of a sequence and we can access the individual items inside that tuple!" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "list2 = [(2,4),(6,8),(10,12)]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(2, 4)\n", + "(6, 8)\n", + "(10, 12)\n" + ] + } + ], + "source": [ + "for tup in list2:\n", + " print(tup)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "6\n", + "10\n" + ] + } + ], + "source": [ + "# Now with unpacking!\n", + "for (t1,t2) in list2:\n", + " print(t1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Cool! With tuples in a sequence we can access the items inside of them through unpacking! The reason this is important is because many objects will deliver their iterables through tuples. Let's start exploring iterating through Dictionaries to explore this further!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 7" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "d = {'k1':1,'k2':2,'k3':3}" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "k1\n", + "k2\n", + "k3\n" + ] + } + ], + "source": [ + "for item in d:\n", + " print(item)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how this produces only the keys. So how can we get the values? Or both the keys and the values? \n", + "\n", + "We're going to introduce three new Dictionary methods: **.keys()**, **.values()** and **.items()**\n", + "\n", + "In Python each of these methods return a *dictionary view object*. It supports operations like membership test and iteration, but its contents are not independent of the original dictionary – it is only a view. Let's see it in action:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_items([('k1', 1), ('k2', 2), ('k3', 3)])" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Create a dictionary view object\n", + "d.items()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since the .items() method supports iteration, we can perform *dictionary unpacking* to separate keys and values just as we did in the previous examples." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "k1\n", + "1\n", + "k2\n", + "2\n", + "k3\n", + "3\n" + ] + } + ], + "source": [ + "# Dictionary unpacking\n", + "for k,v in d.items():\n", + " print(k)\n", + " print(v) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you want to obtain a true list of keys, values, or key/value tuples, you can *cast* the view as a list:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['k1', 'k2', 'k3']" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(d.keys())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Remember that dictionaries are unordered, and that keys and values come back in arbitrary order. You can obtain a sorted list using sorted():" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3]" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sorted(d.values())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Conclusion\n", + "\n", + "We've learned how to use for loops to iterate through tuples, lists, strings, and dictionaries. It will be an important tool for us, so make sure you know it well and understood the above examples.\n", + "\n", + "[More resources](http://www.tutorialspoint.com/python/python_for_loop.htm)" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/04-while Loops-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/04-while Loops-checkpoint.ipynb new file mode 100644 index 0000000..f8ff559 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/04-while Loops-checkpoint.ipynb @@ -0,0 +1,296 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# while Loops\n", + "\n", + "The while statement in Python is one of most general ways to perform iteration. A while statement will repeatedly execute a single statement or group of statements as long as the condition is true. The reason it is called a 'loop' is because the code statements are looped through over and over again until the condition is no longer met.\n", + "\n", + "The general format of a while loop is:\n", + "\n", + " while test:\n", + " code statements\n", + " else:\n", + " final code statements\n", + "\n", + "Let’s look at a few simple while loops in action. " + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is currently: 0\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 1\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 2\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 3\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 4\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 5\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 6\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 7\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 8\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 9\n", + " x is still less than 10, adding 1 to x\n" + ] + } + ], + "source": [ + "x = 0\n", + "\n", + "while x < 10:\n", + " print('x is currently: ',x)\n", + " print(' x is still less than 10, adding 1 to x')\n", + " x+=1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how many times the print statements occurred and how the while loop kept going until the True condition was met, which occurred once x==10. It's important to note that once this occurred the code stopped. Let's see how we could add an else statement:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is currently: 0\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 1\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 2\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 3\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 4\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 5\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 6\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 7\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 8\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 9\n", + " x is still less than 10, adding 1 to x\n", + "All Done!\n" + ] + } + ], + "source": [ + "x = 0\n", + "\n", + "while x < 10:\n", + " print('x is currently: ',x)\n", + " print(' x is still less than 10, adding 1 to x')\n", + " x+=1\n", + " \n", + "else:\n", + " print('All Done!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# break, continue, pass\n", + "\n", + "We can use break, continue, and pass statements in our loops to add additional functionality for various cases. The three statements are defined by:\n", + "\n", + " break: Breaks out of the current closest enclosing loop.\n", + " continue: Goes to the top of the closest enclosing loop.\n", + " pass: Does nothing at all.\n", + " \n", + " \n", + "Thinking about break and continue statements, the general format of the while loop looks like this:\n", + "\n", + " while test: \n", + " code statement\n", + " if test: \n", + " break\n", + " if test: \n", + " continue \n", + " else:\n", + "\n", + "break and continue statements can appear anywhere inside the loop’s body, but we will usually put them further nested in conjunction with an if statement to perform an action based on some condition.\n", + "\n", + "Let's go ahead and look at some examples!" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is currently: 0\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 1\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 2\n", + " x is still less than 10, adding 1 to x\n", + "x==3\n", + "x is currently: 3\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 4\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 5\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 6\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 7\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 8\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 9\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n" + ] + } + ], + "source": [ + "x = 0\n", + "\n", + "while x < 10:\n", + " print('x is currently: ',x)\n", + " print(' x is still less than 10, adding 1 to x')\n", + " x+=1\n", + " if x==3:\n", + " print('x==3')\n", + " else:\n", + " print('continuing...')\n", + " continue" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how we have a printed statement when x==3, and a continue being printed out as we continue through the outer while loop. Let's put in a break once x ==3 and see if the result makes sense:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is currently: 0\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 1\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 2\n", + " x is still less than 10, adding 1 to x\n", + "Breaking because x==3\n" + ] + } + ], + "source": [ + "x = 0\n", + "\n", + "while x < 10:\n", + " print('x is currently: ',x)\n", + " print(' x is still less than 10, adding 1 to x')\n", + " x+=1\n", + " if x==3:\n", + " print('Breaking because x==3')\n", + " break\n", + " else:\n", + " print('continuing...')\n", + " continue" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how the other else statement wasn't reached and continuing was never printed!\n", + "\n", + "After these brief but simple examples, you should feel comfortable using while statements in your code.\n", + "\n", + "**A word of caution however! It is possible to create an infinitely running loop with while statements. For example:**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# DO NOT RUN THIS CODE!!!! \n", + "while True:\n", + " print(\"I'm stuck in an infinite loop!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "A quick note: If you *did* run the above cell, click on the Kernel menu above to restart the kernel!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/05-Useful-Operators-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/05-Useful-Operators-checkpoint.ipynb new file mode 100644 index 0000000..632406a --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/05-Useful-Operators-checkpoint.ipynb @@ -0,0 +1,587 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Useful Operators\n", + "\n", + "There are a few built-in functions and \"operators\" in Python that don't fit well into any category, so we will go over them in this lecture, let's begin!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## range\n", + "\n", + "The range function allows you to quickly *generate* a list of integers, this comes in handy a lot, so take note of how to use it! There are 3 parameters you can pass, a start, a stop, and a step size. Let's see some examples:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "range(0, 11)" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "range(0,11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that this is a **generator** function, so to actually get a list out of it, we need to cast it to a list with **list()**. What is a generator? Its a special type of function that will generate information and not need to save it to memory. We haven't talked about functions or generators yet, so just keep this in your notes for now, we will discuss this in much more detail in later on in your training!" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Notice how 11 is not included, up to but not including 11, just like slice notation!\n", + "list(range(0,11))" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(range(0,12))" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Third parameter is step size!\n", + "# step size just means how big of a jump/leap/step you \n", + "# take from the starting number to get to the next number.\n", + "\n", + "list(range(0,11,2))" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(range(0,101,10))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## enumerate\n", + "\n", + "enumerate is a very useful function to use with for loops. Let's imagine the following situation:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "At index 0 the letter is a\n", + "At index 1 the letter is b\n", + "At index 2 the letter is c\n", + "At index 3 the letter is d\n", + "At index 4 the letter is e\n" + ] + } + ], + "source": [ + "index_count = 0\n", + "\n", + "for letter in 'abcde':\n", + " print(\"At index {} the letter is {}\".format(index_count,letter))\n", + " index_count += 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Keeping track of how many loops you've gone through is so common, that enumerate was created so you don't need to worry about creating and updating this index_count or loop_count variable" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "At index 0 the letter is a\n", + "At index 1 the letter is b\n", + "At index 2 the letter is c\n", + "At index 3 the letter is d\n", + "At index 4 the letter is e\n" + ] + } + ], + "source": [ + "# Notice the tuple unpacking!\n", + "\n", + "for i,letter in enumerate('abcde'):\n", + " print(\"At index {} the letter is {}\".format(i,letter))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## zip\n", + "\n", + "Notice the format enumerate actually returns, let's take a look by transforming it to a list()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(enumerate('abcde'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It was a list of tuples, meaning we could use tuple unpacking during our for loop. This data structure is actually very common in Python , especially when working with outside libraries. You can use the **zip()** function to quickly create a list of tuples by \"zipping\" up together two lists." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "mylist1 = [1,2,3,4,5]\n", + "mylist2 = ['a','b','c','d','e']" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# This one is also a generator! We will explain this later, but for now let's transform it to a list\n", + "zip(mylist1,mylist2)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(zip(mylist1,mylist2))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To use the generator, we could just use a for loop" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "For this tuple, first item was 1 and second item was a\n", + "For this tuple, first item was 2 and second item was b\n", + "For this tuple, first item was 3 and second item was c\n", + "For this tuple, first item was 4 and second item was d\n", + "For this tuple, first item was 5 and second item was e\n" + ] + } + ], + "source": [ + "for item1, item2 in zip(mylist1,mylist2):\n", + " print('For this tuple, first item was {} and second item was {}'.format(item1,item2))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## in operator\n", + "\n", + "We've already seen the **in** keyword durng the for loop, but we can also use it to quickly check if an object is in a list" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'x' in ['x','y','z']" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'x' in [1,2,3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## min and max\n", + "\n", + "Quickly check the minimum or maximum of a list with these functions." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "mylist = [10,20,30,40,100]" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "min(mylist)" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "max(mylist)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## random\n", + "\n", + "Python comes with a built in random library. There are a lot of functions included in this random library, so we will only show you two useful functions for now." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from random import shuffle" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# This shuffles the list \"in-place\" meaning it won't return\n", + "# anything, instead it will effect the list passed\n", + "shuffle(mylist)" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[40, 10, 100, 30, 20]" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "mylist" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from random import randint" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Return random integer in range [a, b], including both end points.\n", + "randint(0,100)" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "91" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Return random integer in range [a, b], including both end points.\n", + "randint(0,100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## input" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter Something into this box: great job!\n" + ] + }, + { + "data": { + "text/plain": [ + "'great job!'" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "input('Enter Something into this box: ')" + ] + } + ], + "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.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/05-range()-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/05-range()-checkpoint.ipynb new file mode 100644 index 0000000..e9c64e0 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/05-range()-checkpoint.ipynb @@ -0,0 +1,162 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# range()\n", + "\n", + "In this short lecture we will be discussing the range function. We haven't developed a very deep level of knowledge of functions yet, but we can understand the basics of this simple (but extremely useful!) function.\n", + "\n", + "range() allows us to generate a list of numbers ranging from a starting point *up to but not including* an ending point. We can also specify step size. Let's walk through a few examples:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(range(0,10))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To see the output of range() as a list, we *cast* it as a list as shown above. This is rarely done, as normally range is used in for loops." + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "range" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Range objects\n", + "x =range(0,10)\n", + "type(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "range objects behave like *generators* - they don't produce every value all at once, but deliver them one at a time as needed. Behind the scenes this saves on overhead since you're not storing every value, and it improves the performance of your code! We will learn more about generators later on in the course." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "start = 0 #Default\n", + "stop = 20 \n", + "x = range(start,stop)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Notice how it went *up to* 20, but doesn't actually produce 20. Just like in indexing. What about step size? We can specify that as a third argument:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "x = range(start,stop,2)\n", + "\n", + "#Show\n", + "list(x)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "You should now have a good understanding of how to use range() in Python." + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/06-List Comprehensions-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/06-List Comprehensions-checkpoint.ipynb new file mode 100644 index 0000000..256271b --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/06-List Comprehensions-checkpoint.ipynb @@ -0,0 +1,217 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# List Comprehensions\n", + "\n", + "In addition to sequence operations and list methods, Python includes a more advanced operation called a list comprehension.\n", + "\n", + "List comprehensions allow us to build out lists using a different notation. You can think of it as essentially a one line for loop built inside of brackets. For a simple example:\n", + "## Example 1" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Grab every letter in string\n", + "lst = [x for x in 'word']" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['w', 'o', 'r', 'd']" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the basic idea of a list comprehension. If you're familiar with mathematical notation this format should feel familiar for example: x^2 : x in { 0,1,2...10 } \n", + "\n", + "Let's see a few more examples of list comprehensions in Python:\n", + "## Example 2" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "# Square numbers in range and turn into list\n", + "lst = [x**2 for x in range(0,11)]" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 3\n", + "Let's see how to add in if statements:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "# Check for even numbers in a range\n", + "lst = [x for x in range(11) if x % 2 == 0]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 4\n", + "Can also do more complicated arithmetic:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[32.0, 50.0, 68.18, 94.1]" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Convert Celsius to Fahrenheit\n", + "celsius = [0,10,20.1,34.5]\n", + "\n", + "fahrenheit = [((9/5)*temp + 32) for temp in celsius ]\n", + "\n", + "fahrenheit" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 5\n", + "We can also perform nested list comprehensions, for example:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst = [ x**2 for x in [x**2 for x in range(11)]]\n", + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Later on in the course we will learn about generator comprehensions. After this lecture you should feel comfortable reading and writing basic list comprehensions." + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/07-Statements Assessment Test-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/07-Statements Assessment Test-checkpoint.ipynb new file mode 100644 index 0000000..4d9ee29 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/07-Statements Assessment Test-checkpoint.ipynb @@ -0,0 +1,193 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Statements Assessment Test\n", + "Let's test your knowledge!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "_____\n", + "**Use for, .split(), and if to create a Statement that will print out words that start with 's':**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "st = 'Print only the words that start with s in this sentence'" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "#Code here" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "______\n", + "**Use range() to print all the even numbers from 0 to 10.**" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "#Code Here" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "___\n", + "**Use a List Comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[]" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Code in this cell\n", + "[]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "_____\n", + "**Go through the string below and if the length of a word is even print \"even!\"**" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "st = 'Print every word in this sentence that has an even number of letters'" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "#Code in this cell" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a program that prints the integers from 1 to 100. But for multiples of three print \"Fizz\" instead of the number, and for the multiples of five print \"Buzz\". For numbers which are multiples of both three and five print \"FizzBuzz\".**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#Code in this cell" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Use List Comprehension to create a list of the first letters of every word in the string below:**" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "st = 'Create a list of the first letters of every word in this string'" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "#Code in this cell" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/08-Statements Assessment Test - Solutions-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/08-Statements Assessment Test - Solutions-checkpoint.ipynb new file mode 100644 index 0000000..bf90566 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/08-Statements Assessment Test - Solutions-checkpoint.ipynb @@ -0,0 +1,241 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Statements Assessment Solutions" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "_____\n", + "**Use for, .split(), and if to create a Statement that will print out words that start with 's':**" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "st = 'Print only the words that start with s in this sentence'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "start\n", + "s\n", + "sentence\n" + ] + } + ], + "source": [ + "for word in st.split():\n", + " if word[0] == 's':\n", + " print(word)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "______\n", + "**Use range() to print all the even numbers from 0 to 10.**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(range(0,11,2))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "___\n", + "**Use List comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.**" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[x for x in range(1,51) if x%3 == 0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "_____\n", + "**Go through the string below and if the length of a word is even print \"even!\"**" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "st = 'Print every word in this sentence that has an even number of letters'" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "word <-- has an even length!\n", + "in <-- has an even length!\n", + "this <-- has an even length!\n", + "sentence <-- has an even length!\n", + "that <-- has an even length!\n", + "an <-- has an even length!\n", + "even <-- has an even length!\n", + "number <-- has an even length!\n", + "of <-- has an even length!\n" + ] + } + ], + "source": [ + "for word in st.split():\n", + " if len(word)%2 == 0:\n", + " print(word+\" <-- has an even length!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a program that prints the integers from 1 to 100. But for multiples of three print \"Fizz\" instead of the number, and for the multiples of five print \"Buzz\". For numbers which are multiples of both three and five print \"FizzBuzz\".**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for num in range(1,101):\n", + " if num % 3 == 0 and num % 5 == 0:\n", + " print(\"FizzBuzz\")\n", + " elif num % 3 == 0:\n", + " print(\"Fizz\")\n", + " elif num % 5 == 0:\n", + " print(\"Buzz\")\n", + " else:\n", + " print(num)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Use a List Comprehension to create a list of the first letters of every word in the string below:**" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "st = 'Create a list of the first letters of every word in this string'" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['C', 'a', 'l', 'o', 't', 'f', 'l', 'o', 'e', 'w', 'i', 't', 's']" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[word[0] for word in st.split()]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/09-Guessing Game Challenge-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/09-Guessing Game Challenge-checkpoint.ipynb new file mode 100644 index 0000000..97f6fb7 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/09-Guessing Game Challenge-checkpoint.ipynb @@ -0,0 +1,154 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Guessing Game Challenge\n", + "\n", + "Let's use `while` loops to create a guessing game.\n", + "\n", + "The Challenge:\n", + "\n", + "Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are:\n", + "\n", + "1. If a player's guess is less than 1 or greater than 100, say \"OUT OF BOUNDS\"\n", + "2. On a player's first turn, if their guess is\n", + " * within 10 of the number, return \"WARM!\"\n", + " * further than 10 away from the number, return \"COLD!\"\n", + "3. On all subsequent turns, if a guess is \n", + " * closer to the number than the previous guess return \"WARMER!\"\n", + " * farther from the number than the previous guess, return \"COLDER!\"\n", + "4. When the player's guess equals the number, tell them they've guessed correctly *and* how many guesses it took!\n", + "\n", + "You can try this from scratch, or follow the steps outlined below. A separate Solution notebook has been provided. Good luck!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### First, pick a random integer from 1 to 100 using the random module and assign it to a variable\n", + "\n", + "Note: `random.randint(a,b)` returns a random integer in range `[a, b]`, including both end points." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Next, print an introduction to the game and explain the rules" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Create a list to store guesses\n", + "\n", + "Hint: zero is a good placeholder value. It's useful because it evaluates to \"False\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Write a `while` loop that asks for a valid guess. Test it a few times to make sure it works." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "while True:\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Write a `while` loop that compares the player's guess to our number. If the player guesses correctly, break from the loop. Otherwise, tell the player if they're warmer or colder, and continue asking for guesses.\n", + "\n", + "Some hints:\n", + "* it may help to sketch out all possible combinations on paper first!\n", + "* you can use the `abs()` function to find the positive difference between two numbers\n", + "* if you append all new guesses to the list, then the previous guess is given as `guesses[-2]`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "while True:\n", + "\n", + " # we can copy the code from above to take an input\n", + "\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That's it! You've just programmed your first game!\n", + "\n", + "In the next section we'll learn how to turn some of these repetitive actions into *functions* that can be called whenever we need them." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Good Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/10-Guessing Game Challenge - Solution-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/10-Guessing Game Challenge - Solution-checkpoint.ipynb new file mode 100644 index 0000000..3df229e --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/.ipynb_checkpoints/10-Guessing Game Challenge - Solution-checkpoint.ipynb @@ -0,0 +1,258 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Guessing Game Challenge - Solution\n", + "\n", + "Let's use `while` loops to create a guessing game.\n", + "\n", + "The Challenge:\n", + "\n", + "Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are:\n", + "\n", + "1. If a player's guess is less than 1 or greater than 100, say \"OUT OF BOUNDS\"\n", + "2. On a player's first turn, if their guess is\n", + " * within 10 of the number, return \"WARM!\"\n", + " * further than 10 away from the number, return \"COLD!\"\n", + "3. On all subsequent turns, if a guess is \n", + " * closer to the number than the previous guess return \"WARMER!\"\n", + " * farther from the number than the previous guess, return \"COLDER!\"\n", + "4. When the player's guess equals the number, tell them they've guessed correctly *and* how many guesses it took!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### First, pick a random integer from 1 to 100 using the random module and assign it to a variable\n", + "\n", + "Note: `random.randint(a,b)` returns a random integer in range `[a, b]`, including both end points." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "num = random.randint(1,100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Next, print an introduction to the game and explain the rules" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "WELCOME TO GUESS ME!\n", + "I'm thinking of a number between 1 and 100\n", + "If your guess is more than 10 away from my number, I'll tell you you're COLD\n", + "If your guess is within 10 of my number, I'll tell you you're WARM\n", + "If your guess is farther than your most recent guess, I'll say you're getting COLDER\n", + "If your guess is closer than your most recent guess, I'll say you're getting WARMER\n", + "LET'S PLAY!\n" + ] + } + ], + "source": [ + "print(\"WELCOME TO GUESS ME!\")\n", + "print(\"I'm thinking of a number between 1 and 100\")\n", + "print(\"If your guess is more than 10 away from my number, I'll tell you you're COLD\")\n", + "print(\"If your guess is within 10 of my number, I'll tell you you're WARM\")\n", + "print(\"If your guess is farther than your most recent guess, I'll say you're getting COLDER\")\n", + "print(\"If your guess is closer than your most recent guess, I'll say you're getting WARMER\")\n", + "print(\"LET'S PLAY!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Create a list to store guesses\n", + "\n", + "Hint: zero is a good placeholder value. It's useful because it evaluates to \"False\"" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "guesses = [0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Write a `while` loop that asks for a valid guess. Test it a few times to make sure it works." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 500\n", + "OUT OF BOUNDS! Please try again: \n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 50\n" + ] + } + ], + "source": [ + "while True:\n", + " \n", + " guess = int(input(\"I'm thinking of a number between 1 and 100.\\n What is your guess? \"))\n", + " \n", + " if guess < 1 or guess > 100:\n", + " print('OUT OF BOUNDS! Please try again: ')\n", + " continue\n", + " \n", + " break" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Write a `while` loop that compares the player's guess to our number. If the player guesses correctly, break from the loop. Otherwise, tell the player if they're warmer or colder, and continue asking for guesses.\n", + "\n", + "Some hints:\n", + "* it may help to sketch out all possible combinations on paper first!\n", + "* you can use the `abs()` function to find the positive difference between two numbers\n", + "* if you append all new guesses to the list, then the previous guess is given as `guesses[-2]`" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 50\n", + "COLD!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 75\n", + "WARMER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 85\n", + "WARMER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 92\n", + "COLDER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 80\n", + "WARMER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 78\n", + "COLDER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 82\n", + "WARMER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 83\n", + "COLDER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 81\n", + "CONGRATULATIONS, YOU GUESSED IT IN ONLY 9 GUESSES!!\n" + ] + } + ], + "source": [ + "while True:\n", + "\n", + " # we can copy the code from above to take an input\n", + " guess = int(input(\"I'm thinking of a number between 1 and 100.\\n What is your guess? \"))\n", + " \n", + " if guess < 1 or guess > 100:\n", + " print('OUT OF BOUNDS! Please try again: ')\n", + " continue\n", + " \n", + " # here we compare the player's guess to our number\n", + " if guess == num:\n", + " print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')\n", + " break\n", + " \n", + " # if guess is incorrect, add guess to the list\n", + " guesses.append(guess)\n", + " \n", + " # when testing the first guess, guesses[-2]==0, which evaluates to False\n", + " # and brings us down to the second section\n", + " \n", + " if guesses[-2]: \n", + " if abs(num-guess) < abs(num-guesses[-2]):\n", + " print('WARMER!')\n", + " else:\n", + " print('COLDER!')\n", + " \n", + " else:\n", + " if abs(num-guess) <= 10:\n", + " print('WARM!')\n", + " else:\n", + " print('COLD!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That's it! You've just programmed your first game!\n", + "\n", + "In the next section we'll learn how to turn some of these repetitive actions into *functions* that can be called whenever we need them." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Good Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/01-Introduction to Python Statements.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/01-Introduction to Python Statements.ipynb new file mode 100644 index 0000000..4de998b --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/01-Introduction to Python Statements.ipynb @@ -0,0 +1,125 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "# Introduction to Python Statements\n", + "\n", + "In this lecture we will be doing a quick overview of Python Statements. This lecture will emphasize differences between Python and other languages such as C++. \n", + "\n", + "There are two reasons we take this approach for learning the context of Python Statements:\n", + "\n", + " 1.) If you are coming from a different language this will rapidly accelerate your understanding of Python.\n", + " 2.) Learning about statements will allow you to be able to read other languages more easily in the future." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "## Python vs Other Languages\n", + "\n", + "Let's create a simple statement that says:\n", + "\"If a is greater than b, assign 2 to a and 4 to b\"\n", + "\n", + "Take a look at these two if statements (we will learn about building out if statements soon).\n", + "\n", + "**Version 1 (Other Languages)**\n", + "\n", + " if (a>b){\n", + " a = 2;\n", + " b = 4;\n", + " }\n", + " \n", + "**Version 2 (Python)** \n", + "\n", + " if a>b:\n", + " a = 2\n", + " b = 4" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You'll notice that Python is less cluttered and much more readable than the first version. How does Python manage this?\n", + "\n", + "Let's walk through the main differences:\n", + "\n", + "Python gets rid of () and {} by incorporating two main factors: a *colon* and *whitespace*. The statement is ended with a colon, and whitespace is used (indentation) to describe what takes place in case of the statement.\n", + "\n", + "Another major difference is the lack of semicolons in Python. Semicolons are used to denote statement endings in many other languages, but in Python, the end of a line is the same as the end of a statement.\n", + "\n", + "Lastly, to end this brief overview of differences, let's take a closer look at indentation syntax in Python vs other languages:\n", + "\n", + "## Indentation\n", + "\n", + "Here is some pseudo-code to indicate the use of whitespace and indentation in Python:\n", + "\n", + "**Other Languages**\n", + "\n", + " if (x)\n", + " if(y)\n", + " code-statement;\n", + " else\n", + " another-code-statement;\n", + " \n", + "**Python**\n", + " \n", + " if x:\n", + " if y:\n", + " code-statement\n", + " else:\n", + " another-code-statement" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how Python is so heavily driven by code indentation and whitespace. This means that code readability is a core part of the design of the Python language.\n", + "\n", + "Now let's start diving deeper by coding these sort of statements in Python!" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Time to code!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/02-if, elif, and else Statements.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/02-if, elif, and else Statements.ipynb new file mode 100644 index 0000000..262bd64 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/02-if, elif, and else Statements.ipynb @@ -0,0 +1,208 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# if, elif, else Statements\n", + "\n", + "if Statements in Python allows us to tell the computer to perform alternative actions based on a certain set of results.\n", + "\n", + "Verbally, we can imagine we are telling the computer:\n", + "\n", + "\"Hey if this case happens, perform some action\"\n", + "\n", + "We can then expand the idea further with elif and else statements, which allow us to tell the computer:\n", + "\n", + "\"Hey if this case happens, perform some action. Else, if another case happens, perform some other action. Else, if *none* of the above cases happened, perform this action.\"\n", + "\n", + "Let's go ahead and look at the syntax format for if statements to get a better idea of this:\n", + "\n", + " if case1:\n", + " perform action1\n", + " elif case2:\n", + " perform action2\n", + " else: \n", + " perform action3" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## First Example\n", + "\n", + "Let's see a quick example of this:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "It was true!\n" + ] + } + ], + "source": [ + "if True:\n", + " print('It was true!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's add in some else logic:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I will be printed in any case where x is not true\n" + ] + } + ], + "source": [ + "x = False\n", + "\n", + "if x:\n", + " print('x was True!')\n", + "else:\n", + " print('I will be printed in any case where x is not true')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Multiple Branches\n", + "\n", + "Let's get a fuller picture of how far if, elif, and else can take us!\n", + "\n", + "We write this out in a nested structure. Take note of how the if, elif, and else line up in the code. This can help you see what if is related to what elif or else statements.\n", + "\n", + "We'll reintroduce a comparison syntax for Python." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to the bank!\n" + ] + } + ], + "source": [ + "loc = 'Bank'\n", + "\n", + "if loc == 'Auto Shop':\n", + " print('Welcome to the Auto Shop!')\n", + "elif loc == 'Bank':\n", + " print('Welcome to the bank!')\n", + "else:\n", + " print('Where are you?')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how the nested if statements are each checked until a True boolean causes the nested code below it to run. You should also note that you can put in as many elif statements as you want before you close off with an else.\n", + "\n", + "Let's create two more simple examples for the if, elif, and else statements:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome Sammy!\n" + ] + } + ], + "source": [ + "person = 'Sammy'\n", + "\n", + "if person == 'Sammy':\n", + " print('Welcome Sammy!')\n", + "else:\n", + " print(\"Welcome, what's your name?\")" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome George!\n" + ] + } + ], + "source": [ + "person = 'George'\n", + "\n", + "if person == 'Sammy':\n", + " print('Welcome Sammy!')\n", + "elif person =='George':\n", + " print('Welcome George!')\n", + "else:\n", + " print(\"Welcome, what's your name?\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Indentation\n", + "\n", + "It is important to keep a good understanding of how indentation works in Python to maintain the structure and order of your code. We will touch on this topic again when we start building out functions!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/03-for Loops.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/03-for Loops.ipynb new file mode 100644 index 0000000..61f54fe --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/03-for Loops.ipynb @@ -0,0 +1,627 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# for Loops\n", + "\n", + "A for loop acts as an iterator in Python; it goes through items that are in a *sequence* or any other iterable item. Objects that we've learned about that we can iterate over include strings, lists, tuples, and even built-in iterables for dictionaries, such as keys or values.\n", + "\n", + "We've already seen the for statement a little bit in past lectures but now let's formalize our understanding.\n", + "\n", + "Here's the general format for a for loop in Python:\n", + "\n", + " for item in object:\n", + " statements to do stuff\n", + " " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The variable name used for the item is completely up to the coder, so use your best judgment for choosing a name that makes sense and you will be able to understand when revisiting your code. This item name can then be referenced inside your loop, for example if you wanted to use if statements to perform checks.\n", + "\n", + "Let's go ahead and work through several example of for loops using a variety of data object types. We'll start simple and build more complexity later on.\n", + "\n", + "## Example 1\n", + "Iterating through a list" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# We'll learn how to automate this sort of list in the next lecture\n", + "list1 = [1,2,3,4,5,6,7,8,9,10]" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n", + "6\n", + "7\n", + "8\n", + "9\n", + "10\n" + ] + } + ], + "source": [ + "for num in list1:\n", + " print(num)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Hopefully this makes sense. Now let's add an if statement to check for even numbers. We'll first introduce a new concept here--the modulo.\n", + "### Modulo\n", + "The modulo allows us to get the remainder in a division and uses the % symbol. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "17 % 5" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This makes sense since 17 divided by 5 is 3 remainder 2. Let's see a few more quick examples:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 3 Remainder 1\n", + "10 % 3" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 2 Remainder 4\n", + "18 % 7" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 2 no remainder\n", + "4 % 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice that if a number is fully divisible with no remainder, the result of the modulo call is 0. We can use this to test for even numbers, since if a number modulo 2 is equal to 0, that means it is an even number!\n", + "\n", + "Back to the for loops!\n", + "\n", + "## Example 2\n", + "Let's print only the even numbers from that list!" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "4\n", + "6\n", + "8\n", + "10\n" + ] + } + ], + "source": [ + "for num in list1:\n", + " if num % 2 == 0:\n", + " print(num)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We could have also put an else statement in there:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Odd number\n", + "2\n", + "Odd number\n", + "4\n", + "Odd number\n", + "6\n", + "Odd number\n", + "8\n", + "Odd number\n", + "10\n" + ] + } + ], + "source": [ + "for num in list1:\n", + " if num % 2 == 0:\n", + " print(num)\n", + " else:\n", + " print('Odd number')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 3\n", + "Another common idea during a for loop is keeping some sort of running tally during multiple loops. For example, let's create a for loop that sums up the list:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "55\n" + ] + } + ], + "source": [ + "# Start sum at zero\n", + "list_sum = 0 \n", + "\n", + "for num in list1:\n", + " list_sum = list_sum + num\n", + "\n", + "print(list_sum)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Read over the above cell and make sure you understand fully what is going on. Also we could have implemented a += to perform the addition towards the sum. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "55\n" + ] + } + ], + "source": [ + "# Start sum at zero\n", + "list_sum = 0 \n", + "\n", + "for num in list1:\n", + " list_sum += num\n", + "\n", + "print(list_sum)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 4\n", + "We've used for loops with lists, how about with strings? Remember strings are a sequence so when we iterate through them we will be accessing each item in that string." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "T\n", + "h\n", + "i\n", + "s\n", + " \n", + "i\n", + "s\n", + " \n", + "a\n", + " \n", + "s\n", + "t\n", + "r\n", + "i\n", + "n\n", + "g\n", + ".\n" + ] + } + ], + "source": [ + "for letter in 'This is a string.':\n", + " print(letter)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 5\n", + "Let's now look at how a for loop can be used with a tuple:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "3\n", + "4\n", + "5\n" + ] + } + ], + "source": [ + "tup = (1,2,3,4,5)\n", + "\n", + "for t in tup:\n", + " print(t)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 6\n", + "Tuples have a special quality when it comes to for loops. If you are iterating through a sequence that contains tuples, the item can actually be the tuple itself, this is an example of *tuple unpacking*. During the for loop we will be unpacking the tuple inside of a sequence and we can access the individual items inside that tuple!" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "list2 = [(2,4),(6,8),(10,12)]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(2, 4)\n", + "(6, 8)\n", + "(10, 12)\n" + ] + } + ], + "source": [ + "for tup in list2:\n", + " print(tup)" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "2\n", + "6\n", + "10\n" + ] + } + ], + "source": [ + "# Now with unpacking!\n", + "for (t1,t2) in list2:\n", + " print(t1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Cool! With tuples in a sequence we can access the items inside of them through unpacking! The reason this is important is because many objects will deliver their iterables through tuples. Let's start exploring iterating through Dictionaries to explore this further!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 7" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "d = {'k1':1,'k2':2,'k3':3}" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "k1\n", + "k2\n", + "k3\n" + ] + } + ], + "source": [ + "for item in d:\n", + " print(item)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how this produces only the keys. So how can we get the values? Or both the keys and the values? \n", + "\n", + "We're going to introduce three new Dictionary methods: **.keys()**, **.values()** and **.items()**\n", + "\n", + "In Python each of these methods return a *dictionary view object*. It supports operations like membership test and iteration, but its contents are not independent of the original dictionary – it is only a view. Let's see it in action:" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "dict_items([('k1', 1), ('k2', 2), ('k3', 3)])" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Create a dictionary view object\n", + "d.items()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Since the .items() method supports iteration, we can perform *dictionary unpacking* to separate keys and values just as we did in the previous examples." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "k1\n", + "1\n", + "k2\n", + "2\n", + "k3\n", + "3\n" + ] + } + ], + "source": [ + "# Dictionary unpacking\n", + "for k,v in d.items():\n", + " print(k)\n", + " print(v) " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you want to obtain a true list of keys, values, or key/value tuples, you can *cast* the view as a list:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['k1', 'k2', 'k3']" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(d.keys())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Remember that dictionaries are unordered, and that keys and values come back in arbitrary order. You can obtain a sorted list using sorted():" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3]" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sorted(d.values())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Conclusion\n", + "\n", + "We've learned how to use for loops to iterate through tuples, lists, strings, and dictionaries. It will be an important tool for us, so make sure you know it well and understood the above examples.\n", + "\n", + "[More resources](http://www.tutorialspoint.com/python/python_for_loop.htm)" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/04-while Loops.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/04-while Loops.ipynb new file mode 100644 index 0000000..f8ff559 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/04-while Loops.ipynb @@ -0,0 +1,296 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# while Loops\n", + "\n", + "The while statement in Python is one of most general ways to perform iteration. A while statement will repeatedly execute a single statement or group of statements as long as the condition is true. The reason it is called a 'loop' is because the code statements are looped through over and over again until the condition is no longer met.\n", + "\n", + "The general format of a while loop is:\n", + "\n", + " while test:\n", + " code statements\n", + " else:\n", + " final code statements\n", + "\n", + "Let’s look at a few simple while loops in action. " + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is currently: 0\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 1\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 2\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 3\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 4\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 5\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 6\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 7\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 8\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 9\n", + " x is still less than 10, adding 1 to x\n" + ] + } + ], + "source": [ + "x = 0\n", + "\n", + "while x < 10:\n", + " print('x is currently: ',x)\n", + " print(' x is still less than 10, adding 1 to x')\n", + " x+=1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how many times the print statements occurred and how the while loop kept going until the True condition was met, which occurred once x==10. It's important to note that once this occurred the code stopped. Let's see how we could add an else statement:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is currently: 0\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 1\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 2\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 3\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 4\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 5\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 6\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 7\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 8\n", + " x is still less than 10, adding 1 to x\n", + "x is currently: 9\n", + " x is still less than 10, adding 1 to x\n", + "All Done!\n" + ] + } + ], + "source": [ + "x = 0\n", + "\n", + "while x < 10:\n", + " print('x is currently: ',x)\n", + " print(' x is still less than 10, adding 1 to x')\n", + " x+=1\n", + " \n", + "else:\n", + " print('All Done!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# break, continue, pass\n", + "\n", + "We can use break, continue, and pass statements in our loops to add additional functionality for various cases. The three statements are defined by:\n", + "\n", + " break: Breaks out of the current closest enclosing loop.\n", + " continue: Goes to the top of the closest enclosing loop.\n", + " pass: Does nothing at all.\n", + " \n", + " \n", + "Thinking about break and continue statements, the general format of the while loop looks like this:\n", + "\n", + " while test: \n", + " code statement\n", + " if test: \n", + " break\n", + " if test: \n", + " continue \n", + " else:\n", + "\n", + "break and continue statements can appear anywhere inside the loop’s body, but we will usually put them further nested in conjunction with an if statement to perform an action based on some condition.\n", + "\n", + "Let's go ahead and look at some examples!" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is currently: 0\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 1\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 2\n", + " x is still less than 10, adding 1 to x\n", + "x==3\n", + "x is currently: 3\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 4\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 5\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 6\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 7\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 8\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 9\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n" + ] + } + ], + "source": [ + "x = 0\n", + "\n", + "while x < 10:\n", + " print('x is currently: ',x)\n", + " print(' x is still less than 10, adding 1 to x')\n", + " x+=1\n", + " if x==3:\n", + " print('x==3')\n", + " else:\n", + " print('continuing...')\n", + " continue" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how we have a printed statement when x==3, and a continue being printed out as we continue through the outer while loop. Let's put in a break once x ==3 and see if the result makes sense:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is currently: 0\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 1\n", + " x is still less than 10, adding 1 to x\n", + "continuing...\n", + "x is currently: 2\n", + " x is still less than 10, adding 1 to x\n", + "Breaking because x==3\n" + ] + } + ], + "source": [ + "x = 0\n", + "\n", + "while x < 10:\n", + " print('x is currently: ',x)\n", + " print(' x is still less than 10, adding 1 to x')\n", + " x+=1\n", + " if x==3:\n", + " print('Breaking because x==3')\n", + " break\n", + " else:\n", + " print('continuing...')\n", + " continue" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how the other else statement wasn't reached and continuing was never printed!\n", + "\n", + "After these brief but simple examples, you should feel comfortable using while statements in your code.\n", + "\n", + "**A word of caution however! It is possible to create an infinitely running loop with while statements. For example:**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# DO NOT RUN THIS CODE!!!! \n", + "while True:\n", + " print(\"I'm stuck in an infinite loop!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "A quick note: If you *did* run the above cell, click on the Kernel menu above to restart the kernel!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/05-Useful-Operators.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/05-Useful-Operators.ipynb new file mode 100644 index 0000000..632406a --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/05-Useful-Operators.ipynb @@ -0,0 +1,587 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Useful Operators\n", + "\n", + "There are a few built-in functions and \"operators\" in Python that don't fit well into any category, so we will go over them in this lecture, let's begin!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## range\n", + "\n", + "The range function allows you to quickly *generate* a list of integers, this comes in handy a lot, so take note of how to use it! There are 3 parameters you can pass, a start, a stop, and a step size. Let's see some examples:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "range(0, 11)" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "range(0,11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that this is a **generator** function, so to actually get a list out of it, we need to cast it to a list with **list()**. What is a generator? Its a special type of function that will generate information and not need to save it to memory. We haven't talked about functions or generators yet, so just keep this in your notes for now, we will discuss this in much more detail in later on in your training!" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Notice how 11 is not included, up to but not including 11, just like slice notation!\n", + "list(range(0,11))" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(range(0,12))" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Third parameter is step size!\n", + "# step size just means how big of a jump/leap/step you \n", + "# take from the starting number to get to the next number.\n", + "\n", + "list(range(0,11,2))" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100]" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(range(0,101,10))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## enumerate\n", + "\n", + "enumerate is a very useful function to use with for loops. Let's imagine the following situation:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "At index 0 the letter is a\n", + "At index 1 the letter is b\n", + "At index 2 the letter is c\n", + "At index 3 the letter is d\n", + "At index 4 the letter is e\n" + ] + } + ], + "source": [ + "index_count = 0\n", + "\n", + "for letter in 'abcde':\n", + " print(\"At index {} the letter is {}\".format(index_count,letter))\n", + " index_count += 1" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Keeping track of how many loops you've gone through is so common, that enumerate was created so you don't need to worry about creating and updating this index_count or loop_count variable" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "At index 0 the letter is a\n", + "At index 1 the letter is b\n", + "At index 2 the letter is c\n", + "At index 3 the letter is d\n", + "At index 4 the letter is e\n" + ] + } + ], + "source": [ + "# Notice the tuple unpacking!\n", + "\n", + "for i,letter in enumerate('abcde'):\n", + " print(\"At index {} the letter is {}\".format(i,letter))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## zip\n", + "\n", + "Notice the format enumerate actually returns, let's take a look by transforming it to a list()" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(0, 'a'), (1, 'b'), (2, 'c'), (3, 'd'), (4, 'e')]" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(enumerate('abcde'))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "It was a list of tuples, meaning we could use tuple unpacking during our for loop. This data structure is actually very common in Python , especially when working with outside libraries. You can use the **zip()** function to quickly create a list of tuples by \"zipping\" up together two lists." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "mylist1 = [1,2,3,4,5]\n", + "mylist2 = ['a','b','c','d','e']" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# This one is also a generator! We will explain this later, but for now let's transform it to a list\n", + "zip(mylist1,mylist2)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[(1, 'a'), (2, 'b'), (3, 'c'), (4, 'd'), (5, 'e')]" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(zip(mylist1,mylist2))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "To use the generator, we could just use a for loop" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "For this tuple, first item was 1 and second item was a\n", + "For this tuple, first item was 2 and second item was b\n", + "For this tuple, first item was 3 and second item was c\n", + "For this tuple, first item was 4 and second item was d\n", + "For this tuple, first item was 5 and second item was e\n" + ] + } + ], + "source": [ + "for item1, item2 in zip(mylist1,mylist2):\n", + " print('For this tuple, first item was {} and second item was {}'.format(item1,item2))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## in operator\n", + "\n", + "We've already seen the **in** keyword durng the for loop, but we can also use it to quickly check if an object is in a list" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'x' in ['x','y','z']" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "'x' in [1,2,3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## min and max\n", + "\n", + "Quickly check the minimum or maximum of a list with these functions." + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "mylist = [10,20,30,40,100]" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "10" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "min(mylist)" + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "max(mylist)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## random\n", + "\n", + "Python comes with a built in random library. There are a lot of functions included in this random library, so we will only show you two useful functions for now." + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from random import shuffle" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# This shuffles the list \"in-place\" meaning it won't return\n", + "# anything, instead it will effect the list passed\n", + "shuffle(mylist)" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[40, 10, 100, 30, 20]" + ] + }, + "execution_count": 36, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "mylist" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from random import randint" + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Return random integer in range [a, b], including both end points.\n", + "randint(0,100)" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "91" + ] + }, + "execution_count": 42, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Return random integer in range [a, b], including both end points.\n", + "randint(0,100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## input" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Enter Something into this box: great job!\n" + ] + }, + { + "data": { + "text/plain": [ + "'great job!'" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "input('Enter Something into this box: ')" + ] + } + ], + "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.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/06-List Comprehensions.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/06-List Comprehensions.ipynb new file mode 100644 index 0000000..256271b --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/06-List Comprehensions.ipynb @@ -0,0 +1,217 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# List Comprehensions\n", + "\n", + "In addition to sequence operations and list methods, Python includes a more advanced operation called a list comprehension.\n", + "\n", + "List comprehensions allow us to build out lists using a different notation. You can think of it as essentially a one line for loop built inside of brackets. For a simple example:\n", + "## Example 1" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Grab every letter in string\n", + "lst = [x for x in 'word']" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['w', 'o', 'r', 'd']" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the basic idea of a list comprehension. If you're familiar with mathematical notation this format should feel familiar for example: x^2 : x in { 0,1,2...10 } \n", + "\n", + "Let's see a few more examples of list comprehensions in Python:\n", + "## Example 2" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "# Square numbers in range and turn into list\n", + "lst = [x**2 for x in range(0,11)]" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 3\n", + "Let's see how to add in if statements:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "# Check for even numbers in a range\n", + "lst = [x for x in range(11) if x % 2 == 0]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 4\n", + "Can also do more complicated arithmetic:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[32.0, 50.0, 68.18, 94.1]" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Convert Celsius to Fahrenheit\n", + "celsius = [0,10,20.1,34.5]\n", + "\n", + "fahrenheit = [((9/5)*temp + 32) for temp in celsius ]\n", + "\n", + "fahrenheit" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 5\n", + "We can also perform nested list comprehensions, for example:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 1, 16, 81, 256, 625, 1296, 2401, 4096, 6561, 10000]" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst = [ x**2 for x in [x**2 for x in range(11)]]\n", + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Later on in the course we will learn about generator comprehensions. After this lecture you should feel comfortable reading and writing basic list comprehensions." + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/07-Statements Assessment Test.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/07-Statements Assessment Test.ipynb new file mode 100644 index 0000000..b9e5454 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/07-Statements Assessment Test.ipynb @@ -0,0 +1,172 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Statements Assessment Test\n", + "Let's test your knowledge!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "_____\n", + "**Use for, .split(), and if to create a Statement that will print out words that start with 's':**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = 'Print only the words that start with s in this sentence'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#Code here" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "______\n", + "**Use range() to print all the even numbers from 0 to 10.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#Code Here" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "___\n", + "**Use a List Comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#Code in this cell\n", + "[]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "_____\n", + "**Go through the string below and if the length of a word is even print \"even!\"**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = 'Print every word in this sentence that has an even number of letters'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#Code in this cell" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a program that prints the integers from 1 to 100. But for multiples of three print \"Fizz\" instead of the number, and for the multiples of five print \"Buzz\". For numbers which are multiples of both three and five print \"FizzBuzz\".**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#Code in this cell" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Use List Comprehension to create a list of the first letters of every word in the string below:**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "st = 'Create a list of the first letters of every word in this string'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "#Code in this cell" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/08-Statements Assessment Test - Solutions.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/08-Statements Assessment Test - Solutions.ipynb new file mode 100644 index 0000000..bf90566 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/08-Statements Assessment Test - Solutions.ipynb @@ -0,0 +1,241 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Statements Assessment Solutions" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "_____\n", + "**Use for, .split(), and if to create a Statement that will print out words that start with 's':**" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "st = 'Print only the words that start with s in this sentence'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "start\n", + "s\n", + "sentence\n" + ] + } + ], + "source": [ + "for word in st.split():\n", + " if word[0] == 's':\n", + " print(word)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "______\n", + "**Use range() to print all the even numbers from 0 to 10.**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(range(0,11,2))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "___\n", + "**Use List comprehension to create a list of all numbers between 1 and 50 that are divisible by 3.**" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36, 39, 42, 45, 48]" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[x for x in range(1,51) if x%3 == 0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "_____\n", + "**Go through the string below and if the length of a word is even print \"even!\"**" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "st = 'Print every word in this sentence that has an even number of letters'" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "word <-- has an even length!\n", + "in <-- has an even length!\n", + "this <-- has an even length!\n", + "sentence <-- has an even length!\n", + "that <-- has an even length!\n", + "an <-- has an even length!\n", + "even <-- has an even length!\n", + "number <-- has an even length!\n", + "of <-- has an even length!\n" + ] + } + ], + "source": [ + "for word in st.split():\n", + " if len(word)%2 == 0:\n", + " print(word+\" <-- has an even length!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a program that prints the integers from 1 to 100. But for multiples of three print \"Fizz\" instead of the number, and for the multiples of five print \"Buzz\". For numbers which are multiples of both three and five print \"FizzBuzz\".**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "for num in range(1,101):\n", + " if num % 3 == 0 and num % 5 == 0:\n", + " print(\"FizzBuzz\")\n", + " elif num % 3 == 0:\n", + " print(\"Fizz\")\n", + " elif num % 5 == 0:\n", + " print(\"Buzz\")\n", + " else:\n", + " print(num)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Use a List Comprehension to create a list of the first letters of every word in the string below:**" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "st = 'Create a list of the first letters of every word in this string'" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['C', 'a', 'l', 'o', 't', 'f', 'l', 'o', 'e', 'w', 'i', 't', 's']" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "[word[0] for word in st.split()]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/09-Guessing Game Challenge.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/09-Guessing Game Challenge.ipynb new file mode 100644 index 0000000..97f6fb7 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/09-Guessing Game Challenge.ipynb @@ -0,0 +1,154 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Guessing Game Challenge\n", + "\n", + "Let's use `while` loops to create a guessing game.\n", + "\n", + "The Challenge:\n", + "\n", + "Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are:\n", + "\n", + "1. If a player's guess is less than 1 or greater than 100, say \"OUT OF BOUNDS\"\n", + "2. On a player's first turn, if their guess is\n", + " * within 10 of the number, return \"WARM!\"\n", + " * further than 10 away from the number, return \"COLD!\"\n", + "3. On all subsequent turns, if a guess is \n", + " * closer to the number than the previous guess return \"WARMER!\"\n", + " * farther from the number than the previous guess, return \"COLDER!\"\n", + "4. When the player's guess equals the number, tell them they've guessed correctly *and* how many guesses it took!\n", + "\n", + "You can try this from scratch, or follow the steps outlined below. A separate Solution notebook has been provided. Good luck!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### First, pick a random integer from 1 to 100 using the random module and assign it to a variable\n", + "\n", + "Note: `random.randint(a,b)` returns a random integer in range `[a, b]`, including both end points." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Next, print an introduction to the game and explain the rules" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Create a list to store guesses\n", + "\n", + "Hint: zero is a good placeholder value. It's useful because it evaluates to \"False\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Write a `while` loop that asks for a valid guess. Test it a few times to make sure it works." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "while True:\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Write a `while` loop that compares the player's guess to our number. If the player guesses correctly, break from the loop. Otherwise, tell the player if they're warmer or colder, and continue asking for guesses.\n", + "\n", + "Some hints:\n", + "* it may help to sketch out all possible combinations on paper first!\n", + "* you can use the `abs()` function to find the positive difference between two numbers\n", + "* if you append all new guesses to the list, then the previous guess is given as `guesses[-2]`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "while True:\n", + "\n", + " # we can copy the code from above to take an input\n", + "\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That's it! You've just programmed your first game!\n", + "\n", + "In the next section we'll learn how to turn some of these repetitive actions into *functions* that can be called whenever we need them." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Good Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/02-Python Statements/10-Guessing Game Challenge - Solution.ipynb b/Complete-Python-3-Bootcamp-master/02-Python Statements/10-Guessing Game Challenge - Solution.ipynb new file mode 100644 index 0000000..3df229e --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/02-Python Statements/10-Guessing Game Challenge - Solution.ipynb @@ -0,0 +1,258 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Guessing Game Challenge - Solution\n", + "\n", + "Let's use `while` loops to create a guessing game.\n", + "\n", + "The Challenge:\n", + "\n", + "Write a program that picks a random integer from 1 to 100, and has players guess the number. The rules are:\n", + "\n", + "1. If a player's guess is less than 1 or greater than 100, say \"OUT OF BOUNDS\"\n", + "2. On a player's first turn, if their guess is\n", + " * within 10 of the number, return \"WARM!\"\n", + " * further than 10 away from the number, return \"COLD!\"\n", + "3. On all subsequent turns, if a guess is \n", + " * closer to the number than the previous guess return \"WARMER!\"\n", + " * farther from the number than the previous guess, return \"COLDER!\"\n", + "4. When the player's guess equals the number, tell them they've guessed correctly *and* how many guesses it took!\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### First, pick a random integer from 1 to 100 using the random module and assign it to a variable\n", + "\n", + "Note: `random.randint(a,b)` returns a random integer in range `[a, b]`, including both end points." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "num = random.randint(1,100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Next, print an introduction to the game and explain the rules" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "WELCOME TO GUESS ME!\n", + "I'm thinking of a number between 1 and 100\n", + "If your guess is more than 10 away from my number, I'll tell you you're COLD\n", + "If your guess is within 10 of my number, I'll tell you you're WARM\n", + "If your guess is farther than your most recent guess, I'll say you're getting COLDER\n", + "If your guess is closer than your most recent guess, I'll say you're getting WARMER\n", + "LET'S PLAY!\n" + ] + } + ], + "source": [ + "print(\"WELCOME TO GUESS ME!\")\n", + "print(\"I'm thinking of a number between 1 and 100\")\n", + "print(\"If your guess is more than 10 away from my number, I'll tell you you're COLD\")\n", + "print(\"If your guess is within 10 of my number, I'll tell you you're WARM\")\n", + "print(\"If your guess is farther than your most recent guess, I'll say you're getting COLDER\")\n", + "print(\"If your guess is closer than your most recent guess, I'll say you're getting WARMER\")\n", + "print(\"LET'S PLAY!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Create a list to store guesses\n", + "\n", + "Hint: zero is a good placeholder value. It's useful because it evaluates to \"False\"" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "guesses = [0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Write a `while` loop that asks for a valid guess. Test it a few times to make sure it works." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 500\n", + "OUT OF BOUNDS! Please try again: \n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 50\n" + ] + } + ], + "source": [ + "while True:\n", + " \n", + " guess = int(input(\"I'm thinking of a number between 1 and 100.\\n What is your guess? \"))\n", + " \n", + " if guess < 1 or guess > 100:\n", + " print('OUT OF BOUNDS! Please try again: ')\n", + " continue\n", + " \n", + " break" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Write a `while` loop that compares the player's guess to our number. If the player guesses correctly, break from the loop. Otherwise, tell the player if they're warmer or colder, and continue asking for guesses.\n", + "\n", + "Some hints:\n", + "* it may help to sketch out all possible combinations on paper first!\n", + "* you can use the `abs()` function to find the positive difference between two numbers\n", + "* if you append all new guesses to the list, then the previous guess is given as `guesses[-2]`" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 50\n", + "COLD!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 75\n", + "WARMER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 85\n", + "WARMER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 92\n", + "COLDER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 80\n", + "WARMER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 78\n", + "COLDER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 82\n", + "WARMER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 83\n", + "COLDER!\n", + "I'm thinking of a number between 1 and 100.\n", + " What is your guess? 81\n", + "CONGRATULATIONS, YOU GUESSED IT IN ONLY 9 GUESSES!!\n" + ] + } + ], + "source": [ + "while True:\n", + "\n", + " # we can copy the code from above to take an input\n", + " guess = int(input(\"I'm thinking of a number between 1 and 100.\\n What is your guess? \"))\n", + " \n", + " if guess < 1 or guess > 100:\n", + " print('OUT OF BOUNDS! Please try again: ')\n", + " continue\n", + " \n", + " # here we compare the player's guess to our number\n", + " if guess == num:\n", + " print(f'CONGRATULATIONS, YOU GUESSED IT IN ONLY {len(guesses)} GUESSES!!')\n", + " break\n", + " \n", + " # if guess is incorrect, add guess to the list\n", + " guesses.append(guess)\n", + " \n", + " # when testing the first guess, guesses[-2]==0, which evaluates to False\n", + " # and brings us down to the second section\n", + " \n", + " if guesses[-2]: \n", + " if abs(num-guess) < abs(num-guesses[-2]):\n", + " print('WARMER!')\n", + " else:\n", + " print('COLDER!')\n", + " \n", + " else:\n", + " if abs(num-guess) <= 10:\n", + " print('WARM!')\n", + " else:\n", + " print('COLD!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "That's it! You've just programmed your first game!\n", + "\n", + "In the next section we'll learn how to turn some of these repetitive actions into *functions* that can be called whenever we need them." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Good Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/01-Methods-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/01-Methods-checkpoint.ipynb new file mode 100644 index 0000000..fde90b4 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/01-Methods-checkpoint.ipynb @@ -0,0 +1,178 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Methods\n", + "\n", + "We've already seen a few example of methods when learning about Object and Data Structure Types in Python. Methods are essentially functions built into objects. Later on in the course we will learn about how to create our own objects and methods using Object Oriented Programming (OOP) and classes.\n", + "\n", + "Methods perform specific actions on an object and can also take arguments, just like a function. This lecture will serve as just a brief introduction to methods and get you thinking about overall design methods that we will touch back upon when we reach OOP in the course.\n", + "\n", + "Methods are in the form:\n", + "\n", + " object.method(arg1,arg2,etc...)\n", + " \n", + "You'll later see that we can think of methods as having an argument 'self' referring to the object itself. You can't see this argument but we will be using it later on in the course during the OOP lectures.\n", + "\n", + "Let's take a quick look at what an example of the various methods a list has:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Create a simple list\n", + "lst = [1,2,3,4,5]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fortunately, with iPython and the Jupyter Notebook we can quickly see all the possible methods using the tab key. The methods for a list are:\n", + "\n", + "* append\n", + "* count\n", + "* extend\n", + "* insert\n", + "* pop\n", + "* remove\n", + "* reverse\n", + "* sort\n", + "\n", + "Let's try out a few of them:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "append() allows us to add elements to the end of a list:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "lst.append(6)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6]" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Now how about count()? The count() method will count the number of occurrences of an element in a list." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check how many times 2 shows up in the list\n", + "lst.count(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can always use Shift+Tab in the Jupyter Notebook to get more help about the method. In general Python you can use the help() function: " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on built-in function count:\n", + "\n", + "count(...) method of builtins.list instance\n", + " L.count(value) -> integer -- return number of occurrences of value\n", + "\n" + ] + } + ], + "source": [ + "help(lst.count)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Feel free to play around with the rest of the methods for a list. Later on in this section your quiz will involve using help and Google searching for methods of different types of objects!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! By this lecture you should feel comfortable calling methods of objects in Python!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/02-Functions-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/02-Functions-checkpoint.ipynb new file mode 100644 index 0000000..1e9243d --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/02-Functions-checkpoint.ipynb @@ -0,0 +1,391 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Functions\n", + "\n", + "## Introduction to Functions\n", + "\n", + "This lecture will consist of explaining what a function is in Python and how to create one. Functions will be one of our main building blocks when we construct larger and larger amounts of code to solve problems.\n", + "\n", + "**So what is a function?**\n", + "\n", + "Formally, a function is a useful device that groups together a set of statements so they can be run more than once. They can also let us specify parameters that can serve as inputs to the functions.\n", + "\n", + "On a more fundamental level, functions allow us to not have to repeatedly write the same code again and again. If you remember back to the lessons on strings and lists, remember that we used a function len() to get the length of a string. Since checking the length of a sequence is a common task you would want to write a function that can do this repeatedly at command.\n", + "\n", + "Functions will be one of most basic levels of reusing code in Python, and it will also allow us to start thinking of program design (we will dive much deeper into the ideas of design when we learn about Object Oriented Programming)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## def Statements\n", + "\n", + "Let's see how to build out a function's syntax in Python. It has the following form:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def name_of_function(arg1,arg2):\n", + " '''\n", + " This is where the function's Document String (docstring) goes\n", + " '''\n", + " # Do stuff here\n", + " # Return desired result" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We begin with def then a space followed by the name of the function. Try to keep names relevant, for example len() is a good name for a length() function. Also be careful with names, you wouldn't want to call a function the same name as a [built-in function in Python](https://docs.python.org/2/library/functions.html) (such as len).\n", + "\n", + "Next come a pair of parentheses with a number of arguments separated by a comma. These arguments are the inputs for your function. You'll be able to use these inputs in your function and reference them. After this you put a colon.\n", + "\n", + "Now here is the important step, you must indent to begin the code inside your function correctly. Python makes use of *whitespace* to organize code. Lots of other programing languages do not do this, so keep that in mind.\n", + "\n", + "Next you'll see the docstring, this is where you write a basic description of the function. Using iPython and iPython Notebooks, you'll be able to read these docstrings by pressing Shift+Tab after a function name. Docstrings are not necessary for simple functions, but it's good practice to put them in so you or other people can easily understand the code you write.\n", + "\n", + "After all this you begin writing the code you wish to execute.\n", + "\n", + "The best way to learn functions is by going through examples. So let's try to go through examples that relate back to the various objects and data structures we learned about before." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Example 1: A simple print 'hello' function" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "def say_hello():\n", + " print('hello')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Call the function:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "hello\n" + ] + } + ], + "source": [ + "say_hello()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Example 2: A simple greeting function\n", + "Let's write a function that greets people with their name." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "def greeting(name):\n", + " print('Hello %s' %(name))" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello Jose\n" + ] + } + ], + "source": [ + "greeting('Jose')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using return\n", + "Let's see some example that use a return statement. return allows a function to *return* a result that can then be stored as a variable, or used in whatever manner a user wants.\n", + "\n", + "### Example 3: Addition function" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "def add_num(num1,num2):\n", + " return num1+num2" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "add_num(4,5)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "# Can also save as variable due to return\n", + "result = add_num(4,5)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "9\n" + ] + } + ], + "source": [ + "print(result)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What happens if we input two strings?" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'onetwo'" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "add_num('one','two')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that because we don't declare variable types in Python, this function could be used to add numbers or sequences together! We'll later learn about adding in checks to make sure a user puts in the correct arguments into a function.\n", + "\n", + "Let's also start using break, continue, and pass statements in our code. We introduced these during the while lecture." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Finally let's go over a full example of creating a function to check if a number is prime (a common interview exercise).\n", + "\n", + "We know a number is prime if that number is only evenly divisible by 1 and itself. Let's write our first version of the function to check all the numbers from 1 to N and perform modulo checks." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def is_prime(num):\n", + " '''\n", + " Naive method of checking for primes. \n", + " '''\n", + " for n in range(2,num):\n", + " if num % n == 0:\n", + " print(num,'is not prime')\n", + " break\n", + " else: # If never mod zero, then prime\n", + " print(num,'is prime!')" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "16 is not prime\n" + ] + } + ], + "source": [ + "is_prime(16)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "17 is prime!\n" + ] + } + ], + "source": [ + "is_prime(17)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how the else lines up under for and not if. This is because we want the for loop to exhaust all possibilities in the range before printing our number is prime.\n", + "\n", + "Also note how we break the code after the first print statement. As soon as we determine that a number is not prime we break out of the for loop.\n", + "\n", + "We can actually improve this function by only checking to the square root of the target number, and by disregarding all even numbers after checking for 2. We'll also switch to returning a boolean value to get an example of using return statements:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "import math\n", + "\n", + "def is_prime2(num):\n", + " '''\n", + " Better method of checking for primes. \n", + " '''\n", + " if num % 2 == 0 and num > 2: \n", + " return False\n", + " for i in range(3, int(math.sqrt(num)) + 1, 2):\n", + " if num % i == 0:\n", + " return False\n", + " return True" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "is_prime2(18)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Why don't we have any break statements? It should be noted that as soon as a function *returns* something, it shuts down. A function can deliver multiple print statements, but it will only obey one return." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! You should now have a basic understanding of creating your own functions to save yourself from repeatedly writing code!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/03-Function Practice Exercises-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/03-Function Practice Exercises-checkpoint.ipynb new file mode 100644 index 0000000..cb906db --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/03-Function Practice Exercises-checkpoint.ipynb @@ -0,0 +1,715 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Function Practice Exercises\n", + "\n", + "Problems are arranged in increasing difficulty:\n", + "* Warmup - these can be solved using basic comparisons and methods\n", + "* Level 1 - these may involve if/then conditional statements and simple methods\n", + "* Level 2 - these may require iterating over sequences, usually with some kind of loop\n", + "* Challenging - these will take some creativity to solve" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## WARMUP SECTION:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers *if* both numbers are even, but returns the greater if one or both numbers are odd\n", + " lesser_of_two_evens(2,4) --> 2\n", + " lesser_of_two_evens(2,5) --> 5" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def lesser_of_two_evens(a,b):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter\n", + " animal_crackers('Levelheaded Llama') --> True\n", + " animal_crackers('Crazy Kangaroo') --> False" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def animal_crackers(text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "animal_crackers('Levelheaded Llama')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "animal_crackers('Crazy Kangaroo')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 *or* if one of the integers is 20. If not, return False\n", + "\n", + " makes_twenty(20,10) --> True\n", + " makes_twenty(12,8) --> True\n", + " makes_twenty(2,3) --> False" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def makes_twenty(n1,n2):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "makes_twenty(20,10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "makes_twenty(2,3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 1 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name\n", + " \n", + " old_macdonald('macdonald') --> MacDonald\n", + " \n", + "Note: `'macdonald'.capitalize()` returns `'Macdonald'`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def old_macdonald(name):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "old_macdonald('macdonald')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MASTER YODA: Given a sentence, return a sentence with the words reversed\n", + "\n", + " master_yoda('I am home') --> 'home am I'\n", + " master_yoda('We are ready') --> 'ready are We'\n", + " \n", + "Note: The .join() method may be useful here. The .join() method allows you to join together strings in a list with some connector string. For example, some uses of the .join() method:\n", + "\n", + " >>> \"--\".join(['a','b','c'])\n", + " >>> 'a--b--c'\n", + "\n", + "This means if you had a list of words you wanted to turn back into a sentence, you could just join them with a single space string:\n", + "\n", + " >>> \" \".join(['Hello','world'])\n", + " >>> \"Hello world\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def master_yoda(text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "master_yoda('I am home')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "master_yoda('We are ready')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200\n", + "\n", + " almost_there(90) --> True\n", + " almost_there(104) --> True\n", + " almost_there(150) --> False\n", + " almost_there(209) --> True\n", + " \n", + "NOTE: `abs(num)` returns the absolute value of a number" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def almost_there(n):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "almost_there(104)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "almost_there(150)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "almost_there(209)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 2 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### FIND 33: \n", + "\n", + "Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.\n", + "\n", + " has_33([1, 3, 3]) → True\n", + " has_33([1, 3, 1, 3]) → False\n", + " has_33([3, 1, 3]) → False" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def has_33(nums):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "has_33([1, 3, 3])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "has_33([1, 3, 1, 3])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "has_33([3, 1, 3])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### PAPER DOLL: Given a string, return a string where for every character in the original there are three characters\n", + " paper_doll('Hello') --> 'HHHeeellllllooo'\n", + " paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def paper_doll(text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "paper_doll('Hello')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "paper_doll('Mississippi')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 *and* there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'\n", + " blackjack(5,6,7) --> 18\n", + " blackjack(9,9,9) --> 'BUST'\n", + " blackjack(9,9,11) --> 19" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def blackjack(a,b,c):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "blackjack(5,6,7)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "blackjack(9,9,9)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "blackjack(9,9,11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.\n", + " \n", + " summer_69([1, 3, 5]) --> 9\n", + " summer_69([4, 5, 6, 7, 8, 9]) --> 9\n", + " summer_69([2, 1, 6, 9, 11]) --> 14" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def summer_69(arr):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "summer_69([1, 3, 5])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "summer_69([4, 5, 6, 7, 8, 9])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "summer_69([2, 1, 6, 9, 11])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# CHALLENGING PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order\n", + "\n", + " spy_game([1,2,4,0,0,7,5]) --> True\n", + " spy_game([1,0,2,4,0,5,7]) --> True\n", + " spy_game([1,7,2,0,4,5,0]) --> False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def spy_game(nums):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "spy_game([1,2,4,0,0,7,5])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "spy_game([1,0,2,4,0,5,7])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "spy_game([1,7,2,0,4,5,0])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### COUNT PRIMES: Write a function that returns the *number* of prime numbers that exist up to and including a given number\n", + " count_primes(100) --> 25\n", + "\n", + "By convention, 0 and 1 are not prime." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def count_primes(num):\n", + " pass\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "count_primes(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Just for fun:\n", + "#### PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter\n", + " print_big('a')\n", + " \n", + " out: * \n", + " * *\n", + " *****\n", + " * *\n", + " * *\n", + "HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns.
For purposes of this exercise, it's ok if your dictionary stops at \"E\"." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def print_big(letter):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "print_big('a')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/03-Lambda expressions-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/03-Lambda expressions-checkpoint.ipynb new file mode 100644 index 0000000..7eec24a --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/03-Lambda expressions-checkpoint.ipynb @@ -0,0 +1,394 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# lambda expressions\n", + "\n", + "One of Python's most useful (and for beginners, confusing) tools is the lambda expression. lambda expressions allow us to create \"anonymous\" functions. This basically means we can quickly make ad-hoc functions without needing to properly define a function using def.\n", + "\n", + "Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs. There is a key difference that makes lambda useful in specialized roles:\n", + "\n", + "**A lambda's body is a single expression, not a block of statements.**\n", + "\n", + "* The lambda's body is similar to what we would put in a def body's return statement. We simply type the result as an expression instead of explicitly returning it. Because it is limited to an expression, a lambda is less general than a def. We can only squeeze design, to limit program nesting. lambda is designed for coding simple functions, and def handles the larger tasks.\n", + "\n", + "Let's slowly break down a lambda expression by deconstructing a function:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def square(num):\n", + " result = num**2\n", + " return result" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Continuing the breakdown:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def square(num):\n", + " return num**2" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can actually write this in one line (although it would be bad style to do so)" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "def square(num): return num**2" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the form that a lambda expression intends to replicate. A lambda expression can then be written as:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda num: num**2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how we get a function back. We can assign this function to a label:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "square = lambda num: num**2" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And there you have it! The breakdown of a function into a lambda expression!\n", + "Lets see a few more examples:\n", + "\n", + "## Example 1\n", + "Check that a number is even:" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "even = lambda x: x%2==0" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "even(3)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "even(4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 2\n", + "Grab first character of a string:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "first = lambda s: s[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'h'" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "first('hello')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 3\n", + "Reverse a string:" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "rev = lambda s: s[::-1]" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'olleh'" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "rev('hello')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Example 4\n", + "Just like a normal function, we can accept more than one argument into a lambda expression:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [], + "source": [ + "adder = lambda x,y : x+y" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "adder(2,3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "lambda expressions really shine when used in conjunction with **map()**, **filter()** and **reduce()**. Each of those functions has its own lecture, so feel free to explore them if you're very interested in lambda." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "I highly recommend reading this blog post at [Python Conquers the Universe](https://pythonconquerstheuniverse.wordpress.com/2011/08/29/lambda_tutorial/) for a great breakdown on lambda expressions and some explanations of common confusions! " + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/04-Function Practice Exercises - Solutions-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/04-Function Practice Exercises - Solutions-checkpoint.ipynb new file mode 100644 index 0000000..33ea1ee --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/04-Function Practice Exercises - Solutions-checkpoint.ipynb @@ -0,0 +1,1106 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Function Practice Exercises - Solutions\n", + "\n", + "Problems are arranged in increasing difficulty:\n", + "* Warmup - these can be solved using basic comparisons and methods\n", + "* Level 1 - these may involve if/then conditional statements and simple methods\n", + "* Level 2 - these may require iterating over sequences, usually with some kind of loop\n", + "* Challenging - these will take some creativity to solve" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## WARMUP SECTION:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers *if* both numbers are even, but returns the greater if one or both numbers are odd\n", + " lesser_of_two_evens(2,4) --> 2\n", + " lesser_of_two_evens(2,5) --> 5" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def lesser_of_two_evens(a,b):\n", + " if a%2 == 0 and b%2 == 0:\n", + " return min(a,b)\n", + " else:\n", + " return max(a,b)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,4)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter\n", + " animal_crackers('Levelheaded Llama') --> True\n", + " animal_crackers('Crazy Kangaroo') --> False" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "def animal_crackers(text):\n", + " wordlist = text.split()\n", + " return wordlist[0][0] == wordlist[1][0]" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "animal_crackers('Levelheaded Llama')" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "animal_crackers('Crazy Kangaroo')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 *or* if one of the integers is 20. If not, return False\n", + "\n", + " makes_twenty(20,10) --> True\n", + " makes_twenty(12,8) --> True\n", + " makes_twenty(2,3) --> False" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "def makes_twenty(n1,n2):\n", + " return (n1+n2)==20 or n1==20 or n2==20" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "makes_twenty(20,10)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "makes_twenty(12,8)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Check\n", + "makes_twenty(2,3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 1 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name\n", + " \n", + " old_macdonald('macdonald') --> MacDonald\n", + " \n", + "Note: `'macdonald'.capitalize()` returns `'Macdonald'`" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def old_macdonald(name):\n", + " if len(name) > 3:\n", + " return name[:3].capitalize() + name[3:].capitalize()\n", + " else:\n", + " return 'Name is too short!'" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'MacDonald'" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "old_macdonald('macdonald')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MASTER YODA: Given a sentence, return a sentence with the words reversed\n", + "\n", + " master_yoda('I am home') --> 'home am I'\n", + " master_yoda('We are ready') --> 'ready are We'" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def master_yoda(text):\n", + " return ' '.join(text.split()[::-1])" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'home am I'" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "master_yoda('I am home')" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'ready are We'" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "master_yoda('We are ready')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200\n", + "\n", + " almost_there(90) --> True\n", + " almost_there(104) --> True\n", + " almost_there(150) --> False\n", + " almost_there(209) --> True\n", + " \n", + "NOTE: `abs(num)` returns the absolute value of a number" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "def almost_there(n):\n", + " return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10))" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(90)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(104)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(150)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(209)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 2 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### FIND 33: \n", + "\n", + "Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.\n", + "\n", + " has_33([1, 3, 3]) → True\n", + " has_33([1, 3, 1, 3]) → False\n", + " has_33([3, 1, 3]) → False" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "def has_33(nums):\n", + " for i in range(0, len(nums)-1):\n", + " \n", + " # nicer looking alternative in commented code\n", + " #if nums[i] == 3 and nums[i+1] == 3:\n", + " \n", + " if nums[i:i+2] == [3,3]:\n", + " return True \n", + " \n", + " return False" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "has_33([1, 3, 3])" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "has_33([1, 3, 1, 3])" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "has_33([3, 1, 3])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### PAPER DOLL: Given a string, return a string where for every character in the original there are three characters\n", + " paper_doll('Hello') --> 'HHHeeellllllooo'\n", + " paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [], + "source": [ + "def paper_doll(text):\n", + " result = ''\n", + " for char in text:\n", + " result += char * 3\n", + " return result" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'HHHeeellllllooo'" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "paper_doll('Hello')" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'MMMiiissssssiiissssssiiippppppiii'" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "paper_doll('Mississippi')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 *and* there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'\n", + " blackjack(5,6,7) --> 18\n", + " blackjack(9,9,9) --> 'BUST'\n", + " blackjack(9,9,11) --> 19" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [], + "source": [ + "def blackjack(a,b,c):\n", + " \n", + " if sum((a,b,c)) <= 21:\n", + " return sum((a,b,c))\n", + " elif sum((a,b,c)) <=31 and 11 in (a,b,c):\n", + " return sum((a,b,c)) - 10\n", + " else:\n", + " return 'BUST'" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "18" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "blackjack(5,6,7)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'BUST'" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "blackjack(9,9,9)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "19" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "blackjack(9,9,11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.\n", + " \n", + " summer_69([1, 3, 5]) --> 9\n", + " summer_69([4, 5, 6, 7, 8, 9]) --> 9\n", + " summer_69([2, 1, 6, 9, 11]) --> 14" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "def summer_69(arr):\n", + " total = 0\n", + " add = True\n", + " for num in arr:\n", + " while add:\n", + " if num != 6:\n", + " total += num\n", + " break\n", + " else:\n", + " add = False\n", + " while not add:\n", + " if num != 9:\n", + " break\n", + " else:\n", + " add = True\n", + " break\n", + " return total" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "summer_69([1, 3, 5])" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "summer_69([4, 5, 6, 7, 8, 9])" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "14" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "summer_69([2, 1, 6, 9, 11])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# CHALLENGING PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order\n", + "\n", + " spy_game([1,2,4,0,0,7,5]) --> True\n", + " spy_game([1,0,2,4,0,5,7]) --> True\n", + " spy_game([1,7,2,0,4,5,0]) --> False\n" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [], + "source": [ + "def spy_game(nums):\n", + "\n", + " code = [0,0,7,'x']\n", + " \n", + " for num in nums:\n", + " if num == code[0]:\n", + " code.pop(0) # code.remove(num) also works\n", + " \n", + " return len(code) == 1" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "spy_game([1,2,4,0,0,7,5])" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "spy_game([1,0,2,4,0,5,7])" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "spy_game([1,7,2,0,4,5,0])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### COUNT PRIMES: Write a function that returns the *number* of prime numbers that exist up to and including a given number\n", + " count_primes(100) --> 25\n", + "\n", + "By convention, 0 and 1 are not prime." + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [], + "source": [ + "def count_primes(num):\n", + " primes = [2]\n", + " x = 3\n", + " if num < 2: # for the case of num = 0 or 1\n", + " return 0\n", + " while x <= num:\n", + " for y in range(3,x,2): # test all odd factors up to x-1\n", + " if x%y == 0:\n", + " x += 2\n", + " break\n", + " else:\n", + " primes.append(x)\n", + " x += 2\n", + " print(primes)\n", + " return len(primes)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n" + ] + }, + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "count_primes(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "BONUS: Here's a faster version that makes use of the prime numbers we're collecting as we go!" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [], + "source": [ + "def count_primes2(num):\n", + " primes = [2]\n", + " x = 3\n", + " if num < 2:\n", + " return 0\n", + " while x <= num:\n", + " for y in primes: # use the primes list!\n", + " if x%y == 0:\n", + " x += 2\n", + " break\n", + " else:\n", + " primes.append(x)\n", + " x += 2\n", + " print(primes)\n", + " return len(primes)" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n" + ] + }, + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "count_primes2(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "-----\n", + "### Just for fun, not a real problem :)\n", + "\n", + "#### PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter\n", + " print_big('a')\n", + " \n", + " out: * \n", + " * *\n", + " *****\n", + " * *\n", + " * *\n", + "HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns.
For purposes of this exercise, it's ok if your dictionary stops at \"E\"." + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": {}, + "outputs": [], + "source": [ + "def print_big(letter):\n", + " patterns = {1:' * ',2:' * * ',3:'* *',4:'*****',5:'**** ',6:' * ',7:' * ',8:'* * ',9:'* '}\n", + " alphabet = {'A':[1,2,4,3,3],'B':[5,3,5,3,5],'C':[4,9,9,9,4],'D':[5,3,3,3,5],'E':[4,9,4,9,4]}\n", + " for pattern in alphabet[letter.upper()]:\n", + " print(patterns[pattern])" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " * \n", + " * * \n", + "*****\n", + "* *\n", + "* *\n" + ] + } + ], + "source": [ + "print_big('a')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/04-Nested Statements and Scope-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/04-Nested Statements and Scope-checkpoint.ipynb new file mode 100644 index 0000000..c3871db --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/04-Nested Statements and Scope-checkpoint.ipynb @@ -0,0 +1,357 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Nested Statements and Scope \n", + "\n", + "Now that we have gone over writing our own functions, it's important to understand how Python deals with the variable names you assign. When you create a variable name in Python the name is stored in a *name-space*. Variable names also have a *scope*, the scope determines the visibility of that variable name to other parts of your code.\n", + "\n", + "Let's start with a quick thought experiment; imagine the following code:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "x = 25\n", + "\n", + "def printer():\n", + " x = 50\n", + " return x\n", + "\n", + "# print(x)\n", + "# print(printer())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What do you imagine the output of printer() is? 25 or 50? What is the output of print x? 25 or 50?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "25\n" + ] + } + ], + "source": [ + "print(x)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "50\n" + ] + } + ], + "source": [ + "print(printer())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Interesting! But how does Python know which **x** you're referring to in your code? This is where the idea of scope comes in. Python has a set of rules it follows to decide what variables (such as **x** in this case) you are referencing in your code. Lets break down the rules:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "This idea of scope in your code is very important to understand in order to properly assign and call variable names. \n", + "\n", + "In simple terms, the idea of scope can be described by 3 general rules:\n", + "\n", + "1. Name assignments will create or change local names by default.\n", + "2. Name references search (at most) four scopes, these are:\n", + " * local\n", + " * enclosing functions\n", + " * global\n", + " * built-in\n", + "3. Names declared in global and nonlocal statements map assigned names to enclosing module and function scopes.\n", + "\n", + "\n", + "The statement in #2 above can be defined by the LEGB rule.\n", + "\n", + "**LEGB Rule:**\n", + "\n", + "L: Local — Names assigned in any way within a function (def or lambda), and not declared global in that function.\n", + "\n", + "E: Enclosing function locals — Names in the local scope of any and all enclosing functions (def or lambda), from inner to outer.\n", + "\n", + "G: Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.\n", + "\n", + "B: Built-in (Python) — Names preassigned in the built-in names module : open, range, SyntaxError,..." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Quick examples of LEGB\n", + "\n", + "### Local" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "# x is local here:\n", + "f = lambda x:x**2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Enclosing function locals\n", + "This occurs when we have a function inside a function (nested functions)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello Sammy\n" + ] + } + ], + "source": [ + "name = 'This is a global name'\n", + "\n", + "def greet():\n", + " # Enclosing function\n", + " name = 'Sammy'\n", + " \n", + " def hello():\n", + " print('Hello '+name)\n", + " \n", + " hello()\n", + "\n", + "greet()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how Sammy was used, because the hello() function was enclosed inside of the greet function!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Global\n", + "Luckily in Jupyter a quick way to test for global variables is to see if another cell recognizes the variable!" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a global name\n" + ] + } + ], + "source": [ + "print(name)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Built-in\n", + "These are the built-in function names in Python (don't overwrite these!)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Local Variables\n", + "When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function - i.e. variable names are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name.\n", + "\n", + "Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is 50\n", + "Changed local x to 2\n", + "x is still 50\n" + ] + } + ], + "source": [ + "x = 50\n", + "\n", + "def func(x):\n", + " print('x is', x)\n", + " x = 2\n", + " print('Changed local x to', x)\n", + "\n", + "func(x)\n", + "print('x is still', x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The first time that we print the value of the name **x** with the first line in the function’s body, Python uses the value of the parameter declared in the main block, above the function definition.\n", + "\n", + "Next, we assign the value 2 to **x**. The name **x** is local to our function. So, when we change the value of **x** in the function, the **x** defined in the main block remains unaffected.\n", + "\n", + "With the last print statement, we display the value of **x** as defined in the main block, thereby confirming that it is actually unaffected by the local assignment within the previously called function.\n", + "\n", + "## The global statement\n", + "If you want to assign a value to a name defined at the top level of the program (i.e. not inside any kind of scope such as functions or classes), then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.\n", + "\n", + "You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable’s definition is. Using the global statement makes it amply clear that the variable is defined in an outermost block.\n", + "\n", + "Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Before calling func(), x is: 50\n", + "This function is now using the global x!\n", + "Because of global x is: 50\n", + "Ran func(), changed global x to 2\n", + "Value of x (outside of func()) is: 2\n" + ] + } + ], + "source": [ + "x = 50\n", + "\n", + "def func():\n", + " global x\n", + " print('This function is now using the global x!')\n", + " print('Because of global x is: ', x)\n", + " x = 2\n", + " print('Ran func(), changed global x to', x)\n", + "\n", + "print('Before calling func(), x is: ', x)\n", + "func()\n", + "print('Value of x (outside of func()) is: ', x)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "The global statement is used to declare that **x** is a global variable - hence, when we assign a value to **x** inside the function, that change is reflected when we use the value of **x** in the main block.\n", + "\n", + "You can specify more than one global variable using the same global statement e.g. global x, y, z." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Conclusion\n", + "You should now have a good understanding of Scope (you may have already intuitively felt right about Scope which is great!) One last mention is that you can use the **globals()** and **locals()** functions to check what are your current local and global variables.\n", + "\n", + "Another thing to keep in mind is that everything in Python is an object! I can assign variables to functions just like I can with numbers! We will go over this again in the decorator section of the course!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/05-Functions and Methods Homework-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/05-Functions and Methods Homework-checkpoint.ipynb new file mode 100644 index 0000000..95d6109 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/05-Functions and Methods Homework-checkpoint.ipynb @@ -0,0 +1,386 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Functions and Methods Homework \n", + "\n", + "Complete the following questions:\n", + "____\n", + "**Write a function that computes the volume of a sphere given its radius.**\n", + "

The volume of a sphere is given as $$\\frac{4}{3} πr^3$$

" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def vol(rad):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "33.49333333333333" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "vol(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "___\n", + "**Write a function that checks whether a number is in a given range (inclusive of high and low)**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def ran_check(num,low,high):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5 is in the range between 2 and 7\n" + ] + } + ], + "source": [ + "# Check\n", + "ran_check(5,2,7)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you only wanted to return a boolean:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "def ran_bool(num,low,high):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ran_bool(3,1,10)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters.**\n", + "\n", + " Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'\n", + " Expected Output : \n", + " No. of Upper case characters : 4\n", + " No. of Lower case Characters : 33\n", + "\n", + "HINT: Two string methods that might prove useful: **.isupper()** and **.islower()**\n", + "\n", + "If you feel ambitious, explore the Collections module to solve this problem!" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "def up_low(s):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Original String : Hello Mr. Rogers, how are you this fine Tuesday?\n", + "No. of Upper case characters : 4\n", + "No. of Lower case Characters : 33\n" + ] + } + ], + "source": [ + "s = 'Hello Mr. Rogers, how are you this fine Tuesday?'\n", + "up_low(s)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that takes a list and returns a new list with unique elements of the first list.**\n", + "\n", + " Sample List : [1,1,1,1,2,2,3,3,3,3,4,5]\n", + " Unique List : [1, 2, 3, 4, 5]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "def unique_list(lst):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5]" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "unique_list([1,1,1,1,2,2,3,3,3,3,4,5])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function to multiply all the numbers in a list.**\n", + "\n", + " Sample List : [1, 2, 3, -4]\n", + " Expected Output : -24" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def multiply(numbers): \n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-24" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "multiply([1,2,3,-4])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that checks whether a passed in string is palindrome or not.**\n", + "\n", + "Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def palindrome(s):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "palindrome('helleh')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "#### Hard:\n", + "\n", + "**Write a Python function to check whether a string is pangram or not.**\n", + "\n", + " Note : Pangrams are words or sentences containing every letter of the alphabet at least once.\n", + " For example : \"The quick brown fox jumps over the lazy dog\"\n", + "\n", + "Hint: Look at the string module" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "import string\n", + "\n", + "def ispangram(str1, alphabet=string.ascii_lowercase):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ispangram(\"The quick brown fox jumps over the lazy dog\")" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'abcdefghijklmnopqrstuvwxyz'" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "string.ascii_lowercase" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "#### Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/05-Lambda-Expressions-Map-and-Filter-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/05-Lambda-Expressions-Map-and-Filter-checkpoint.ipynb new file mode 100644 index 0000000..4243e68 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/05-Lambda-Expressions-Map-and-Filter-checkpoint.ipynb @@ -0,0 +1,569 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lambda Expressions, Map, and Filter\n", + "\n", + "Now its time to quickly learn about two built in functions, filter and map. Once we learn about how these operate, we can learn about the lambda expression, which will come in handy when you begin to develop your skills further!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## map function\n", + "\n", + "The **map** function allows you to \"map\" a function to an iterable object. That is to say you can quickly call the same function to every item in an iterable, such as a list. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def square(num):\n", + " return num**2" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_nums = [1,2,3,4,5]" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "map(square,my_nums)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 4, 9, 16, 25]" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# To get the results, either iterate through map() \n", + "# or just cast to a list\n", + "list(map(square,my_nums))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The functions can also be more complex" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def splicer(mystring):\n", + " if len(mystring) % 2 == 0:\n", + " return 'even'\n", + " else:\n", + " return mystring[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "mynames = ['John','Cindy','Sarah','Kelly','Mike']" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['even', 'C', 'S', 'K', 'even']" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(map(splicer,mynames))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## filter function\n", + "\n", + "The filter function returns an iterator yielding those items of iterable for which function(item)\n", + "is true. Meaning you need to filter by a function that returns either True or False. Then passing that into filter (along with your iterable) and you will get back only the results that would return True when passed to the function." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def check_even(num):\n", + " return num % 2 == 0 " + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "nums = [0,1,2,3,4,5,6,7,8,9,10]" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "filter(check_even,nums)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(filter(check_even,nums))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## lambda expression\n", + "\n", + "One of Pythons most useful (and for beginners, confusing) tools is the lambda expression. lambda expressions allow us to create \"anonymous\" functions. This basically means we can quickly make ad-hoc functions without needing to properly define a function using def.\n", + "\n", + "Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs. There is key difference that makes lambda useful in specialized roles:\n", + "\n", + "**lambda's body is a single expression, not a block of statements.**\n", + "\n", + "* The lambda's body is similar to what we would put in a def body's return statement. We simply type the result as an expression instead of explicitly returning it. Because it is limited to an expression, a lambda is less general that a def. We can only squeeze design, to limit program nesting. lambda is designed for coding simple functions, and def handles the larger tasks." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Lets slowly break down a lambda expression by deconstructing a function:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def square(num):\n", + " result = num**2\n", + " return result" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We could simplify it:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def square(num):\n", + " return num**2" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We could actually even write this all on one line." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def square(num): return num**2" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the form a function that a lambda expression intends to replicate. A lambda expression can then be written as:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda num: num ** 2" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# You wouldn't usually assign a name to a lambda expression, this is just for demonstration!\n", + "square = lambda num: num **2" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So why would use this? Many function calls need a function passed in, such as map and filter. Often you only need to use the function you are passing in once, so instead of formally defining it, you just use the lambda expression. Let's repeat some of the examples from above with a lambda expression" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 4, 9, 16, 25]" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(map(lambda num: num ** 2, my_nums))" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(filter(lambda n: n % 2 == 0,nums))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here are a few more examples, keep in mind the more comples a function is, the harder it is to translate into a lambda expression, meaning sometimes its just easier (and often the only way) to create the def keyword function." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "** Lambda expression for grabbing the first character of a string: **" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda s: s[0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "** Lambda expression for reversing a string: **" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda s: s[::-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can even pass in multiple arguments into a lambda expression. Again, keep in mind that not every function can be translated into a lambda expression." + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda x,y : x + y" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You will find yourself using lambda expressions often with certain non-built-in libraries, for example the pandas library for data analysis works very well with lambda expressions." + ] + } + ], + "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.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/06-Functions and Methods Homework - Solutions-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/06-Functions and Methods Homework - Solutions-checkpoint.ipynb new file mode 100644 index 0000000..68303e6 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/06-Functions and Methods Homework - Solutions-checkpoint.ipynb @@ -0,0 +1,417 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Functions and Methods Homework Solutions\n", + "____\n", + "**Write a function that computes the volume of a sphere given its radius.**" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def vol(rad):\n", + " return (4/3)*(3.14)*(rad**3)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "33.49333333333333" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "vol(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "___\n", + "**Write a function that checks whether a number is in a given range (inclusive of high and low)**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def ran_check(num,low,high):\n", + " #Check if num is between low and high (including low and high)\n", + " if num in range(low,high+1):\n", + " print('{} is in the range between {} and {}'.format(num,low,high))\n", + " else:\n", + " print('The number is outside the range.')" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5 is in the range between 2 and 7\n" + ] + } + ], + "source": [ + "# Check\n", + "ran_check(5,2,7)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you only wanted to return a boolean:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "def ran_bool(num,low,high):\n", + " return num in range(low,high+1)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ran_bool(3,1,10)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters.**\n", + "\n", + " Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'\n", + " Expected Output : \n", + " No. of Upper case characters : 4\n", + " No. of Lower case Characters : 33\n", + "\n", + "If you feel ambitious, explore the Collections module to solve this problem!" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "def up_low(s):\n", + " d={\"upper\":0, \"lower\":0}\n", + " for c in s:\n", + " if c.isupper():\n", + " d[\"upper\"]+=1\n", + " elif c.islower():\n", + " d[\"lower\"]+=1\n", + " else:\n", + " pass\n", + " print(\"Original String : \", s)\n", + " print(\"No. of Upper case characters : \", d[\"upper\"])\n", + " print(\"No. of Lower case Characters : \", d[\"lower\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Original String : Hello Mr. Rogers, how are you this fine Tuesday?\n", + "No. of Upper case characters : 4\n", + "No. of Lower case Characters : 33\n" + ] + } + ], + "source": [ + "s = 'Hello Mr. Rogers, how are you this fine Tuesday?'\n", + "up_low(s)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that takes a list and returns a new list with unique elements of the first list.**\n", + "\n", + " Sample List : [1,1,1,1,2,2,3,3,3,3,4,5]\n", + " Unique List : [1, 2, 3, 4, 5]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "def unique_list(lst):\n", + " # Also possible to use list(set())\n", + " x = []\n", + " for a in lst:\n", + " if a not in x:\n", + " x.append(a)\n", + " return x" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5]" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "unique_list([1,1,1,1,2,2,3,3,3,3,4,5])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function to multiply all the numbers in a list.**\n", + "\n", + " Sample List : [1, 2, 3, -4]\n", + " Expected Output : -24" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def multiply(numbers):\n", + " total = 1\n", + " for x in numbers:\n", + " total *= x\n", + " return total" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-24" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "multiply([1,2,3,-4])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that checks whether a passed string is palindrome or not.**\n", + "\n", + "Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def palindrome(s):\n", + " \n", + " s = s.replace(' ','') # This replaces all spaces ' ' with no space ''. (Fixes issues with strings that have spaces)\n", + " return s == s[::-1] # Check through slicing" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "palindrome('nurses run')" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "palindrome('abcba')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Hard**:\n", + "\n", + "Write a Python function to check whether a string is pangram or not.\n", + "\n", + " Note : Pangrams are words or sentences containing every letter of the alphabet at least once.\n", + " For example : \"The quick brown fox jumps over the lazy dog\"\n", + "\n", + "Hint: Look at the string module" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "import string\n", + "\n", + "def ispangram(str1, alphabet=string.ascii_lowercase): \n", + " alphaset = set(alphabet) \n", + " return alphaset <= set(str1.lower()) " + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ispangram(\"The quick brown fox jumps over the lazy dog\")" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'abcdefghijklmnopqrstuvwxyz'" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "string.ascii_lowercase" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/07-args and kwargs-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/07-args and kwargs-checkpoint.ipynb new file mode 100644 index 0000000..47fa02a --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/07-args and kwargs-checkpoint.ipynb @@ -0,0 +1,272 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# `*args` and `**kwargs`\n", + "\n", + "Work with Python long enough, and eventually you will encounter `*args` and `**kwargs`. These strange terms show up as parameters in function definitions. What do they do? Let's review a simple function:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5.0" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def myfunc(a,b):\n", + " return sum((a,b))*.05\n", + "\n", + "myfunc(40,60)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This function returns 5% of the sum of **a** and **b**. In this example, **a** and **b** are *positional* arguments; that is, 40 is assigned to **a** because it is the first argument, and 60 to **b**. Notice also that to work with multiple positional arguments in the `sum()` function we had to pass them in as a tuple.\n", + "\n", + "What if we want to work with more than two numbers? One way would be to assign a *lot* of parameters, and give each one a default value." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "6.0" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def myfunc(a=0,b=0,c=0,d=0,e=0):\n", + " return sum((a,b,c,d,e))*.05\n", + "\n", + "myfunc(40,60,20)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Obviously this is not a very efficient solution, and that's where `*args` comes in.\n", + "\n", + "## `*args`\n", + "\n", + "When a function parameter starts with an asterisk, it allows for an *arbitrary number* of arguments, and the function takes them in as a tuple of values. Rewriting the above function:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "6.0" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def myfunc(*args):\n", + " return sum(args)*.05\n", + "\n", + "myfunc(40,60,20)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how passing the keyword \"args\" into the `sum()` function did the same thing as a tuple of arguments.\n", + "\n", + "It is worth noting that the word \"args\" is itself arbitrary - any word will do so long as it's preceded by an asterisk. To demonstrate this:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "6.0" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def myfunc(*spam):\n", + " return sum(spam)*.05\n", + "\n", + "myfunc(40,60,20)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `**kwargs`\n", + "\n", + "Similarly, Python offers a way to handle arbitrary numbers of *keyworded* arguments. Instead of creating a tuple of values, `**kwargs` builds a dictionary of key/value pairs. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "My favorite fruit is pineapple\n" + ] + } + ], + "source": [ + "def myfunc(**kwargs):\n", + " if 'fruit' in kwargs:\n", + " print(f\"My favorite fruit is {kwargs['fruit']}\") # review String Formatting and f-strings if this syntax is unfamiliar\n", + " else:\n", + " print(\"I don't like fruit\")\n", + " \n", + "myfunc(fruit='pineapple')" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I don't like fruit\n" + ] + } + ], + "source": [ + "myfunc()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `*args` and `**kwargs` combined\n", + "\n", + "You can pass `*args` and `**kwargs` into the same function, but `*args` have to appear before `**kwargs`" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I like eggs and spam and my favorite fruit is cherries\n", + "May I have some orange juice?\n" + ] + } + ], + "source": [ + "def myfunc(*args, **kwargs):\n", + " if 'fruit' and 'juice' in kwargs:\n", + " print(f\"I like {' and '.join(args)} and my favorite fruit is {kwargs['fruit']}\")\n", + " print(f\"May I have some {kwargs['juice']} juice?\")\n", + " else:\n", + " pass\n", + " \n", + "myfunc('eggs','spam',fruit='cherries',juice='orange')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Placing keyworded arguments ahead of positional arguments raises an exception:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "positional argument follows keyword argument (, line 1)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m myfunc(fruit='cherries',juice='orange','eggs','spam')\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m positional argument follows keyword argument\n" + ] + } + ], + "source": [ + "myfunc(fruit='cherries',juice='orange','eggs','spam')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As with \"args\", you can use any name you'd like for keyworded arguments - \"kwargs\" is just a popular convention.\n", + "\n", + "That's it! Now you should understand how `*args` and `**kwargs` provide the flexibilty to work with arbitrary numbers of arguments!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/08-Function Practice Exercises-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/08-Function Practice Exercises-checkpoint.ipynb new file mode 100644 index 0000000..3380eeb --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/08-Function Practice Exercises-checkpoint.ipynb @@ -0,0 +1,604 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Function Practice Exercises\n", + "\n", + "Problems are arranged in increasing difficulty:\n", + "* Warmup - these can be solved using basic comparisons and methods\n", + "* Level 1 - these may involve if/then conditional statements and simple methods\n", + "* Level 2 - these may require iterating over sequences, usually with some kind of loop\n", + "* Challenging - these will take some creativity to solve" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## WARMUP SECTION:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers *if* both numbers are even, but returns the greater if one or both numbers are odd\n", + " lesser_of_two_evens(2,4) --> 2\n", + " lesser_of_two_evens(2,5) --> 5" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def lesser_of_two_evens(a,b):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter\n", + " animal_crackers('Levelheaded Llama') --> True\n", + " animal_crackers('Crazy Kangaroo') --> False" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def animal_crackers(text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "animal_crackers('Levelheaded Llama')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "animal_crackers('Crazy Kangaroo')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### THE OTHER SIDE OF SEVEN: Given a value, return a value that is twice as far away on the other side of 7\n", + "\n", + " other_side_of_seven(4) --> 13\n", + " other_side_of_seven(12) --> -3" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def other_side_of_seven(num):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "other_side_of_seven(4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "other_side_of_seven(12)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 1 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name\n", + " \n", + " old_macdonald('macdonald') --> MacDonald\n", + " \n", + "Note: `'macdonald'.capitalize()` returns `'Macdonald'`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def old_macdonald(name):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "old_macdonald('macdonald')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MASTER YODA: Given a sentence, return a sentence with the words reversed\n", + "\n", + " master_yoda('I am home') --> 'home am I'\n", + " master_yoda('We are ready') --> 'ready are We'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def master_yoda(text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "master_yoda('I am home')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "master_yoda('We are ready')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200\n", + "\n", + " almost_there(90) --> True\n", + " almost_there(104) --> True\n", + " almost_there(150) --> False\n", + " almost_there(209) --> True\n", + " \n", + "NOTE: `abs(num)` returns the absolute value of a number" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def almost_there(n):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "almost_there(104)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "almost_there(150)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "almost_there(209)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 2 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### LAUGHTER: Write a function that counts the number of times a given pattern appears in a string, *including overlap*\n", + "\n", + " laughter('hah','hahahah') --> 3\n", + "\n", + "Note that `'hahahah'.count('hah')` only returns 2." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def laughter(pattern,text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "laughter('hah','hahahah')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### PAPER DOLL: Given a string, return a string where for every character in the original there are three characters\n", + " paper_doll('Hello') --> 'HHHeeellllllooo'\n", + " paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def paper_doll(text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "paper_doll('Hello')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "paper_doll('Mississippi')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 *and* there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'\n", + " blackjack(5,6,7) --> 18\n", + " blackjack(9,9,9) --> 'BUST'\n", + " blackjack(9,9,11) --> 19" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def blackjack(a,b,c):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "blackjack(5,6,7)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "blackjack(9,9,9)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "blackjack(9,9,11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.\n", + " \n", + " summer_69([1, 3, 5]) --> 9\n", + " summer_69([4, 5, 6, 7, 8, 9]) --> 9\n", + " summer_69([2, 1, 6, 9, 11]) --> 14" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def summer_69(arr):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "summer_69([1, 3, 5])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "summer_69([4, 5, 6, 7, 8, 9])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "summer_69([2, 1, 6, 9, 11])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# CHALLENGING PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order\n", + "\n", + " spy_game([1,2,4,0,0,7,5]) --> True\n", + " spy_game([1,0,2,4,0,5,7]) --> True\n", + " spy_game([1,7,2,0,4,5,0]) --> False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def spy_game(nums):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "spy_game([1,2,4,0,0,7,5])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "spy_game([1,0,2,4,0,5,7])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "spy_game([1,7,2,0,4,5,0])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### COUNT PRIMES: Write a function that returns the *number* of prime numbers that exist up to and including a given number\n", + " count_primes(100) --> 25\n", + "\n", + "By convention, 0 and 1 are not prime." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def count_primes(num):\n", + " pass\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "count_primes(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Just for fun:\n", + "#### PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter\n", + " print_big('a')\n", + " \n", + " out: * \n", + " * *\n", + " *****\n", + " * *\n", + " * *\n", + "HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns.
For purposes of this exercise, it's ok if your dictionary stops at \"E\"." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def print_big(letter):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print_big('a')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/09-Function Practice Exercises - Solutions-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/09-Function Practice Exercises - Solutions-checkpoint.ipynb new file mode 100644 index 0000000..d5c2069 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/.ipynb_checkpoints/09-Function Practice Exercises - Solutions-checkpoint.ipynb @@ -0,0 +1,1013 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Function Practice Exercises - Solutions\n", + "\n", + "Problems are arranged in increasing difficulty:\n", + "* Warmup - these can be solved using basic comparisons and methods\n", + "* Level 1 - these may involve if/then conditional statements and simple methods\n", + "* Level 2 - these may require iterating over sequences, usually with some kind of loop\n", + "* Challenging - these will take some creativity to solve" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## WARMUP SECTION:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers *if* both numbers are even, but returns the greater if one or both numbers are odd\n", + " lesser_of_two_evens(2,4) --> 2\n", + " lesser_of_two_evens(2,5) --> 5" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def lesser_of_two_evens(a,b):\n", + " if a%2 == 0 and b%2 == 0:\n", + " return min(a,b)\n", + " else:\n", + " return max(a,b)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,4)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter\n", + " animal_crackers('Levelheaded Llama') --> True\n", + " animal_crackers('Crazy Kangaroo') --> False" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "def animal_crackers(text):\n", + " wordlist = text.split()\n", + " return wordlist[0][0] == wordlist[1][0]" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "animal_crackers('Levelheaded Llama')" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "animal_crackers('Crazy Kangaroo')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### THE OTHER SIDE OF SEVEN: Given a value, return a value that is twice as far away on the other side of 7\n", + "\n", + " other_side_of_seven(4) --> 13\n", + " other_side_of_seven(12) --> -3" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "def other_side_of_seven(num):\n", + " return 7 - 2*(num-7)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "13" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "other_side_of_seven(4)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-3" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "other_side_of_seven(12)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 1 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name\n", + " \n", + " old_macdonald('macdonald') --> MacDonald\n", + " \n", + "Note: `'macdonald'.capitalize()` returns `'Macdonald'`" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def old_macdonald(name):\n", + " if len(name) > 3:\n", + " return name[:3].capitalize() + name[3:].capitalize()\n", + " else:\n", + " return 'Name is too short!'" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'MacDonald'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "old_macdonald('macdonald')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MASTER YODA: Given a sentence, return a sentence with the words reversed\n", + "\n", + " master_yoda('I am home') --> 'home am I'\n", + " master_yoda('We are ready') --> 'ready are We'" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "def master_yoda(text):\n", + " return ' '.join(text.split()[::-1])" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'home am I'" + ] + }, + "execution_count": 13, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "master_yoda('I am home')" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'ready are We'" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "master_yoda('We are ready')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200\n", + "\n", + " almost_there(90) --> True\n", + " almost_there(104) --> True\n", + " almost_there(150) --> False\n", + " almost_there(209) --> True\n", + " \n", + "NOTE: `abs(num)` returns the absolute value of a number" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "def almost_there(n):\n", + " return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10))" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(104)" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(150)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(209)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 2 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### LAUGHTER: Write a function that counts the number of times a given pattern appears in a string, *including overlap*\n", + "\n", + " laughter('hah','hahahah') --> 3\n", + "\n", + "Note that `'hahahah'.count('hah')` only returns 2." + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [], + "source": [ + "def laughter(pattern,text):\n", + " out = 0\n", + " for x in range(len(text)-2):\n", + " if text[x:x+len(pattern)] == pattern:\n", + " out += 1\n", + " return out" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "laughter('hah','hahahah')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### PAPER DOLL: Given a string, return a string where for every character in the original there are three characters\n", + " paper_doll('Hello') --> 'HHHeeellllllooo'\n", + " paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "def paper_doll(text):\n", + " result = ''\n", + " for char in text:\n", + " result += char * 3\n", + " return result" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'HHHeeellllllooo'" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "paper_doll('Hello')" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'MMMiiissssssiiissssssiiippppppiii'" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "paper_doll('Mississippi')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 *and* there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'\n", + " blackjack(5,6,7) --> 18\n", + " blackjack(9,9,9) --> 'BUST'\n", + " blackjack(9,9,11) --> 19" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [], + "source": [ + "def blackjack(a,b,c):\n", + " \n", + " if sum((a,b,c)) <= 21:\n", + " return sum((a,b,c))\n", + " elif sum((a,b,c)) <=31 and 11 in (a,b,c):\n", + " return sum((a,b,c)) - 10\n", + " else:\n", + " return 'BUST'" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "18" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "blackjack(5,6,7)" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'BUST'" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "blackjack(9,9,9)" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "19" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "blackjack(9,9,11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.\n", + " \n", + " summer_69([1, 3, 5]) --> 9\n", + " summer_69([4, 5, 6, 7, 8, 9]) --> 9\n", + " summer_69([2, 1, 6, 9, 11]) --> 14" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [], + "source": [ + "def summer_69(arr):\n", + " total = 0\n", + " add = True\n", + " for num in arr:\n", + " while add:\n", + " if num != 6:\n", + " total += num\n", + " break\n", + " else:\n", + " add = False\n", + " while not add:\n", + " if num != 9:\n", + " break\n", + " else:\n", + " add = True\n", + " break\n", + " return total" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "summer_69([1, 3, 5])" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "summer_69([4, 5, 6, 7, 8, 9])" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "14" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "summer_69([2, 1, 6, 9, 11])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# CHALLENGING PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order\n", + "\n", + " spy_game([1,2,4,0,0,7,5]) --> True\n", + " spy_game([1,0,2,4,0,5,7]) --> True\n", + " spy_game([1,7,2,0,4,5,0]) --> False\n" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "def spy_game(nums):\n", + "\n", + " code = [0,0,7,'x']\n", + " \n", + " for num in nums:\n", + " if num == code[0]:\n", + " code.pop(0) # code.remove(num) also works\n", + " \n", + " return len(code) == 1" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "spy_game([1,2,4,0,0,7,5])" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "spy_game([1,0,2,4,0,5,7])" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "spy_game([1,7,2,0,4,5,0])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### COUNT PRIMES: Write a function that returns the *number* of prime numbers that exist up to and including a given number\n", + " count_primes(100) --> 25\n", + "\n", + "By convention, 0 and 1 are not prime." + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [], + "source": [ + "def count_primes(num):\n", + " primes = [2]\n", + " x = 3\n", + " if num < 2: # for the case of num = 0 or 1\n", + " return 0\n", + " while x <= num:\n", + " for y in range(3,x,2): # test all odd factors up to x-1\n", + " if x%y == 0:\n", + " x += 2\n", + " break\n", + " else:\n", + " primes.append(x)\n", + " x += 2\n", + " print(primes)\n", + " return len(primes)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n" + ] + }, + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "count_primes(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "BONUS: Here's a faster version that makes use of the prime numbers we're collecting as we go!" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [], + "source": [ + "def count_primes2(num):\n", + " primes = [2]\n", + " x = 3\n", + " if num < 2:\n", + " return 0\n", + " while x <= num:\n", + " for y in primes: # use the primes list!\n", + " if x%y == 0:\n", + " x += 2\n", + " break\n", + " else:\n", + " primes.append(x)\n", + " x += 2\n", + " print(primes)\n", + " return len(primes)" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n" + ] + }, + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "count_primes2(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Just for fun:\n", + "#### PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter\n", + " print_big('a')\n", + " \n", + " out: * \n", + " * *\n", + " *****\n", + " * *\n", + " * *\n", + "HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns.
For purposes of this exercise, it's ok if your dictionary stops at \"E\"." + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [], + "source": [ + "def print_big(letter):\n", + " patterns = {1:' * ',2:' * * ',3:'* *',4:'*****',5:'**** ',6:' * ',7:' * ',8:'* * ',9:'* '}\n", + " alphabet = {'A':[1,2,4,3,3],'B':[5,3,5,3,5],'C':[4,9,9,9,4],'D':[5,3,3,3,5],'E':[4,9,4,9,4]}\n", + " for pattern in alphabet[letter.upper()]:\n", + " print(patterns[pattern])" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " * \n", + " * * \n", + "*****\n", + "* *\n", + "* *\n" + ] + } + ], + "source": [ + "print_big('a')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/01-Methods.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/01-Methods.ipynb new file mode 100644 index 0000000..fde90b4 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/01-Methods.ipynb @@ -0,0 +1,178 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Methods\n", + "\n", + "We've already seen a few example of methods when learning about Object and Data Structure Types in Python. Methods are essentially functions built into objects. Later on in the course we will learn about how to create our own objects and methods using Object Oriented Programming (OOP) and classes.\n", + "\n", + "Methods perform specific actions on an object and can also take arguments, just like a function. This lecture will serve as just a brief introduction to methods and get you thinking about overall design methods that we will touch back upon when we reach OOP in the course.\n", + "\n", + "Methods are in the form:\n", + "\n", + " object.method(arg1,arg2,etc...)\n", + " \n", + "You'll later see that we can think of methods as having an argument 'self' referring to the object itself. You can't see this argument but we will be using it later on in the course during the OOP lectures.\n", + "\n", + "Let's take a quick look at what an example of the various methods a list has:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# Create a simple list\n", + "lst = [1,2,3,4,5]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fortunately, with iPython and the Jupyter Notebook we can quickly see all the possible methods using the tab key. The methods for a list are:\n", + "\n", + "* append\n", + "* count\n", + "* extend\n", + "* insert\n", + "* pop\n", + "* remove\n", + "* reverse\n", + "* sort\n", + "\n", + "Let's try out a few of them:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "append() allows us to add elements to the end of a list:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "lst.append(6)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5, 6]" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Now how about count()? The count() method will count the number of occurrences of an element in a list." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check how many times 2 shows up in the list\n", + "lst.count(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can always use Shift+Tab in the Jupyter Notebook to get more help about the method. In general Python you can use the help() function: " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on built-in function count:\n", + "\n", + "count(...) method of builtins.list instance\n", + " L.count(value) -> integer -- return number of occurrences of value\n", + "\n" + ] + } + ], + "source": [ + "help(lst.count)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Feel free to play around with the rest of the methods for a list. Later on in this section your quiz will involve using help and Google searching for methods of different types of objects!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! By this lecture you should feel comfortable calling methods of objects in Python!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/02-Functions.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/02-Functions.ipynb new file mode 100644 index 0000000..1e9243d --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/02-Functions.ipynb @@ -0,0 +1,391 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Functions\n", + "\n", + "## Introduction to Functions\n", + "\n", + "This lecture will consist of explaining what a function is in Python and how to create one. Functions will be one of our main building blocks when we construct larger and larger amounts of code to solve problems.\n", + "\n", + "**So what is a function?**\n", + "\n", + "Formally, a function is a useful device that groups together a set of statements so they can be run more than once. They can also let us specify parameters that can serve as inputs to the functions.\n", + "\n", + "On a more fundamental level, functions allow us to not have to repeatedly write the same code again and again. If you remember back to the lessons on strings and lists, remember that we used a function len() to get the length of a string. Since checking the length of a sequence is a common task you would want to write a function that can do this repeatedly at command.\n", + "\n", + "Functions will be one of most basic levels of reusing code in Python, and it will also allow us to start thinking of program design (we will dive much deeper into the ideas of design when we learn about Object Oriented Programming)." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## def Statements\n", + "\n", + "Let's see how to build out a function's syntax in Python. It has the following form:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def name_of_function(arg1,arg2):\n", + " '''\n", + " This is where the function's Document String (docstring) goes\n", + " '''\n", + " # Do stuff here\n", + " # Return desired result" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We begin with def then a space followed by the name of the function. Try to keep names relevant, for example len() is a good name for a length() function. Also be careful with names, you wouldn't want to call a function the same name as a [built-in function in Python](https://docs.python.org/2/library/functions.html) (such as len).\n", + "\n", + "Next come a pair of parentheses with a number of arguments separated by a comma. These arguments are the inputs for your function. You'll be able to use these inputs in your function and reference them. After this you put a colon.\n", + "\n", + "Now here is the important step, you must indent to begin the code inside your function correctly. Python makes use of *whitespace* to organize code. Lots of other programing languages do not do this, so keep that in mind.\n", + "\n", + "Next you'll see the docstring, this is where you write a basic description of the function. Using iPython and iPython Notebooks, you'll be able to read these docstrings by pressing Shift+Tab after a function name. Docstrings are not necessary for simple functions, but it's good practice to put them in so you or other people can easily understand the code you write.\n", + "\n", + "After all this you begin writing the code you wish to execute.\n", + "\n", + "The best way to learn functions is by going through examples. So let's try to go through examples that relate back to the various objects and data structures we learned about before." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Example 1: A simple print 'hello' function" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "def say_hello():\n", + " print('hello')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Call the function:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "hello\n" + ] + } + ], + "source": [ + "say_hello()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Example 2: A simple greeting function\n", + "Let's write a function that greets people with their name." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "def greeting(name):\n", + " print('Hello %s' %(name))" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello Jose\n" + ] + } + ], + "source": [ + "greeting('Jose')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Using return\n", + "Let's see some example that use a return statement. return allows a function to *return* a result that can then be stored as a variable, or used in whatever manner a user wants.\n", + "\n", + "### Example 3: Addition function" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "def add_num(num1,num2):\n", + " return num1+num2" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "add_num(4,5)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "# Can also save as variable due to return\n", + "result = add_num(4,5)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "9\n" + ] + } + ], + "source": [ + "print(result)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What happens if we input two strings?" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'onetwo'" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "add_num('one','two')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that because we don't declare variable types in Python, this function could be used to add numbers or sequences together! We'll later learn about adding in checks to make sure a user puts in the correct arguments into a function.\n", + "\n", + "Let's also start using break, continue, and pass statements in our code. We introduced these during the while lecture." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "Finally let's go over a full example of creating a function to check if a number is prime (a common interview exercise).\n", + "\n", + "We know a number is prime if that number is only evenly divisible by 1 and itself. Let's write our first version of the function to check all the numbers from 1 to N and perform modulo checks." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def is_prime(num):\n", + " '''\n", + " Naive method of checking for primes. \n", + " '''\n", + " for n in range(2,num):\n", + " if num % n == 0:\n", + " print(num,'is not prime')\n", + " break\n", + " else: # If never mod zero, then prime\n", + " print(num,'is prime!')" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "16 is not prime\n" + ] + } + ], + "source": [ + "is_prime(16)" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "17 is prime!\n" + ] + } + ], + "source": [ + "is_prime(17)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how the else lines up under for and not if. This is because we want the for loop to exhaust all possibilities in the range before printing our number is prime.\n", + "\n", + "Also note how we break the code after the first print statement. As soon as we determine that a number is not prime we break out of the for loop.\n", + "\n", + "We can actually improve this function by only checking to the square root of the target number, and by disregarding all even numbers after checking for 2. We'll also switch to returning a boolean value to get an example of using return statements:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "import math\n", + "\n", + "def is_prime2(num):\n", + " '''\n", + " Better method of checking for primes. \n", + " '''\n", + " if num % 2 == 0 and num > 2: \n", + " return False\n", + " for i in range(3, int(math.sqrt(num)) + 1, 2):\n", + " if num % i == 0:\n", + " return False\n", + " return True" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "is_prime2(18)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Why don't we have any break statements? It should be noted that as soon as a function *returns* something, it shuts down. A function can deliver multiple print statements, but it will only obey one return." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! You should now have a basic understanding of creating your own functions to save yourself from repeatedly writing code!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/03-Function Practice Exercises.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/03-Function Practice Exercises.ipynb new file mode 100644 index 0000000..cb906db --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/03-Function Practice Exercises.ipynb @@ -0,0 +1,715 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Function Practice Exercises\n", + "\n", + "Problems are arranged in increasing difficulty:\n", + "* Warmup - these can be solved using basic comparisons and methods\n", + "* Level 1 - these may involve if/then conditional statements and simple methods\n", + "* Level 2 - these may require iterating over sequences, usually with some kind of loop\n", + "* Challenging - these will take some creativity to solve" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## WARMUP SECTION:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers *if* both numbers are even, but returns the greater if one or both numbers are odd\n", + " lesser_of_two_evens(2,4) --> 2\n", + " lesser_of_two_evens(2,5) --> 5" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def lesser_of_two_evens(a,b):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,4)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter\n", + " animal_crackers('Levelheaded Llama') --> True\n", + " animal_crackers('Crazy Kangaroo') --> False" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def animal_crackers(text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "animal_crackers('Levelheaded Llama')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "animal_crackers('Crazy Kangaroo')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 *or* if one of the integers is 20. If not, return False\n", + "\n", + " makes_twenty(20,10) --> True\n", + " makes_twenty(12,8) --> True\n", + " makes_twenty(2,3) --> False" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def makes_twenty(n1,n2):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "makes_twenty(20,10)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "makes_twenty(2,3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 1 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name\n", + " \n", + " old_macdonald('macdonald') --> MacDonald\n", + " \n", + "Note: `'macdonald'.capitalize()` returns `'Macdonald'`" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def old_macdonald(name):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "old_macdonald('macdonald')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MASTER YODA: Given a sentence, return a sentence with the words reversed\n", + "\n", + " master_yoda('I am home') --> 'home am I'\n", + " master_yoda('We are ready') --> 'ready are We'\n", + " \n", + "Note: The .join() method may be useful here. The .join() method allows you to join together strings in a list with some connector string. For example, some uses of the .join() method:\n", + "\n", + " >>> \"--\".join(['a','b','c'])\n", + " >>> 'a--b--c'\n", + "\n", + "This means if you had a list of words you wanted to turn back into a sentence, you could just join them with a single space string:\n", + "\n", + " >>> \" \".join(['Hello','world'])\n", + " >>> \"Hello world\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def master_yoda(text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "master_yoda('I am home')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "master_yoda('We are ready')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200\n", + "\n", + " almost_there(90) --> True\n", + " almost_there(104) --> True\n", + " almost_there(150) --> False\n", + " almost_there(209) --> True\n", + " \n", + "NOTE: `abs(num)` returns the absolute value of a number" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def almost_there(n):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "almost_there(104)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "almost_there(150)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "almost_there(209)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 2 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### FIND 33: \n", + "\n", + "Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.\n", + "\n", + " has_33([1, 3, 3]) → True\n", + " has_33([1, 3, 1, 3]) → False\n", + " has_33([3, 1, 3]) → False" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def has_33(nums):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "has_33([1, 3, 3])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "has_33([1, 3, 1, 3])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Check\n", + "has_33([3, 1, 3])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### PAPER DOLL: Given a string, return a string where for every character in the original there are three characters\n", + " paper_doll('Hello') --> 'HHHeeellllllooo'\n", + " paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def paper_doll(text):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "paper_doll('Hello')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "paper_doll('Mississippi')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 *and* there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'\n", + " blackjack(5,6,7) --> 18\n", + " blackjack(9,9,9) --> 'BUST'\n", + " blackjack(9,9,11) --> 19" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def blackjack(a,b,c):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "blackjack(5,6,7)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "blackjack(9,9,9)" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "blackjack(9,9,11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.\n", + " \n", + " summer_69([1, 3, 5]) --> 9\n", + " summer_69([4, 5, 6, 7, 8, 9]) --> 9\n", + " summer_69([2, 1, 6, 9, 11]) --> 14" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def summer_69(arr):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "summer_69([1, 3, 5])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "summer_69([4, 5, 6, 7, 8, 9])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "summer_69([2, 1, 6, 9, 11])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# CHALLENGING PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order\n", + "\n", + " spy_game([1,2,4,0,0,7,5]) --> True\n", + " spy_game([1,0,2,4,0,5,7]) --> True\n", + " spy_game([1,7,2,0,4,5,0]) --> False\n" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def spy_game(nums):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "spy_game([1,2,4,0,0,7,5])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "spy_game([1,0,2,4,0,5,7])" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "spy_game([1,7,2,0,4,5,0])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### COUNT PRIMES: Write a function that returns the *number* of prime numbers that exist up to and including a given number\n", + " count_primes(100) --> 25\n", + "\n", + "By convention, 0 and 1 are not prime." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def count_primes(num):\n", + " pass\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Check\n", + "count_primes(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Just for fun:\n", + "#### PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter\n", + " print_big('a')\n", + " \n", + " out: * \n", + " * *\n", + " *****\n", + " * *\n", + " * *\n", + "HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns.
For purposes of this exercise, it's ok if your dictionary stops at \"E\"." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def print_big(letter):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "print_big('a')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/04-Function Practice Exercises - Solutions.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/04-Function Practice Exercises - Solutions.ipynb new file mode 100644 index 0000000..33ea1ee --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/04-Function Practice Exercises - Solutions.ipynb @@ -0,0 +1,1106 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Function Practice Exercises - Solutions\n", + "\n", + "Problems are arranged in increasing difficulty:\n", + "* Warmup - these can be solved using basic comparisons and methods\n", + "* Level 1 - these may involve if/then conditional statements and simple methods\n", + "* Level 2 - these may require iterating over sequences, usually with some kind of loop\n", + "* Challenging - these will take some creativity to solve" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## WARMUP SECTION:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### LESSER OF TWO EVENS: Write a function that returns the lesser of two given numbers *if* both numbers are even, but returns the greater if one or both numbers are odd\n", + " lesser_of_two_evens(2,4) --> 2\n", + " lesser_of_two_evens(2,5) --> 5" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def lesser_of_two_evens(a,b):\n", + " if a%2 == 0 and b%2 == 0:\n", + " return min(a,b)\n", + " else:\n", + " return max(a,b)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,4)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "lesser_of_two_evens(2,5)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ANIMAL CRACKERS: Write a function takes a two-word string and returns True if both words begin with same letter\n", + " animal_crackers('Levelheaded Llama') --> True\n", + " animal_crackers('Crazy Kangaroo') --> False" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "def animal_crackers(text):\n", + " wordlist = text.split()\n", + " return wordlist[0][0] == wordlist[1][0]" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "animal_crackers('Levelheaded Llama')" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "animal_crackers('Crazy Kangaroo')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MAKES TWENTY: Given two integers, return True if the sum of the integers is 20 *or* if one of the integers is 20. If not, return False\n", + "\n", + " makes_twenty(20,10) --> True\n", + " makes_twenty(12,8) --> True\n", + " makes_twenty(2,3) --> False" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "def makes_twenty(n1,n2):\n", + " return (n1+n2)==20 or n1==20 or n2==20" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "makes_twenty(20,10)" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "makes_twenty(12,8)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "#Check\n", + "makes_twenty(2,3)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 1 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### OLD MACDONALD: Write a function that capitalizes the first and fourth letters of a name\n", + " \n", + " old_macdonald('macdonald') --> MacDonald\n", + " \n", + "Note: `'macdonald'.capitalize()` returns `'Macdonald'`" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def old_macdonald(name):\n", + " if len(name) > 3:\n", + " return name[:3].capitalize() + name[3:].capitalize()\n", + " else:\n", + " return 'Name is too short!'" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'MacDonald'" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "old_macdonald('macdonald')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### MASTER YODA: Given a sentence, return a sentence with the words reversed\n", + "\n", + " master_yoda('I am home') --> 'home am I'\n", + " master_yoda('We are ready') --> 'ready are We'" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def master_yoda(text):\n", + " return ' '.join(text.split()[::-1])" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'home am I'" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "master_yoda('I am home')" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'ready are We'" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "master_yoda('We are ready')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### ALMOST THERE: Given an integer n, return True if n is within 10 of either 100 or 200\n", + "\n", + " almost_there(90) --> True\n", + " almost_there(104) --> True\n", + " almost_there(150) --> False\n", + " almost_there(209) --> True\n", + " \n", + "NOTE: `abs(num)` returns the absolute value of a number" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "def almost_there(n):\n", + " return ((abs(100 - n) <= 10) or (abs(200 - n) <= 10))" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(90)" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(104)" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 19, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(150)" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "almost_there(209)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# LEVEL 2 PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### FIND 33: \n", + "\n", + "Given a list of ints, return True if the array contains a 3 next to a 3 somewhere.\n", + "\n", + " has_33([1, 3, 3]) → True\n", + " has_33([1, 3, 1, 3]) → False\n", + " has_33([3, 1, 3]) → False" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [], + "source": [ + "def has_33(nums):\n", + " for i in range(0, len(nums)-1):\n", + " \n", + " # nicer looking alternative in commented code\n", + " #if nums[i] == 3 and nums[i+1] == 3:\n", + " \n", + " if nums[i:i+2] == [3,3]:\n", + " return True \n", + " \n", + " return False" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "has_33([1, 3, 3])" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "has_33([1, 3, 1, 3])" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 24, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "has_33([3, 1, 3])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### PAPER DOLL: Given a string, return a string where for every character in the original there are three characters\n", + " paper_doll('Hello') --> 'HHHeeellllllooo'\n", + " paper_doll('Mississippi') --> 'MMMiiissssssiiippppppiii'" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": {}, + "outputs": [], + "source": [ + "def paper_doll(text):\n", + " result = ''\n", + " for char in text:\n", + " result += char * 3\n", + " return result" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'HHHeeellllllooo'" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "paper_doll('Hello')" + ] + }, + { + "cell_type": "code", + "execution_count": 27, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'MMMiiissssssiiissssssiiippppppiii'" + ] + }, + "execution_count": 27, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "paper_doll('Mississippi')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### BLACKJACK: Given three integers between 1 and 11, if their sum is less than or equal to 21, return their sum. If their sum exceeds 21 *and* there's an eleven, reduce the total sum by 10. Finally, if the sum (even after adjustment) exceeds 21, return 'BUST'\n", + " blackjack(5,6,7) --> 18\n", + " blackjack(9,9,9) --> 'BUST'\n", + " blackjack(9,9,11) --> 19" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [], + "source": [ + "def blackjack(a,b,c):\n", + " \n", + " if sum((a,b,c)) <= 21:\n", + " return sum((a,b,c))\n", + " elif sum((a,b,c)) <=31 and 11 in (a,b,c):\n", + " return sum((a,b,c)) - 10\n", + " else:\n", + " return 'BUST'" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "18" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "blackjack(5,6,7)" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'BUST'" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "blackjack(9,9,9)" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "19" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "blackjack(9,9,11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SUMMER OF '69: Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.\n", + " \n", + " summer_69([1, 3, 5]) --> 9\n", + " summer_69([4, 5, 6, 7, 8, 9]) --> 9\n", + " summer_69([2, 1, 6, 9, 11]) --> 14" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [], + "source": [ + "def summer_69(arr):\n", + " total = 0\n", + " add = True\n", + " for num in arr:\n", + " while add:\n", + " if num != 6:\n", + " total += num\n", + " break\n", + " else:\n", + " add = False\n", + " while not add:\n", + " if num != 9:\n", + " break\n", + " else:\n", + " add = True\n", + " break\n", + " return total" + ] + }, + { + "cell_type": "code", + "execution_count": 33, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 33, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "summer_69([1, 3, 5])" + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "summer_69([4, 5, 6, 7, 8, 9])" + ] + }, + { + "cell_type": "code", + "execution_count": 35, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "14" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "summer_69([2, 1, 6, 9, 11])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# CHALLENGING PROBLEMS" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### SPY GAME: Write a function that takes in a list of integers and returns True if it contains 007 in order\n", + "\n", + " spy_game([1,2,4,0,0,7,5]) --> True\n", + " spy_game([1,0,2,4,0,5,7]) --> True\n", + " spy_game([1,7,2,0,4,5,0]) --> False\n" + ] + }, + { + "cell_type": "code", + "execution_count": 36, + "metadata": {}, + "outputs": [], + "source": [ + "def spy_game(nums):\n", + "\n", + " code = [0,0,7,'x']\n", + " \n", + " for num in nums:\n", + " if num == code[0]:\n", + " code.pop(0) # code.remove(num) also works\n", + " \n", + " return len(code) == 1" + ] + }, + { + "cell_type": "code", + "execution_count": 37, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 37, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "spy_game([1,2,4,0,0,7,5])" + ] + }, + { + "cell_type": "code", + "execution_count": 38, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "spy_game([1,0,2,4,0,5,7])" + ] + }, + { + "cell_type": "code", + "execution_count": 39, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "spy_game([1,7,2,0,4,5,0])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### COUNT PRIMES: Write a function that returns the *number* of prime numbers that exist up to and including a given number\n", + " count_primes(100) --> 25\n", + "\n", + "By convention, 0 and 1 are not prime." + ] + }, + { + "cell_type": "code", + "execution_count": 40, + "metadata": {}, + "outputs": [], + "source": [ + "def count_primes(num):\n", + " primes = [2]\n", + " x = 3\n", + " if num < 2: # for the case of num = 0 or 1\n", + " return 0\n", + " while x <= num:\n", + " for y in range(3,x,2): # test all odd factors up to x-1\n", + " if x%y == 0:\n", + " x += 2\n", + " break\n", + " else:\n", + " primes.append(x)\n", + " x += 2\n", + " print(primes)\n", + " return len(primes)\n", + " " + ] + }, + { + "cell_type": "code", + "execution_count": 41, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n" + ] + }, + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 41, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "count_primes(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "BONUS: Here's a faster version that makes use of the prime numbers we're collecting as we go!" + ] + }, + { + "cell_type": "code", + "execution_count": 42, + "metadata": {}, + "outputs": [], + "source": [ + "def count_primes2(num):\n", + " primes = [2]\n", + " x = 3\n", + " if num < 2:\n", + " return 0\n", + " while x <= num:\n", + " for y in primes: # use the primes list!\n", + " if x%y == 0:\n", + " x += 2\n", + " break\n", + " else:\n", + " primes.append(x)\n", + " x += 2\n", + " print(primes)\n", + " return len(primes)" + ] + }, + { + "cell_type": "code", + "execution_count": 43, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97]\n" + ] + }, + { + "data": { + "text/plain": [ + "25" + ] + }, + "execution_count": 43, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "count_primes2(100)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "-----\n", + "### Just for fun, not a real problem :)\n", + "\n", + "#### PRINT BIG: Write a function that takes in a single letter, and returns a 5x5 representation of that letter\n", + " print_big('a')\n", + " \n", + " out: * \n", + " * *\n", + " *****\n", + " * *\n", + " * *\n", + "HINT: Consider making a dictionary of possible patterns, and mapping the alphabet to specific 5-line combinations of patterns.
For purposes of this exercise, it's ok if your dictionary stops at \"E\"." + ] + }, + { + "cell_type": "code", + "execution_count": 44, + "metadata": {}, + "outputs": [], + "source": [ + "def print_big(letter):\n", + " patterns = {1:' * ',2:' * * ',3:'* *',4:'*****',5:'**** ',6:' * ',7:' * ',8:'* * ',9:'* '}\n", + " alphabet = {'A':[1,2,4,3,3],'B':[5,3,5,3,5],'C':[4,9,9,9,4],'D':[5,3,3,3,5],'E':[4,9,4,9,4]}\n", + " for pattern in alphabet[letter.upper()]:\n", + " print(patterns[pattern])" + ] + }, + { + "cell_type": "code", + "execution_count": 45, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " * \n", + " * * \n", + "*****\n", + "* *\n", + "* *\n" + ] + } + ], + "source": [ + "print_big('a')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/05-Lambda-Expressions-Map-and-Filter.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/05-Lambda-Expressions-Map-and-Filter.ipynb new file mode 100644 index 0000000..4243e68 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/05-Lambda-Expressions-Map-and-Filter.ipynb @@ -0,0 +1,569 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Lambda Expressions, Map, and Filter\n", + "\n", + "Now its time to quickly learn about two built in functions, filter and map. Once we learn about how these operate, we can learn about the lambda expression, which will come in handy when you begin to develop your skills further!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## map function\n", + "\n", + "The **map** function allows you to \"map\" a function to an iterable object. That is to say you can quickly call the same function to every item in an iterable, such as a list. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def square(num):\n", + " return num**2" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "my_nums = [1,2,3,4,5]" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "map(square,my_nums)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 4, 9, 16, 25]" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# To get the results, either iterate through map() \n", + "# or just cast to a list\n", + "list(map(square,my_nums))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The functions can also be more complex" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def splicer(mystring):\n", + " if len(mystring) % 2 == 0:\n", + " return 'even'\n", + " else:\n", + " return mystring[0]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "mynames = ['John','Cindy','Sarah','Kelly','Mike']" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "['even', 'C', 'S', 'K', 'even']" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(map(splicer,mynames))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## filter function\n", + "\n", + "The filter function returns an iterator yielding those items of iterable for which function(item)\n", + "is true. Meaning you need to filter by a function that returns either True or False. Then passing that into filter (along with your iterable) and you will get back only the results that would return True when passed to the function." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def check_even(num):\n", + " return num % 2 == 0 " + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "nums = [0,1,2,3,4,5,6,7,8,9,10]" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "filter(check_even,nums)" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(filter(check_even,nums))" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## lambda expression\n", + "\n", + "One of Pythons most useful (and for beginners, confusing) tools is the lambda expression. lambda expressions allow us to create \"anonymous\" functions. This basically means we can quickly make ad-hoc functions without needing to properly define a function using def.\n", + "\n", + "Function objects returned by running lambda expressions work exactly the same as those created and assigned by defs. There is key difference that makes lambda useful in specialized roles:\n", + "\n", + "**lambda's body is a single expression, not a block of statements.**\n", + "\n", + "* The lambda's body is similar to what we would put in a def body's return statement. We simply type the result as an expression instead of explicitly returning it. Because it is limited to an expression, a lambda is less general that a def. We can only squeeze design, to limit program nesting. lambda is designed for coding simple functions, and def handles the larger tasks." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Lets slowly break down a lambda expression by deconstructing a function:" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def square(num):\n", + " result = num**2\n", + " return result" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We could simplify it:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def square(num):\n", + " return num**2" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 20, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We could actually even write this all on one line." + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def square(num): return num**2" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 22, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This is the form a function that a lambda expression intends to replicate. A lambda expression can then be written as:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 23, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda num: num ** 2" + ] + }, + { + "cell_type": "code", + "execution_count": 25, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# You wouldn't usually assign a name to a lambda expression, this is just for demonstration!\n", + "square = lambda num: num **2" + ] + }, + { + "cell_type": "code", + "execution_count": 26, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 26, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "square(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So why would use this? Many function calls need a function passed in, such as map and filter. Often you only need to use the function you are passing in once, so instead of formally defining it, you just use the lambda expression. Let's repeat some of the examples from above with a lambda expression" + ] + }, + { + "cell_type": "code", + "execution_count": 29, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 4, 9, 16, 25]" + ] + }, + "execution_count": 29, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(map(lambda num: num ** 2, my_nums))" + ] + }, + { + "cell_type": "code", + "execution_count": 30, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[0, 2, 4, 6, 8, 10]" + ] + }, + "execution_count": 30, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "list(filter(lambda n: n % 2 == 0,nums))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here are a few more examples, keep in mind the more comples a function is, the harder it is to translate into a lambda expression, meaning sometimes its just easier (and often the only way) to create the def keyword function." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "** Lambda expression for grabbing the first character of a string: **" + ] + }, + { + "cell_type": "code", + "execution_count": 31, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 31, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda s: s[0]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "** Lambda expression for reversing a string: **" + ] + }, + { + "cell_type": "code", + "execution_count": 32, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 32, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda s: s[::-1]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You can even pass in multiple arguments into a lambda expression. Again, keep in mind that not every function can be translated into a lambda expression." + ] + }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + ">" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lambda x,y : x + y" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "You will find yourself using lambda expressions often with certain non-built-in libraries, for example the pandas library for data analysis works very well with lambda expressions." + ] + } + ], + "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.1" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/06-Nested Statements and Scope.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/06-Nested Statements and Scope.ipynb new file mode 100644 index 0000000..c3871db --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/06-Nested Statements and Scope.ipynb @@ -0,0 +1,357 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Nested Statements and Scope \n", + "\n", + "Now that we have gone over writing our own functions, it's important to understand how Python deals with the variable names you assign. When you create a variable name in Python the name is stored in a *name-space*. Variable names also have a *scope*, the scope determines the visibility of that variable name to other parts of your code.\n", + "\n", + "Let's start with a quick thought experiment; imagine the following code:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "x = 25\n", + "\n", + "def printer():\n", + " x = 50\n", + " return x\n", + "\n", + "# print(x)\n", + "# print(printer())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What do you imagine the output of printer() is? 25 or 50? What is the output of print x? 25 or 50?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "25\n" + ] + } + ], + "source": [ + "print(x)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "50\n" + ] + } + ], + "source": [ + "print(printer())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Interesting! But how does Python know which **x** you're referring to in your code? This is where the idea of scope comes in. Python has a set of rules it follows to decide what variables (such as **x** in this case) you are referencing in your code. Lets break down the rules:" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "This idea of scope in your code is very important to understand in order to properly assign and call variable names. \n", + "\n", + "In simple terms, the idea of scope can be described by 3 general rules:\n", + "\n", + "1. Name assignments will create or change local names by default.\n", + "2. Name references search (at most) four scopes, these are:\n", + " * local\n", + " * enclosing functions\n", + " * global\n", + " * built-in\n", + "3. Names declared in global and nonlocal statements map assigned names to enclosing module and function scopes.\n", + "\n", + "\n", + "The statement in #2 above can be defined by the LEGB rule.\n", + "\n", + "**LEGB Rule:**\n", + "\n", + "L: Local — Names assigned in any way within a function (def or lambda), and not declared global in that function.\n", + "\n", + "E: Enclosing function locals — Names in the local scope of any and all enclosing functions (def or lambda), from inner to outer.\n", + "\n", + "G: Global (module) — Names assigned at the top-level of a module file, or declared global in a def within the file.\n", + "\n", + "B: Built-in (Python) — Names preassigned in the built-in names module : open, range, SyntaxError,..." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Quick examples of LEGB\n", + "\n", + "### Local" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [], + "source": [ + "# x is local here:\n", + "f = lambda x:x**2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Enclosing function locals\n", + "This occurs when we have a function inside a function (nested functions)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Hello Sammy\n" + ] + } + ], + "source": [ + "name = 'This is a global name'\n", + "\n", + "def greet():\n", + " # Enclosing function\n", + " name = 'Sammy'\n", + " \n", + " def hello():\n", + " print('Hello '+name)\n", + " \n", + " hello()\n", + "\n", + "greet()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how Sammy was used, because the hello() function was enclosed inside of the greet function!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Global\n", + "Luckily in Jupyter a quick way to test for global variables is to see if another cell recognizes the variable!" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "This is a global name\n" + ] + } + ], + "source": [ + "print(name)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Built-in\n", + "These are the built-in function names in Python (don't overwrite these!)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "len" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Local Variables\n", + "When you declare variables inside a function definition, they are not related in any way to other variables with the same names used outside the function - i.e. variable names are local to the function. This is called the scope of the variable. All variables have the scope of the block they are declared in starting from the point of definition of the name.\n", + "\n", + "Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "x is 50\n", + "Changed local x to 2\n", + "x is still 50\n" + ] + } + ], + "source": [ + "x = 50\n", + "\n", + "def func(x):\n", + " print('x is', x)\n", + " x = 2\n", + " print('Changed local x to', x)\n", + "\n", + "func(x)\n", + "print('x is still', x)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The first time that we print the value of the name **x** with the first line in the function’s body, Python uses the value of the parameter declared in the main block, above the function definition.\n", + "\n", + "Next, we assign the value 2 to **x**. The name **x** is local to our function. So, when we change the value of **x** in the function, the **x** defined in the main block remains unaffected.\n", + "\n", + "With the last print statement, we display the value of **x** as defined in the main block, thereby confirming that it is actually unaffected by the local assignment within the previously called function.\n", + "\n", + "## The global statement\n", + "If you want to assign a value to a name defined at the top level of the program (i.e. not inside any kind of scope such as functions or classes), then you have to tell Python that the name is not local, but it is global. We do this using the global statement. It is impossible to assign a value to a variable defined outside a function without the global statement.\n", + "\n", + "You can use the values of such variables defined outside the function (assuming there is no variable with the same name within the function). However, this is not encouraged and should be avoided since it becomes unclear to the reader of the program as to where that variable’s definition is. Using the global statement makes it amply clear that the variable is defined in an outermost block.\n", + "\n", + "Example:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Before calling func(), x is: 50\n", + "This function is now using the global x!\n", + "Because of global x is: 50\n", + "Ran func(), changed global x to 2\n", + "Value of x (outside of func()) is: 2\n" + ] + } + ], + "source": [ + "x = 50\n", + "\n", + "def func():\n", + " global x\n", + " print('This function is now using the global x!')\n", + " print('Because of global x is: ', x)\n", + " x = 2\n", + " print('Ran func(), changed global x to', x)\n", + "\n", + "print('Before calling func(), x is: ', x)\n", + "func()\n", + "print('Value of x (outside of func()) is: ', x)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "The global statement is used to declare that **x** is a global variable - hence, when we assign a value to **x** inside the function, that change is reflected when we use the value of **x** in the main block.\n", + "\n", + "You can specify more than one global variable using the same global statement e.g. global x, y, z." + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Conclusion\n", + "You should now have a good understanding of Scope (you may have already intuitively felt right about Scope which is great!) One last mention is that you can use the **globals()** and **locals()** functions to check what are your current local and global variables.\n", + "\n", + "Another thing to keep in mind is that everything in Python is an object! I can assign variables to functions just like I can with numbers! We will go over this again in the decorator section of the course!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/07-args and kwargs.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/07-args and kwargs.ipynb new file mode 100644 index 0000000..47fa02a --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/07-args and kwargs.ipynb @@ -0,0 +1,272 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# `*args` and `**kwargs`\n", + "\n", + "Work with Python long enough, and eventually you will encounter `*args` and `**kwargs`. These strange terms show up as parameters in function definitions. What do they do? Let's review a simple function:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "5.0" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def myfunc(a,b):\n", + " return sum((a,b))*.05\n", + "\n", + "myfunc(40,60)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This function returns 5% of the sum of **a** and **b**. In this example, **a** and **b** are *positional* arguments; that is, 40 is assigned to **a** because it is the first argument, and 60 to **b**. Notice also that to work with multiple positional arguments in the `sum()` function we had to pass them in as a tuple.\n", + "\n", + "What if we want to work with more than two numbers? One way would be to assign a *lot* of parameters, and give each one a default value." + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "6.0" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def myfunc(a=0,b=0,c=0,d=0,e=0):\n", + " return sum((a,b,c,d,e))*.05\n", + "\n", + "myfunc(40,60,20)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Obviously this is not a very efficient solution, and that's where `*args` comes in.\n", + "\n", + "## `*args`\n", + "\n", + "When a function parameter starts with an asterisk, it allows for an *arbitrary number* of arguments, and the function takes them in as a tuple of values. Rewriting the above function:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "6.0" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def myfunc(*args):\n", + " return sum(args)*.05\n", + "\n", + "myfunc(40,60,20)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how passing the keyword \"args\" into the `sum()` function did the same thing as a tuple of arguments.\n", + "\n", + "It is worth noting that the word \"args\" is itself arbitrary - any word will do so long as it's preceded by an asterisk. To demonstrate this:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "6.0" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def myfunc(*spam):\n", + " return sum(spam)*.05\n", + "\n", + "myfunc(40,60,20)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `**kwargs`\n", + "\n", + "Similarly, Python offers a way to handle arbitrary numbers of *keyworded* arguments. Instead of creating a tuple of values, `**kwargs` builds a dictionary of key/value pairs. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "My favorite fruit is pineapple\n" + ] + } + ], + "source": [ + "def myfunc(**kwargs):\n", + " if 'fruit' in kwargs:\n", + " print(f\"My favorite fruit is {kwargs['fruit']}\") # review String Formatting and f-strings if this syntax is unfamiliar\n", + " else:\n", + " print(\"I don't like fruit\")\n", + " \n", + "myfunc(fruit='pineapple')" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I don't like fruit\n" + ] + } + ], + "source": [ + "myfunc()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `*args` and `**kwargs` combined\n", + "\n", + "You can pass `*args` and `**kwargs` into the same function, but `*args` have to appear before `**kwargs`" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "I like eggs and spam and my favorite fruit is cherries\n", + "May I have some orange juice?\n" + ] + } + ], + "source": [ + "def myfunc(*args, **kwargs):\n", + " if 'fruit' and 'juice' in kwargs:\n", + " print(f\"I like {' and '.join(args)} and my favorite fruit is {kwargs['fruit']}\")\n", + " print(f\"May I have some {kwargs['juice']} juice?\")\n", + " else:\n", + " pass\n", + " \n", + "myfunc('eggs','spam',fruit='cherries',juice='orange')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Placing keyworded arguments ahead of positional arguments raises an exception:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "positional argument follows keyword argument (, line 1)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m myfunc(fruit='cherries',juice='orange','eggs','spam')\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m positional argument follows keyword argument\n" + ] + } + ], + "source": [ + "myfunc(fruit='cherries',juice='orange','eggs','spam')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "As with \"args\", you can use any name you'd like for keyworded arguments - \"kwargs\" is just a popular convention.\n", + "\n", + "That's it! Now you should understand how `*args` and `**kwargs` provide the flexibilty to work with arbitrary numbers of arguments!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/08-Functions and Methods Homework.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/08-Functions and Methods Homework.ipynb new file mode 100644 index 0000000..95d6109 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/08-Functions and Methods Homework.ipynb @@ -0,0 +1,386 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Functions and Methods Homework \n", + "\n", + "Complete the following questions:\n", + "____\n", + "**Write a function that computes the volume of a sphere given its radius.**\n", + "

The volume of a sphere is given as $$\\frac{4}{3} πr^3$$

" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def vol(rad):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "33.49333333333333" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "vol(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "___\n", + "**Write a function that checks whether a number is in a given range (inclusive of high and low)**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def ran_check(num,low,high):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5 is in the range between 2 and 7\n" + ] + } + ], + "source": [ + "# Check\n", + "ran_check(5,2,7)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you only wanted to return a boolean:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "def ran_bool(num,low,high):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ran_bool(3,1,10)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters.**\n", + "\n", + " Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'\n", + " Expected Output : \n", + " No. of Upper case characters : 4\n", + " No. of Lower case Characters : 33\n", + "\n", + "HINT: Two string methods that might prove useful: **.isupper()** and **.islower()**\n", + "\n", + "If you feel ambitious, explore the Collections module to solve this problem!" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "def up_low(s):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Original String : Hello Mr. Rogers, how are you this fine Tuesday?\n", + "No. of Upper case characters : 4\n", + "No. of Lower case Characters : 33\n" + ] + } + ], + "source": [ + "s = 'Hello Mr. Rogers, how are you this fine Tuesday?'\n", + "up_low(s)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that takes a list and returns a new list with unique elements of the first list.**\n", + "\n", + " Sample List : [1,1,1,1,2,2,3,3,3,3,4,5]\n", + " Unique List : [1, 2, 3, 4, 5]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "def unique_list(lst):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5]" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "unique_list([1,1,1,1,2,2,3,3,3,3,4,5])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function to multiply all the numbers in a list.**\n", + "\n", + " Sample List : [1, 2, 3, -4]\n", + " Expected Output : -24" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def multiply(numbers): \n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-24" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "multiply([1,2,3,-4])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that checks whether a passed in string is palindrome or not.**\n", + "\n", + "Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def palindrome(s):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "palindrome('helleh')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "#### Hard:\n", + "\n", + "**Write a Python function to check whether a string is pangram or not.**\n", + "\n", + " Note : Pangrams are words or sentences containing every letter of the alphabet at least once.\n", + " For example : \"The quick brown fox jumps over the lazy dog\"\n", + "\n", + "Hint: Look at the string module" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [], + "source": [ + "import string\n", + "\n", + "def ispangram(str1, alphabet=string.ascii_lowercase):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ispangram(\"The quick brown fox jumps over the lazy dog\")" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'abcdefghijklmnopqrstuvwxyz'" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "string.ascii_lowercase" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "#### Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/03-Methods and Functions/09-Functions and Methods Homework - Solutions.ipynb b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/09-Functions and Methods Homework - Solutions.ipynb new file mode 100644 index 0000000..68303e6 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/03-Methods and Functions/09-Functions and Methods Homework - Solutions.ipynb @@ -0,0 +1,417 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Functions and Methods Homework Solutions\n", + "____\n", + "**Write a function that computes the volume of a sphere given its radius.**" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "def vol(rad):\n", + " return (4/3)*(3.14)*(rad**3)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "33.49333333333333" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# Check\n", + "vol(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "___\n", + "**Write a function that checks whether a number is in a given range (inclusive of high and low)**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def ran_check(num,low,high):\n", + " #Check if num is between low and high (including low and high)\n", + " if num in range(low,high+1):\n", + " print('{} is in the range between {} and {}'.format(num,low,high))\n", + " else:\n", + " print('The number is outside the range.')" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "5 is in the range between 2 and 7\n" + ] + } + ], + "source": [ + "# Check\n", + "ran_check(5,2,7)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "If you only wanted to return a boolean:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "def ran_bool(num,low,high):\n", + " return num in range(low,high+1)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ran_bool(3,1,10)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that accepts a string and calculates the number of upper case letters and lower case letters.**\n", + "\n", + " Sample String : 'Hello Mr. Rogers, how are you this fine Tuesday?'\n", + " Expected Output : \n", + " No. of Upper case characters : 4\n", + " No. of Lower case Characters : 33\n", + "\n", + "If you feel ambitious, explore the Collections module to solve this problem!" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "def up_low(s):\n", + " d={\"upper\":0, \"lower\":0}\n", + " for c in s:\n", + " if c.isupper():\n", + " d[\"upper\"]+=1\n", + " elif c.islower():\n", + " d[\"lower\"]+=1\n", + " else:\n", + " pass\n", + " print(\"Original String : \", s)\n", + " print(\"No. of Upper case characters : \", d[\"upper\"])\n", + " print(\"No. of Lower case Characters : \", d[\"lower\"])" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Original String : Hello Mr. Rogers, how are you this fine Tuesday?\n", + "No. of Upper case characters : 4\n", + "No. of Lower case Characters : 33\n" + ] + } + ], + "source": [ + "s = 'Hello Mr. Rogers, how are you this fine Tuesday?'\n", + "up_low(s)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that takes a list and returns a new list with unique elements of the first list.**\n", + "\n", + " Sample List : [1,1,1,1,2,2,3,3,3,3,4,5]\n", + " Unique List : [1, 2, 3, 4, 5]" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "def unique_list(lst):\n", + " # Also possible to use list(set())\n", + " x = []\n", + " for a in lst:\n", + " if a not in x:\n", + " x.append(a)\n", + " return x" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "[1, 2, 3, 4, 5]" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "unique_list([1,1,1,1,2,2,3,3,3,3,4,5])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function to multiply all the numbers in a list.**\n", + "\n", + " Sample List : [1, 2, 3, -4]\n", + " Expected Output : -24" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def multiply(numbers):\n", + " total = 1\n", + " for x in numbers:\n", + " total *= x\n", + " return total" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "-24" + ] + }, + "execution_count": 12, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "multiply([1,2,3,-4])" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Write a Python function that checks whether a passed string is palindrome or not.**\n", + "\n", + "Note: A palindrome is word, phrase, or sequence that reads the same backward as forward, e.g., madam or nurses run." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def palindrome(s):\n", + " \n", + " s = s.replace(' ','') # This replaces all spaces ' ' with no space ''. (Fixes issues with strings that have spaces)\n", + " return s == s[::-1] # Check through slicing" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 14, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "palindrome('nurses run')" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "palindrome('abcba')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "____\n", + "**Hard**:\n", + "\n", + "Write a Python function to check whether a string is pangram or not.\n", + "\n", + " Note : Pangrams are words or sentences containing every letter of the alphabet at least once.\n", + " For example : \"The quick brown fox jumps over the lazy dog\"\n", + "\n", + "Hint: Look at the string module" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [], + "source": [ + "import string\n", + "\n", + "def ispangram(str1, alphabet=string.ascii_lowercase): \n", + " alphaset = set(alphabet) \n", + " return alphaset <= set(str1.lower()) " + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "ispangram(\"The quick brown fox jumps over the lazy dog\")" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'abcdefghijklmnopqrstuvwxyz'" + ] + }, + "execution_count": 18, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "string.ascii_lowercase" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/01-Milestone Project 1 - Assignment-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/01-Milestone Project 1 - Assignment-checkpoint.ipynb new file mode 100644 index 0000000..b9b4a76 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/01-Milestone Project 1 - Assignment-checkpoint.ipynb @@ -0,0 +1,62 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Milestone Project 1\n", + "## Congratulations on making it to your first milestone!\n", + "You've already learned a ton and are ready to work on a real project.\n", + "\n", + "Your assignment: Create a Tic Tac Toe game. You are free to use any IDE you like.\n", + "\n", + "Here are the requirements:\n", + "\n", + "* 2 players should be able to play the game (both sitting at the same computer)\n", + "* The board should be printed out every time a player makes a move\n", + "* You should be able to accept input of the player position and then place a symbol on the board\n", + "\n", + "Feel free to use Google to help you figure anything out (but don't just Google \"Tic Tac Toe in Python\" otherwise you won't learn anything!) Keep in mind that this project can take anywhere between several hours to several days.\n", + "\n", + "There are 4 Jupyter Notebooks related to this assignment:\n", + "\n", + "* This Assignment Notebook\n", + "* A \"Walkthrough Steps Workbook\" Notebook\n", + "* A \"Complete Walkthrough Solution\" Notebook\n", + "* An \"Advanced Solution\" Notebook\n", + "\n", + "I encourage you to just try to start the project on your own without referencing any of the notebooks. If you get stuck, check out the next lecture which is a text lecture with helpful hints and steps. If you're still stuck after that, then check out the Walkthrough Steps Workbook, which breaks up the project in steps for you to solve. Still stuck? Then check out the Complete Walkthrough Solution video for more help on approaching the project!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are parts of this that will be a struggle...and that is good! I have complete faith that if you have made it this far through the course you have all the tools and knowledge to tackle this project. Remember, it's totally open book, so take your time, do a little research, and remember:\n", + "\n", + "## HAVE FUN!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/02-Milestone Project 1 - Walkthrough Steps Workbook-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/02-Milestone Project 1 - Walkthrough Steps Workbook-checkpoint.ipynb new file mode 100644 index 0000000..81a5a45 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/02-Milestone Project 1 - Walkthrough Steps Workbook-checkpoint.ipynb @@ -0,0 +1,291 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Milestone Project 1: Walkthrough Steps Workbook\n", + "\n", + "Below is a set of steps for you to follow to try to create the Tic Tac Toe Milestone Project game!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Some suggested tools before you get started:\n", + "To take input from a user:\n", + "\n", + " player1 = input(\"Please pick a marker 'X' or 'O'\")\n", + " \n", + "Note that input() takes in a string. If you need an integer value, use\n", + "\n", + " position = int(input('Please enter a number'))\n", + " \n", + "
To clear the screen between moves:\n", + "\n", + " from IPython.display import clear_output\n", + " clear_output()\n", + " \n", + "Note that clear_output() will only work in jupyter. To clear the screen in other IDEs, consider:\n", + "\n", + " print('\\n'*100)\n", + " \n", + "This scrolls the previous board up out of view. Now on to the program!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 1: Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.**" + ] + }, + { + "cell_type": "code", + "execution_count": 87, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from IPython.display import clear_output\n", + "\n", + "def display_board(board):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'. Think about using *while* loops to continually ask until you get a correct answer.**" + ] + }, + { + "cell_type": "code", + "execution_count": 88, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def player_input():\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 3: Write a function that takes in the board list object, a marker ('X' or 'O'), and a desired position (number 1-9) and assigns it to the board.**" + ] + }, + { + "cell_type": "code", + "execution_count": 89, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def place_marker(board, marker, position):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 4: Write a function that takes in a board and a mark (X or O) and then checks to see if that mark has won. **" + ] + }, + { + "cell_type": "code", + "execution_count": 90, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def win_check(board, mark):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 5: Write a function that uses the random module to randomly decide which player goes first. You may want to lookup random.randint() Return a string of which player went first.**" + ] + }, + { + "cell_type": "code", + "execution_count": 91, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import random\n", + "def choose_first():\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 6: Write a function that returns a boolean indicating whether a space on the board is freely available.**" + ] + }, + { + "cell_type": "code", + "execution_count": 92, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def space_check(board, position):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 7: Write a function that checks if the board is full and returns a boolean value. True if full, False otherwise.**" + ] + }, + { + "cell_type": "code", + "execution_count": 93, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def full_board_check(board):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 8: Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if it's a free position. If it is, then return the position for later use.**" + ] + }, + { + "cell_type": "code", + "execution_count": 94, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def player_choice(board):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 9: Write a function that asks the player if they want to play again and returns a boolean True if they do want to play again.**" + ] + }, + { + "cell_type": "code", + "execution_count": 95, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def replay():\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "**Step 10: Here comes the hard part! Use while loops and the functions you've made to run the game!**" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to Tic Tac Toe!\n" + ] + } + ], + "source": [ + "print('Welcome to Tic Tac Toe!')\n", + "\n", + "#while True:\n", + " # Set the game up here\n", + " #pass\n", + "\n", + " #while game_on:\n", + " #Player 1 Turn\n", + " \n", + " \n", + " # Player2's turn.\n", + " \n", + " #pass\n", + "\n", + " #if not replay():\n", + " #break" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Good Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/03-Milestone Project 1 - Complete Walkthrough Solution-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/03-Milestone Project 1 - Complete Walkthrough Solution-checkpoint.ipynb new file mode 100644 index 0000000..8e84722 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/03-Milestone Project 1 - Complete Walkthrough Solution-checkpoint.ipynb @@ -0,0 +1,495 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Milestone Project 1: Full Walk-through Code Solution\n", + "\n", + "Below is the filled in code that goes along with the complete walk-through video. Check out the corresponding lecture videos for more information on this code!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 1: Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.**" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from IPython.display import clear_output\n", + "\n", + "def display_board(board):\n", + " clear_output() # Remember, this only works in jupyter!\n", + " \n", + " print(' | |')\n", + " print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])\n", + " print(' | |')\n", + " print('-----------')\n", + " print(' | |')\n", + " print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])\n", + " print(' | |')\n", + " print('-----------')\n", + " print(' | |')\n", + " print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])\n", + " print(' | |')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 1:** run your function on a test version of the board list, and make adjustments as necessary" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " | |\n", + " X | O | X\n", + " | |\n", + "-----------\n", + " | |\n", + " O | X | O\n", + " | |\n", + "-----------\n", + " | |\n", + " X | O | X\n", + " | |\n" + ] + } + ], + "source": [ + "test_board = ['#','X','O','X','O','X','O','X','O','X']\n", + "display_board(test_board)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'. Think about using *while* loops to continually ask until you get a correct answer.**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def player_input():\n", + " marker = ''\n", + " \n", + " while not (marker == 'X' or marker == 'O'):\n", + " marker = input('Player 1: Do you want to be X or O? ').upper()\n", + "\n", + " if marker == 'X':\n", + " return ('X', 'O')\n", + " else:\n", + " return ('O', 'X')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 2:** run the function to make sure it returns the desired output" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Player 1: Do you want to be X or O? X\n" + ] + }, + { + "data": { + "text/plain": [ + "('X', 'O')" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "player_input()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 3: Write a function that takes in the board list object, a marker ('X' or 'O'), and a desired position (number 1-9) and assigns it to the board.**" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def place_marker(board, marker, position):\n", + " board[position] = marker" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 3:** run the place marker function using test parameters and display the modified board" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " | |\n", + " X | $ | X\n", + " | |\n", + "-----------\n", + " | |\n", + " O | X | O\n", + " | |\n", + "-----------\n", + " | |\n", + " X | O | X\n", + " | |\n" + ] + } + ], + "source": [ + "place_marker(test_board,'$',8)\n", + "display_board(test_board)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 4: Write a function that takes in a board and checks to see if someone has won. **" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def win_check(board,mark):\n", + " \n", + " return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top\n", + " (board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle\n", + " (board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom\n", + " (board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle\n", + " (board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle\n", + " (board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side\n", + " (board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal\n", + " (board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 4:** run the win_check function against our test_board - it should return True" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "win_check(test_board,'X')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 5: Write a function that uses the random module to randomly decide which player goes first. You may want to lookup random.randint() Return a string of which player went first.**" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import random\n", + "\n", + "def choose_first():\n", + " if random.randint(0, 1) == 0:\n", + " return 'Player 2'\n", + " else:\n", + " return 'Player 1'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 6: Write a function that returns a boolean indicating whether a space on the board is freely available.**" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def space_check(board, position):\n", + " \n", + " return board[position] == ' '" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 7: Write a function that checks if the board is full and returns a boolean value. True if full, False otherwise.**" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def full_board_check(board):\n", + " for i in range(1,10):\n", + " if space_check(board, i):\n", + " return False\n", + " return True" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 8: Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if its a free position. If it is, then return the position for later use. **" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def player_choice(board):\n", + " position = 0\n", + " \n", + " while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):\n", + " position = int(input('Choose your next position: (1-9) '))\n", + " \n", + " return position" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 9: Write a function that asks the player if they want to play again and returns a boolean True if they do want to play again.**" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def replay():\n", + " \n", + " return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "**Step 10: Here comes the hard part! Use while loops and the functions you've made to run the game!**" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " | |\n", + " | O | \n", + " | |\n", + "-----------\n", + " | |\n", + " | O | X\n", + " | |\n", + "-----------\n", + " | |\n", + " X | O | X\n", + " | |\n", + "Player 2 has won!\n", + "Do you want to play again? Enter Yes or No: No\n" + ] + } + ], + "source": [ + "print('Welcome to Tic Tac Toe!')\n", + "\n", + "while True:\n", + " # Reset the board\n", + " theBoard = [' '] * 10\n", + " player1_marker, player2_marker = player_input()\n", + " turn = choose_first()\n", + " print(turn + ' will go first.')\n", + " \n", + " play_game = input('Are you ready to play? Enter Yes or No.')\n", + " \n", + " if play_game.lower()[0] == 'y':\n", + " game_on = True\n", + " else:\n", + " game_on = False\n", + "\n", + " while game_on:\n", + " if turn == 'Player 1':\n", + " # Player1's turn.\n", + " \n", + " display_board(theBoard)\n", + " position = player_choice(theBoard)\n", + " place_marker(theBoard, player1_marker, position)\n", + "\n", + " if win_check(theBoard, player1_marker):\n", + " display_board(theBoard)\n", + " print('Congratulations! You have won the game!')\n", + " game_on = False\n", + " else:\n", + " if full_board_check(theBoard):\n", + " display_board(theBoard)\n", + " print('The game is a draw!')\n", + " break\n", + " else:\n", + " turn = 'Player 2'\n", + "\n", + " else:\n", + " # Player2's turn.\n", + " \n", + " display_board(theBoard)\n", + " position = player_choice(theBoard)\n", + " place_marker(theBoard, player2_marker, position)\n", + "\n", + " if win_check(theBoard, player2_marker):\n", + " display_board(theBoard)\n", + " print('Player 2 has won!')\n", + " game_on = False\n", + " else:\n", + " if full_board_check(theBoard):\n", + " display_board(theBoard)\n", + " print('The game is a draw!')\n", + " break\n", + " else:\n", + " turn = 'Player 1'\n", + "\n", + " if not replay():\n", + " break" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Good Job!" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python [default]", + "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.5.3" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/04-OPTIONAL -Milestone Project 1 - Advanced Solution-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/04-OPTIONAL -Milestone Project 1 - Advanced Solution-checkpoint.ipynb new file mode 100644 index 0000000..0829bc5 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/.ipynb_checkpoints/04-OPTIONAL -Milestone Project 1 - Advanced Solution-checkpoint.ipynb @@ -0,0 +1,264 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Tic Tac Toe - Advanced Solution\n", + "\n", + "This solution follows the same basic format as the Complete Walkthrough Solution, but takes advantage of some of the more advanced statements we have learned. Feel free to download the notebook to understand how it works!" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Specifically for the iPython Notebook environment for clearing output\n", + "from IPython.display import clear_output\n", + "import random\n", + "\n", + "# Global variables\n", + "theBoard = [' '] * 10 # a list of empty spaces\n", + "available = [str(num) for num in range(0,10)] # a List Comprehension\n", + "players = [0,'X','O'] # note that players[1] == 'X' and players[-1] == 'O'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Available TIC-TAC-TOE\n", + " moves\n", + "\n", + " 7|8|9 | | \n", + " ----- -----\n", + " 4|5|6 | | \n", + " ----- -----\n", + " 1|2|3 | | \n", + "\n" + ] + } + ], + "source": [ + "def display_board(a,b):\n", + " print('Available TIC-TAC-TOE\\n'+\n", + " ' moves\\n\\n '+\n", + " a[7]+'|'+a[8]+'|'+a[9]+' '+b[7]+'|'+b[8]+'|'+b[9]+'\\n '+\n", + " '----- -----\\n '+\n", + " a[4]+'|'+a[5]+'|'+a[6]+' '+b[4]+'|'+b[5]+'|'+b[6]+'\\n '+\n", + " '----- -----\\n '+\n", + " a[1]+'|'+a[2]+'|'+a[3]+' '+b[1]+'|'+b[2]+'|'+b[3]+'\\n')\n", + "display_board(available,theBoard)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Available TIC-TAC-TOE\n", + " moves\n", + "\n", + " 7|8|9 | | \n", + " ----- -----\n", + " 4|5|6 | | \n", + " ----- -----\n", + " 1|2|3 | | \n", + "\n" + ] + } + ], + "source": [ + "def display_board(a,b):\n", + " print(f'Available TIC-TAC-TOE\\n moves\\n\\n {a[7]}|{a[8]}|{a[9]} {b[7]}|{b[8]}|{b[9]}\\n ----- -----\\n {a[4]}|{a[5]}|{a[6]} {b[4]}|{b[5]}|{b[6]}\\n ----- -----\\n {a[1]}|{a[2]}|{a[3]} {b[1]}|{b[2]}|{b[3]}\\n')\n", + "display_board(available,theBoard)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def place_marker(avail,board,marker,position):\n", + " board[position] = marker\n", + " avail[position] = ' '" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def win_check(board,mark):\n", + "\n", + " return ((board[7] == board[8] == board[9] == mark) or # across the top\n", + " (board[4] == board[5] == board[6] == mark) or # across the middle\n", + " (board[1] == board[2] == board[3] == mark) or # across the bottom\n", + " (board[7] == board[4] == board[1] == mark) or # down the middle\n", + " (board[8] == board[5] == board[2] == mark) or # down the middle\n", + " (board[9] == board[6] == board[3] == mark) or # down the right side\n", + " (board[7] == board[5] == board[3] == mark) or # diagonal\n", + " (board[9] == board[5] == board[1] == mark)) # diagonal" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def random_player():\n", + " return random.choice((-1, 1))\n", + " \n", + "def space_check(board,position):\n", + " return board[position] == ' '\n", + "\n", + "def full_board_check(board):\n", + " return ' ' not in board[1:]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def player_choice(board,player):\n", + " position = 0\n", + " \n", + " while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):\n", + " try:\n", + " position = int(input('Player %s, choose your next position: (1-9) '%(player)))\n", + " except:\n", + " print(\"I'm sorry, please try again.\")\n", + " \n", + " return position" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def replay():\n", + " \n", + " return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to Tic Tac Toe!\n", + "For this round, Player X will go first!\n" + ] + } + ], + "source": [ + "while True:\n", + " clear_output()\n", + " print('Welcome to Tic Tac Toe!')\n", + " \n", + " toggle = random_player()\n", + " player = players[toggle]\n", + " print('For this round, Player %s will go first!' %(player))\n", + " \n", + " game_on = True\n", + " input('Hit Enter to continue')\n", + " while game_on:\n", + " display_board(available,theBoard)\n", + " position = player_choice(theBoard,player)\n", + " place_marker(available,theBoard,player,position)\n", + "\n", + " if win_check(theBoard, player):\n", + " display_board(available,theBoard)\n", + " print('Congratulations! Player '+player+' wins!')\n", + " game_on = False\n", + " else:\n", + " if full_board_check(theBoard):\n", + " display_board(available,theBoard)\n", + " print('The game is a draw!')\n", + " break\n", + " else:\n", + " toggle *= -1\n", + " player = players[toggle]\n", + " clear_output()\n", + "\n", + " # reset the board and available moves list\n", + " theBoard = [' '] * 10\n", + " available = [str(num) for num in range(0,10)]\n", + " \n", + " if not replay():\n", + " break" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python [default]", + "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.5.3" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/01-Milestone Project 1 - Assignment.ipynb b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/01-Milestone Project 1 - Assignment.ipynb new file mode 100644 index 0000000..b9b4a76 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/01-Milestone Project 1 - Assignment.ipynb @@ -0,0 +1,62 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Milestone Project 1\n", + "## Congratulations on making it to your first milestone!\n", + "You've already learned a ton and are ready to work on a real project.\n", + "\n", + "Your assignment: Create a Tic Tac Toe game. You are free to use any IDE you like.\n", + "\n", + "Here are the requirements:\n", + "\n", + "* 2 players should be able to play the game (both sitting at the same computer)\n", + "* The board should be printed out every time a player makes a move\n", + "* You should be able to accept input of the player position and then place a symbol on the board\n", + "\n", + "Feel free to use Google to help you figure anything out (but don't just Google \"Tic Tac Toe in Python\" otherwise you won't learn anything!) Keep in mind that this project can take anywhere between several hours to several days.\n", + "\n", + "There are 4 Jupyter Notebooks related to this assignment:\n", + "\n", + "* This Assignment Notebook\n", + "* A \"Walkthrough Steps Workbook\" Notebook\n", + "* A \"Complete Walkthrough Solution\" Notebook\n", + "* An \"Advanced Solution\" Notebook\n", + "\n", + "I encourage you to just try to start the project on your own without referencing any of the notebooks. If you get stuck, check out the next lecture which is a text lecture with helpful hints and steps. If you're still stuck after that, then check out the Walkthrough Steps Workbook, which breaks up the project in steps for you to solve. Still stuck? Then check out the Complete Walkthrough Solution video for more help on approaching the project!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "There are parts of this that will be a struggle...and that is good! I have complete faith that if you have made it this far through the course you have all the tools and knowledge to tackle this project. Remember, it's totally open book, so take your time, do a little research, and remember:\n", + "\n", + "## HAVE FUN!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/02-Milestone Project 1 - Walkthrough Steps Workbook.ipynb b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/02-Milestone Project 1 - Walkthrough Steps Workbook.ipynb new file mode 100644 index 0000000..3242b1d --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/02-Milestone Project 1 - Walkthrough Steps Workbook.ipynb @@ -0,0 +1,332 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Milestone Project 1: Walkthrough Steps Workbook\n", + "\n", + "Below is a set of steps for you to follow to try to create the Tic Tac Toe Milestone Project game!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "#### Some suggested tools before you get started:\n", + "To take input from a user:\n", + "\n", + " player1 = input(\"Please pick a marker 'X' or 'O'\")\n", + " \n", + "Note that input() takes in a string. If you need an integer value, use\n", + "\n", + " position = int(input('Please enter a number'))\n", + " \n", + "
To clear the screen between moves:\n", + "\n", + " from IPython.display import clear_output\n", + " clear_output()\n", + " \n", + "Note that clear_output() will only work in jupyter. To clear the screen in other IDEs, consider:\n", + "\n", + " print('\\n'*100)\n", + " \n", + "This scrolls the previous board up out of view. Now on to the program!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 1: Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "from IPython.display import clear_output\n", + "\n", + "def display_board(board):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 1:** run your function on a test version of the board list, and make adjustments as necessary" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "test_board = ['#','X','O','X','O','X','O','X','O','X']\n", + "display_board(test_board)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'. Think about using *while* loops to continually ask until you get a correct answer.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def player_input():\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 2:** run the function to make sure it returns the desired output" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "player_input()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 3: Write a function that takes in the board list object, a marker ('X' or 'O'), and a desired position (number 1-9) and assigns it to the board.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def place_marker(board, marker, position):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 3:** run the place marker function using test parameters and display the modified board" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "place_marker(test_board,'$',8)\n", + "display_board(test_board)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 4: Write a function that takes in a board and a mark (X or O) and then checks to see if that mark has won. **" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def win_check(board, mark):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 4:** run the win_check function against our test_board - it should return True" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "win_check(test_board,'X')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 5: Write a function that uses the random module to randomly decide which player goes first. You may want to lookup random.randint() Return a string of which player went first.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "def choose_first():\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 6: Write a function that returns a boolean indicating whether a space on the board is freely available.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def space_check(board, position):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 7: Write a function that checks if the board is full and returns a boolean value. True if full, False otherwise.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def full_board_check(board):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 8: Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if it's a free position. If it is, then return the position for later use.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def player_choice(board):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 9: Write a function that asks the player if they want to play again and returns a boolean True if they do want to play again.**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def replay():\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "**Step 10: Here comes the hard part! Use while loops and the functions you've made to run the game!**" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "print('Welcome to Tic Tac Toe!')\n", + "\n", + "#while True:\n", + " # Set the game up here\n", + " #pass\n", + "\n", + " #while game_on:\n", + " #Player 1 Turn\n", + " \n", + " \n", + " # Player2's turn.\n", + " \n", + " #pass\n", + "\n", + " #if not replay():\n", + " #break" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Good Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/03-Milestone Project 1 - Complete Walkthrough Solution.ipynb b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/03-Milestone Project 1 - Complete Walkthrough Solution.ipynb new file mode 100644 index 0000000..cad94aa --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/03-Milestone Project 1 - Complete Walkthrough Solution.ipynb @@ -0,0 +1,485 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Milestone Project 1: Full Walk-through Code Solution\n", + "\n", + "Below is the filled in code that goes along with the complete walk-through video. Check out the corresponding lecture videos for more information on this code!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 1: Write a function that can print out a board. Set up your board as a list, where each index 1-9 corresponds with a number on a number pad, so you get a 3 by 3 board representation.**" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "from IPython.display import clear_output\n", + "\n", + "def display_board(board):\n", + " clear_output() # Remember, this only works in jupyter!\n", + " \n", + " print(' | |')\n", + " print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9])\n", + " print(' | |')\n", + " print('-----------')\n", + " print(' | |')\n", + " print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6])\n", + " print(' | |')\n", + " print('-----------')\n", + " print(' | |')\n", + " print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3])\n", + " print(' | |')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 1:** run your function on a test version of the board list, and make adjustments as necessary" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " | |\n", + " X | O | X\n", + " | |\n", + "-----------\n", + " | |\n", + " O | X | O\n", + " | |\n", + "-----------\n", + " | |\n", + " X | O | X\n", + " | |\n" + ] + } + ], + "source": [ + "test_board = ['#','X','O','X','O','X','O','X','O','X']\n", + "display_board(test_board)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 2: Write a function that can take in a player input and assign their marker as 'X' or 'O'. Think about using *while* loops to continually ask until you get a correct answer.**" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def player_input():\n", + " marker = ''\n", + " \n", + " while not (marker == 'X' or marker == 'O'):\n", + " marker = input('Player 1: Do you want to be X or O? ').upper()\n", + "\n", + " if marker == 'X':\n", + " return ('X', 'O')\n", + " else:\n", + " return ('O', 'X')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 2:** run the function to make sure it returns the desired output" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Player 1: Do you want to be X or O? X\n" + ] + }, + { + "data": { + "text/plain": [ + "('X', 'O')" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "player_input()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 3: Write a function that takes in the board list object, a marker ('X' or 'O'), and a desired position (number 1-9) and assigns it to the board.**" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def place_marker(board, marker, position):\n", + " board[position] = marker" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 3:** run the place marker function using test parameters and display the modified board" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " | |\n", + " X | $ | X\n", + " | |\n", + "-----------\n", + " | |\n", + " O | X | O\n", + " | |\n", + "-----------\n", + " | |\n", + " X | O | X\n", + " | |\n" + ] + } + ], + "source": [ + "place_marker(test_board,'$',8)\n", + "display_board(test_board)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 4: Write a function that takes in a board and checks to see if someone has won. **" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def win_check(board,mark):\n", + " \n", + " return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top\n", + " (board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle\n", + " (board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom\n", + " (board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle\n", + " (board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle\n", + " (board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side\n", + " (board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal\n", + " (board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**TEST Step 4:** run the win_check function against our test_board - it should return True" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "win_check(test_board,'X')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 5: Write a function that uses the random module to randomly decide which player goes first. You may want to lookup random.randint() Return a string of which player went first.**" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "import random\n", + "\n", + "def choose_first():\n", + " if random.randint(0, 1) == 0:\n", + " return 'Player 2'\n", + " else:\n", + " return 'Player 1'" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 6: Write a function that returns a boolean indicating whether a space on the board is freely available.**" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def space_check(board, position):\n", + " \n", + " return board[position] == ' '" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 7: Write a function that checks if the board is full and returns a boolean value. True if full, False otherwise.**" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def full_board_check(board):\n", + " for i in range(1,10):\n", + " if space_check(board, i):\n", + " return False\n", + " return True" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 8: Write a function that asks for a player's next position (as a number 1-9) and then uses the function from step 6 to check if its a free position. If it is, then return the position for later use. **" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def player_choice(board):\n", + " position = 0\n", + " \n", + " while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):\n", + " position = int(input('Choose your next position: (1-9) '))\n", + " \n", + " return position" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 9: Write a function that asks the player if they want to play again and returns a boolean True if they do want to play again.**" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def replay():\n", + " \n", + " return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "**Step 10: Here comes the hard part! Use while loops and the functions you've made to run the game!**" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + " | |\n", + " | O | O\n", + " | |\n", + "-----------\n", + " | |\n", + " | | \n", + " | |\n", + "-----------\n", + " | |\n", + " X | X | X\n", + " | |\n", + "Congratulations! You have won the game!\n", + "Do you want to play again? Enter Yes or No: No\n" + ] + } + ], + "source": [ + "print('Welcome to Tic Tac Toe!')\n", + "\n", + "while True:\n", + " # Reset the board\n", + " theBoard = [' '] * 10\n", + " player1_marker, player2_marker = player_input()\n", + " turn = choose_first()\n", + " print(turn + ' will go first.')\n", + " \n", + " play_game = input('Are you ready to play? Enter Yes or No.')\n", + " \n", + " if play_game.lower()[0] == 'y':\n", + " game_on = True\n", + " else:\n", + " game_on = False\n", + "\n", + " while game_on:\n", + " if turn == 'Player 1':\n", + " # Player1's turn.\n", + " \n", + " display_board(theBoard)\n", + " position = player_choice(theBoard)\n", + " place_marker(theBoard, player1_marker, position)\n", + "\n", + " if win_check(theBoard, player1_marker):\n", + " display_board(theBoard)\n", + " print('Congratulations! You have won the game!')\n", + " game_on = False\n", + " else:\n", + " if full_board_check(theBoard):\n", + " display_board(theBoard)\n", + " print('The game is a draw!')\n", + " break\n", + " else:\n", + " turn = 'Player 2'\n", + "\n", + " else:\n", + " # Player2's turn.\n", + " \n", + " display_board(theBoard)\n", + " position = player_choice(theBoard)\n", + " place_marker(theBoard, player2_marker, position)\n", + "\n", + " if win_check(theBoard, player2_marker):\n", + " display_board(theBoard)\n", + " print('Player 2 has won!')\n", + " game_on = False\n", + " else:\n", + " if full_board_check(theBoard):\n", + " display_board(theBoard)\n", + " print('The game is a draw!')\n", + " break\n", + " else:\n", + " turn = 'Player 1'\n", + "\n", + " if not replay():\n", + " break" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "## Good Job!" + ] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python 3", + "language": "python", + "name": "python3" + }, + "language_info": { + "codemirror_mode": { + "name": "ipython", + "version": 3 + }, + "file_extension": ".py", + "mimetype": "text/x-python", + "name": "python", + "nbconvert_exporter": "python", + "pygments_lexer": "ipython3", + "version": "3.6.1" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/04-OPTIONAL -Milestone Project 1 - Advanced Solution.ipynb b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/04-OPTIONAL -Milestone Project 1 - Advanced Solution.ipynb new file mode 100644 index 0000000..0829bc5 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/04-Milestone Project - 1/04-OPTIONAL -Milestone Project 1 - Advanced Solution.ipynb @@ -0,0 +1,264 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Tic Tac Toe - Advanced Solution\n", + "\n", + "This solution follows the same basic format as the Complete Walkthrough Solution, but takes advantage of some of the more advanced statements we have learned. Feel free to download the notebook to understand how it works!" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Specifically for the iPython Notebook environment for clearing output\n", + "from IPython.display import clear_output\n", + "import random\n", + "\n", + "# Global variables\n", + "theBoard = [' '] * 10 # a list of empty spaces\n", + "available = [str(num) for num in range(0,10)] # a List Comprehension\n", + "players = [0,'X','O'] # note that players[1] == 'X' and players[-1] == 'O'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Available TIC-TAC-TOE\n", + " moves\n", + "\n", + " 7|8|9 | | \n", + " ----- -----\n", + " 4|5|6 | | \n", + " ----- -----\n", + " 1|2|3 | | \n", + "\n" + ] + } + ], + "source": [ + "def display_board(a,b):\n", + " print('Available TIC-TAC-TOE\\n'+\n", + " ' moves\\n\\n '+\n", + " a[7]+'|'+a[8]+'|'+a[9]+' '+b[7]+'|'+b[8]+'|'+b[9]+'\\n '+\n", + " '----- -----\\n '+\n", + " a[4]+'|'+a[5]+'|'+a[6]+' '+b[4]+'|'+b[5]+'|'+b[6]+'\\n '+\n", + " '----- -----\\n '+\n", + " a[1]+'|'+a[2]+'|'+a[3]+' '+b[1]+'|'+b[2]+'|'+b[3]+'\\n')\n", + "display_board(available,theBoard)" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Available TIC-TAC-TOE\n", + " moves\n", + "\n", + " 7|8|9 | | \n", + " ----- -----\n", + " 4|5|6 | | \n", + " ----- -----\n", + " 1|2|3 | | \n", + "\n" + ] + } + ], + "source": [ + "def display_board(a,b):\n", + " print(f'Available TIC-TAC-TOE\\n moves\\n\\n {a[7]}|{a[8]}|{a[9]} {b[7]}|{b[8]}|{b[9]}\\n ----- -----\\n {a[4]}|{a[5]}|{a[6]} {b[4]}|{b[5]}|{b[6]}\\n ----- -----\\n {a[1]}|{a[2]}|{a[3]} {b[1]}|{b[2]}|{b[3]}\\n')\n", + "display_board(available,theBoard)\n" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def place_marker(avail,board,marker,position):\n", + " board[position] = marker\n", + " avail[position] = ' '" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def win_check(board,mark):\n", + "\n", + " return ((board[7] == board[8] == board[9] == mark) or # across the top\n", + " (board[4] == board[5] == board[6] == mark) or # across the middle\n", + " (board[1] == board[2] == board[3] == mark) or # across the bottom\n", + " (board[7] == board[4] == board[1] == mark) or # down the middle\n", + " (board[8] == board[5] == board[2] == mark) or # down the middle\n", + " (board[9] == board[6] == board[3] == mark) or # down the right side\n", + " (board[7] == board[5] == board[3] == mark) or # diagonal\n", + " (board[9] == board[5] == board[1] == mark)) # diagonal" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def random_player():\n", + " return random.choice((-1, 1))\n", + " \n", + "def space_check(board,position):\n", + " return board[position] == ' '\n", + "\n", + "def full_board_check(board):\n", + " return ' ' not in board[1:]" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def player_choice(board,player):\n", + " position = 0\n", + " \n", + " while position not in [1,2,3,4,5,6,7,8,9] or not space_check(board, position):\n", + " try:\n", + " position = int(input('Player %s, choose your next position: (1-9) '%(player)))\n", + " except:\n", + " print(\"I'm sorry, please try again.\")\n", + " \n", + " return position" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "def replay():\n", + " \n", + " return input('Do you want to play again? Enter Yes or No: ').lower().startswith('y')" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": false + }, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Welcome to Tic Tac Toe!\n", + "For this round, Player X will go first!\n" + ] + } + ], + "source": [ + "while True:\n", + " clear_output()\n", + " print('Welcome to Tic Tac Toe!')\n", + " \n", + " toggle = random_player()\n", + " player = players[toggle]\n", + " print('For this round, Player %s will go first!' %(player))\n", + " \n", + " game_on = True\n", + " input('Hit Enter to continue')\n", + " while game_on:\n", + " display_board(available,theBoard)\n", + " position = player_choice(theBoard,player)\n", + " place_marker(available,theBoard,player,position)\n", + "\n", + " if win_check(theBoard, player):\n", + " display_board(available,theBoard)\n", + " print('Congratulations! Player '+player+' wins!')\n", + " game_on = False\n", + " else:\n", + " if full_board_check(theBoard):\n", + " display_board(available,theBoard)\n", + " print('The game is a draw!')\n", + " break\n", + " else:\n", + " toggle *= -1\n", + " player = players[toggle]\n", + " clear_output()\n", + "\n", + " # reset the board and available moves list\n", + " theBoard = [' '] * 10\n", + " available = [str(num) for num in range(0,10)]\n", + " \n", + " if not replay():\n", + " break" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [] + } + ], + "metadata": { + "anaconda-cloud": {}, + "kernelspec": { + "display_name": "Python [default]", + "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.5.3" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/01-Object Oriented Programming-Copy1-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/01-Object Oriented Programming-Copy1-checkpoint.ipynb new file mode 100644 index 0000000..e73ceba --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/01-Object Oriented Programming-Copy1-checkpoint.ipynb @@ -0,0 +1,789 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Object Oriented Programming\n", + "\n", + "Object Oriented Programming (OOP) tends to be one of the major obstacles for beginners when they are first starting to learn Python.\n", + "\n", + "There are many, many tutorials and lessons covering OOP so feel free to Google search other lessons, and I have also put some links to other useful tutorials online at the bottom of this Notebook.\n", + "\n", + "For this lesson we will construct our knowledge of OOP in Python by building on the following topics:\n", + "\n", + "* Objects\n", + "* Using the *class* keyword\n", + "* Creating class attributes\n", + "* Creating methods in a class\n", + "* Learning about Inheritance\n", + "* Learning about Special Methods for classes\n", + "\n", + "Lets start the lesson by remembering about the Basic Python Objects. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "lst = [1,2,3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Remember how we could call methods on a list?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst.count(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What we will basically be doing in this lecture is exploring how we could create an Object type like a list. We've already learned about how to create functions. So let's explore Objects in general:\n", + "\n", + "## Objects\n", + "In Python, *everything is an object*. Remember from previous lectures we can use type() to check the type of object something is:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\n", + "\n" + ] + } + ], + "source": [ + "print(type(1))\n", + "print(type([]))\n", + "print(type(()))\n", + "print(type({}))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So we know all these things are objects, so how can we create our own Object types? That is where the class keyword comes in.\n", + "## class\n", + "User defined objects are created using the class keyword. The class is a blueprint that defines the nature of a future object. From classes we can construct instances. An instance is a specific object created from a particular class. For example, above we created the object lst which was an instance of a list object. \n", + "\n", + "Let see how we can use class:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], + "source": [ + "# Create a new object type called Sample\n", + "class Sample:\n", + " pass\n", + "\n", + "# Instance of Sample\n", + "x = Sample()\n", + "\n", + "print(type(x))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By convention we give classes a name that starts with a capital letter. Note how x is now the reference to our new instance of a Sample class. In other words, we **instantiate** the Sample class.\n", + "\n", + "Inside of the class we currently just have pass. But we can define class attributes and methods.\n", + "\n", + "An **attribute** is a characteristic of an object.\n", + "A **method** is an operation we can perform with the object.\n", + "\n", + "For example, we can create a class called Dog. An attribute of a dog may be its breed or its name, while a method of a dog may be defined by a .bark() method which returns a sound.\n", + "\n", + "Let's get a better understanding of attributes through an example.\n", + "\n", + "## Attributes\n", + "The syntax for creating an attribute is:\n", + " \n", + " self.attribute = something\n", + " \n", + "There is a special method called:\n", + "\n", + " __init__()\n", + "\n", + "This method is used to initialize the attributes of an object. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "class Dog:\n", + " def __init__(self,breed):\n", + " self.breed = breed\n", + " \n", + "sam = Dog(breed='Lab')\n", + "frank = Dog(breed='Huskie')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Lets break down what we have above.The special method \n", + "\n", + " __init__() \n", + "is called automatically right after the object has been created:\n", + "\n", + " def __init__(self, breed):\n", + "Each attribute in a class definition begins with a reference to the instance object. It is by convention named self. The breed is the argument. The value is passed during the class instantiation.\n", + "\n", + " self.breed = breed" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we have created two instances of the Dog class. With two breed types, we can then access these attributes like this:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Lab'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sam.breed" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Huskie'" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "frank.breed" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how we don't have any parentheses after breed; this is because it is an attribute and doesn't take any arguments.\n", + "\n", + "In Python there are also *class object attributes*. These Class Object Attributes are the same for any instance of the class. For example, we could create the attribute *species* for the Dog class. Dogs, regardless of their breed, name, or other attributes, will always be mammals. We apply this logic in the following manner:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "class Dog:\n", + " \n", + " # Class Object Attribute\n", + " species = 'mammal'\n", + " \n", + " def __init__(self,breed,name):\n", + " self.breed = breed\n", + " self.name = name" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "sam = Dog('Lab','Sam')" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Sam'" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sam.name" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that the Class Object Attribute is defined outside of any methods in the class. Also by convention, we place them first before the init." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'mammal'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sam.species" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Methods\n", + "\n", + "Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods are a key concept of the OOP paradigm. They are essential to dividing responsibilities in programming, especially in large applications.\n", + "\n", + "You can basically think of methods as functions acting on an Object that take the Object itself into account through its *self* argument.\n", + "\n", + "Let's go through an example of creating a Circle class:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Radius is: 1\n", + "Area is: 3.14\n", + "Circumference is: 6.28\n" + ] + } + ], + "source": [ + "class Circle:\n", + " pi = 3.14\n", + "\n", + " # Circle gets instantiated with a radius (default is 1)\n", + " def __init__(self, radius=1):\n", + " self.radius = radius \n", + " self.area = radius * radius * Circle.pi\n", + "\n", + " # Method for resetting Radius\n", + " def setRadius(self, new_radius):\n", + " self.radius = new_radius\n", + " self.area = new_radius * new_radius * self.pi\n", + "\n", + " # Method for getting Circumference\n", + " def getCircumference(self):\n", + " return self.radius * self.pi * 2\n", + "\n", + "\n", + "c = Circle()\n", + "\n", + "print('Radius is: ',c.radius)\n", + "print('Area is: ',c.area)\n", + "print('Circumference is: ',c.getCircumference())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the \\__init__ method above, in order to calculate the area attribute, we had to call Circle.pi. This is because the object does not yet have its own .pi attribute, so we call the Class Object Attribute pi instead.
\n", + "In the setRadius method, however, we'll be working with an existing Circle object that does have its own pi attribute. Here we can use either Circle.pi or self.pi.

\n", + "Now let's change the radius and see how that affects our Circle object:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Radius is: 2\n", + "Area is: 12.56\n", + "Circumference is: 12.56\n" + ] + } + ], + "source": [ + "c.setRadius(2)\n", + "\n", + "print('Radius is: ',c.radius)\n", + "print('Area is: ',c.area)\n", + "print('Circumference is: ',c.getCircumference())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Notice how we used self. notation to reference attributes of the class within the method calls. Review how the code above works and try creating your own method.\n", + "\n", + "## Inheritance\n", + "\n", + "Inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of base classes (ancestors).\n", + "\n", + "Let's see an example by incorporating our previous work on the Dog class:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "class Animal:\n", + " def __init__(self):\n", + " print(\"Animal created\")\n", + "\n", + " def whoAmI(self):\n", + " print(\"Animal\")\n", + "\n", + " def eat(self):\n", + " print(\"Eating\")\n", + "\n", + "\n", + "class Dog(Animal):\n", + " def __init__(self):\n", + " Animal.__init__(self)\n", + " print(\"Dog created\")\n", + "\n", + " def whoAmI(self):\n", + " print(\"Dog\")\n", + "\n", + " def bark(self):\n", + " print(\"Woof!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Animal created\n", + "Dog created\n" + ] + } + ], + "source": [ + "d = Dog()" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Dog\n" + ] + } + ], + "source": [ + "d.whoAmI()" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Eating\n" + ] + } + ], + "source": [ + "d.eat()" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Woof!\n" + ] + } + ], + "source": [ + "d.bark()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this example, we have two classes: Animal and Dog. The Animal is the base class, the Dog is the derived class. \n", + "\n", + "The derived class inherits the functionality of the base class. \n", + "\n", + "* It is shown by the eat() method. \n", + "\n", + "The derived class modifies existing behavior of the base class.\n", + "\n", + "* shown by the whoAmI() method. \n", + "\n", + "Finally, the derived class extends the functionality of the base class, by defining a new bark() method." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Polymorphism\n", + "\n", + "We've learned that while functions can take in different arguments, methods belong to the objects they act on. In Python, *polymorphism* refers to the way in which different object classes can share the same method name, and those methods can be called from the same place even though a variety of different objects might be passed in. The best way to explain this is by example:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Niko says Woof!\n", + "Felix says Meow!\n" + ] + } + ], + "source": [ + "class Dog:\n", + " def __init__(self, name):\n", + " self.name = name\n", + "\n", + " def speak(self):\n", + " return self.name+' says Woof!'\n", + " \n", + "class Cat:\n", + " def __init__(self, name):\n", + " self.name = name\n", + "\n", + " def speak(self):\n", + " return self.name+' says Meow!' \n", + " \n", + "niko = Dog('Niko')\n", + "felix = Cat('Felix')\n", + "\n", + "print(niko.speak())\n", + "print(felix.speak())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we have a Dog class and a Cat class, and each has a `.speak()` method. When called, each object's `.speak()` method returns a result unique to the object.\n", + "\n", + "There a few different ways to demonstrate polymorphism. First, with a for loop:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Niko says Woof!\n", + "Felix says Meow!\n" + ] + } + ], + "source": [ + "for pet in [niko,felix]:\n", + " print(pet.speak())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Another is with functions:" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Niko says Woof!\n", + "Felix says Meow!\n" + ] + } + ], + "source": [ + "def pet_speak(pet):\n", + " print(pet.speak())\n", + "\n", + "pet_speak(niko)\n", + "pet_speak(felix)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "In both cases we were able to pass in different object types, and we obtained object-specific results from the same mechanism.\n", + "\n", + "A more common practice is to use abstract classes and inheritance. An abstract class is one that never expects to be instantiated. For example, we will never have an Animal object, only Dog and Cat objects, although Dogs and Cats are derived from Animals:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Fido says Woof!\n", + "Isis says Meow!\n" + ] + } + ], + "source": [ + "class Animal:\n", + " def __init__(self, name): # Constructor of the class\n", + " self.name = name\n", + "\n", + " def speak(self): # Abstract method, defined by convention only\n", + " raise NotImplementedError(\"Subclass must implement abstract method\")\n", + "\n", + "\n", + "class Dog(Animal):\n", + " \n", + " def speak(self):\n", + " return self.name+' says Woof!'\n", + " \n", + "class Cat(Animal):\n", + "\n", + " def speak(self):\n", + " return self.name+' says Meow!'\n", + " \n", + "fido = Dog('Fido')\n", + "isis = Cat('Isis')\n", + "\n", + "print(fido.speak())\n", + "print(isis.speak())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Real life examples of polymorphism include:\n", + "* opening different file types - different tools are needed to display Word, pdf and Excel files\n", + "* adding different objects - the `+` operator performs arithmetic and concatenation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Special Methods\n", + "Finally let's go over special methods. Classes in Python can implement certain operations with special method names. These methods are not actually called directly but by Python specific language syntax. For example let's create a Book class:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "class Book:\n", + " def __init__(self, title, author, pages):\n", + " print(\"A book is created\")\n", + " self.title = title\n", + " self.author = author\n", + " self.pages = pages\n", + "\n", + " def __str__(self):\n", + " return \"Title: %s, author: %s, pages: %s\" %(self.title, self.author, self.pages)\n", + "\n", + " def __len__(self):\n", + " return self.pages\n", + "\n", + " def __del__(self):\n", + " print(\"A book is destroyed\")" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A book is created\n", + "Title: Python Rocks!, author: Jose Portilla, pages: 159\n", + "159\n", + "A book is destroyed\n" + ] + } + ], + "source": [ + "book = Book(\"Python Rocks!\", \"Jose Portilla\", 159)\n", + "\n", + "#Special Methods\n", + "print(book)\n", + "print(len(book))\n", + "del book" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " The __init__(), __str__(), __len__() and __del__() methods\n", + "These special methods are defined by their use of underscores. They allow us to use Python specific functions on objects created through our class.\n", + "\n", + "**Great! After this lecture you should have a basic understanding of how to create your own objects with class in Python. You will be utilizing this heavily in your next milestone project!**\n", + "\n", + "For more great resources on this topic, check out:\n", + "\n", + "[Mozilla's Post](https://developer.mozilla.org/en-US/Learn/Python/Quickly_Learn_Object_Oriented_Programming)\n", + "\n", + "[Tutorial's Point](http://www.tutorialspoint.com/python/python_classes_objects.htm)\n", + "\n", + "[Official Documentation](https://docs.python.org/3/tutorial/classes.html)" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/01-Object Oriented Programming-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/01-Object Oriented Programming-checkpoint.ipynb new file mode 100644 index 0000000..4d9e12e --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/01-Object Oriented Programming-checkpoint.ipynb @@ -0,0 +1,792 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Object Oriented Programming\n", + "\n", + "Object Oriented Programming (OOP) tends to be one of the major obstacles for beginners when they are first starting to learn Python.\n", + "\n", + "There are many, many tutorials and lessons covering OOP so feel free to Google search other lessons, and I have also put some links to other useful tutorials online at the bottom of this Notebook.\n", + "\n", + "For this lesson we will construct our knowledge of OOP in Python by building on the following topics:\n", + "\n", + "* Objects\n", + "* Using the *class* keyword\n", + "* Creating class attributes\n", + "* Creating methods in a class\n", + "* Learning about Inheritance\n", + "* Learning about Polymorphism\n", + "* Learning about Special Methods for classes\n", + "\n", + "Lets start the lesson by remembering about the Basic Python Objects. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "lst = [1,2,3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Remember how we could call methods on a list?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst.count(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What we will basically be doing in this lecture is exploring how we could create an Object type like a list. We've already learned about how to create functions. So let's explore Objects in general:\n", + "\n", + "## Objects\n", + "In Python, *everything is an object*. Remember from previous lectures we can use type() to check the type of object something is:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\n", + "\n" + ] + } + ], + "source": [ + "print(type(1))\n", + "print(type([]))\n", + "print(type(()))\n", + "print(type({}))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So we know all these things are objects, so how can we create our own Object types? That is where the class keyword comes in.\n", + "## class\n", + "User defined objects are created using the class keyword. The class is a blueprint that defines the nature of a future object. From classes we can construct instances. An instance is a specific object created from a particular class. For example, above we created the object lst which was an instance of a list object. \n", + "\n", + "Let see how we can use class:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], + "source": [ + "# Create a new object type called Sample\n", + "class Sample:\n", + " pass\n", + "\n", + "# Instance of Sample\n", + "x = Sample()\n", + "\n", + "print(type(x))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By convention we give classes a name that starts with a capital letter. Note how x is now the reference to our new instance of a Sample class. In other words, we **instantiate** the Sample class.\n", + "\n", + "Inside of the class we currently just have pass. But we can define class attributes and methods.\n", + "\n", + "An **attribute** is a characteristic of an object.\n", + "A **method** is an operation we can perform with the object.\n", + "\n", + "For example, we can create a class called Dog. An attribute of a dog may be its breed or its name, while a method of a dog may be defined by a .bark() method which returns a sound.\n", + "\n", + "Let's get a better understanding of attributes through an example.\n", + "\n", + "## Attributes\n", + "The syntax for creating an attribute is:\n", + " \n", + " self.attribute = something\n", + " \n", + "There is a special method called:\n", + "\n", + " __init__()\n", + "\n", + "This method is used to initialize the attributes of an object. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "class Dog:\n", + " def __init__(self,breed):\n", + " self.breed = breed\n", + " \n", + "sam = Dog(breed='Lab')\n", + "frank = Dog(breed='Huskie')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Lets break down what we have above.The special method \n", + "\n", + " __init__() \n", + "is called automatically right after the object has been created:\n", + "\n", + " def __init__(self, breed):\n", + "Each attribute in a class definition begins with a reference to the instance object. It is by convention named self. The breed is the argument. The value is passed during the class instantiation.\n", + "\n", + " self.breed = breed" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we have created two instances of the Dog class. With two breed types, we can then access these attributes like this:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Lab'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sam.breed" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Huskie'" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "frank.breed" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how we don't have any parentheses after breed; this is because it is an attribute and doesn't take any arguments.\n", + "\n", + "In Python there are also *class object attributes*. These Class Object Attributes are the same for any instance of the class. For example, we could create the attribute *species* for the Dog class. Dogs, regardless of their breed, name, or other attributes, will always be mammals. We apply this logic in the following manner:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "class Dog:\n", + " \n", + " # Class Object Attribute\n", + " species = 'mammal'\n", + " \n", + " def __init__(self,breed,name):\n", + " self.breed = breed\n", + " self.name = name" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "sam = Dog('Lab','Sam')" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Sam'" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sam.name" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that the Class Object Attribute is defined outside of any methods in the class. Also by convention, we place them first before the init." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'mammal'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sam.species" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Methods\n", + "\n", + "Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods are a key concept of the OOP paradigm. They are essential to dividing responsibilities in programming, especially in large applications.\n", + "\n", + "You can basically think of methods as functions acting on an Object that take the Object itself into account through its *self* argument.\n", + "\n", + "Let's go through an example of creating a Circle class:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Radius is: 1\n", + "Area is: 3.14\n", + "Circumference is: 6.28\n" + ] + } + ], + "source": [ + "class Circle:\n", + " pi = 3.14\n", + "\n", + " # Circle gets instantiated with a radius (default is 1)\n", + " def __init__(self, radius=1):\n", + " self.radius = radius \n", + " self.area = radius * radius * Circle.pi\n", + "\n", + " # Method for resetting Radius\n", + " def setRadius(self, new_radius):\n", + " self.radius = new_radius\n", + " self.area = new_radius * new_radius * self.pi\n", + "\n", + " # Method for getting Circumference\n", + " def getCircumference(self):\n", + " return self.radius * self.pi * 2\n", + "\n", + "\n", + "c = Circle()\n", + "\n", + "print('Radius is: ',c.radius)\n", + "print('Area is: ',c.area)\n", + "print('Circumference is: ',c.getCircumference())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the \\__init__ method above, in order to calculate the area attribute, we had to call Circle.pi. This is because the object does not yet have its own .pi attribute, so we call the Class Object Attribute pi instead.
\n", + "In the setRadius method, however, we'll be working with an existing Circle object that does have its own pi attribute. Here we can use either Circle.pi or self.pi.

\n", + "Now let's change the radius and see how that affects our Circle object:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Radius is: 2\n", + "Area is: 12.56\n", + "Circumference is: 12.56\n" + ] + } + ], + "source": [ + "c.setRadius(2)\n", + "\n", + "print('Radius is: ',c.radius)\n", + "print('Area is: ',c.area)\n", + "print('Circumference is: ',c.getCircumference())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Notice how we used self. notation to reference attributes of the class within the method calls. Review how the code above works and try creating your own method.\n", + "\n", + "## Inheritance\n", + "\n", + "Inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of base classes (ancestors).\n", + "\n", + "Let's see an example by incorporating our previous work on the Dog class:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "class Animal:\n", + " def __init__(self):\n", + " print(\"Animal created\")\n", + "\n", + " def whoAmI(self):\n", + " print(\"Animal\")\n", + "\n", + " def eat(self):\n", + " print(\"Eating\")\n", + "\n", + "\n", + "class Dog(Animal):\n", + " def __init__(self):\n", + " Animal.__init__(self)\n", + " print(\"Dog created\")\n", + "\n", + " def whoAmI(self):\n", + " print(\"Dog\")\n", + "\n", + " def bark(self):\n", + " print(\"Woof!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Animal created\n", + "Dog created\n" + ] + } + ], + "source": [ + "d = Dog()" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Dog\n" + ] + } + ], + "source": [ + "d.whoAmI()" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Eating\n" + ] + } + ], + "source": [ + "d.eat()" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Woof!\n" + ] + } + ], + "source": [ + "d.bark()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this example, we have two classes: Animal and Dog. The Animal is the base class, the Dog is the derived class. \n", + "\n", + "The derived class inherits the functionality of the base class. \n", + "\n", + "* It is shown by the eat() method. \n", + "\n", + "The derived class modifies existing behavior of the base class.\n", + "\n", + "* shown by the whoAmI() method. \n", + "\n", + "Finally, the derived class extends the functionality of the base class, by defining a new bark() method." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Polymorphism\n", + "\n", + "We've learned that while functions can take in different arguments, methods belong to the objects they act on. In Python, *polymorphism* refers to the way in which different object classes can share the same method name, and those methods can be called from the same place even though a variety of different objects might be passed in. The best way to explain this is by example:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Niko says Woof!\n", + "Felix says Meow!\n" + ] + } + ], + "source": [ + "class Dog:\n", + " def __init__(self, name):\n", + " self.name = name\n", + "\n", + " def speak(self):\n", + " return self.name+' says Woof!'\n", + " \n", + "class Cat:\n", + " def __init__(self, name):\n", + " self.name = name\n", + "\n", + " def speak(self):\n", + " return self.name+' says Meow!' \n", + " \n", + "niko = Dog('Niko')\n", + "felix = Cat('Felix')\n", + "\n", + "print(niko.speak())\n", + "print(felix.speak())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we have a Dog class and a Cat class, and each has a `.speak()` method. When called, each object's `.speak()` method returns a result unique to the object.\n", + "\n", + "There a few different ways to demonstrate polymorphism. First, with a for loop:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Niko says Woof!\n", + "Felix says Meow!\n" + ] + } + ], + "source": [ + "for pet in [niko,felix]:\n", + " print(pet.speak())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Another is with functions:" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Niko says Woof!\n", + "Felix says Meow!\n" + ] + } + ], + "source": [ + "def pet_speak(pet):\n", + " print(pet.speak())\n", + "\n", + "pet_speak(niko)\n", + "pet_speak(felix)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "In both cases we were able to pass in different object types, and we obtained object-specific results from the same mechanism.\n", + "\n", + "A more common practice is to use abstract classes and inheritance. An abstract class is one that never expects to be instantiated. For example, we will never have an Animal object, only Dog and Cat objects, although Dogs and Cats are derived from Animals:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Fido says Woof!\n", + "Isis says Meow!\n" + ] + } + ], + "source": [ + "class Animal:\n", + " def __init__(self, name): # Constructor of the class\n", + " self.name = name\n", + "\n", + " def speak(self): # Abstract method, defined by convention only\n", + " raise NotImplementedError(\"Subclass must implement abstract method\")\n", + "\n", + "\n", + "class Dog(Animal):\n", + " \n", + " def speak(self):\n", + " return self.name+' says Woof!'\n", + " \n", + "class Cat(Animal):\n", + "\n", + " def speak(self):\n", + " return self.name+' says Meow!'\n", + " \n", + "fido = Dog('Fido')\n", + "isis = Cat('Isis')\n", + "\n", + "print(fido.speak())\n", + "print(isis.speak())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Real life examples of polymorphism include:\n", + "* opening different file types - different tools are needed to display Word, pdf and Excel files\n", + "* adding different objects - the `+` operator performs arithmetic and concatenation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Special Methods\n", + "Finally let's go over special methods. Classes in Python can implement certain operations with special method names. These methods are not actually called directly but by Python specific language syntax. For example let's create a Book class:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "class Book:\n", + " def __init__(self, title, author, pages):\n", + " print(\"A book is created\")\n", + " self.title = title\n", + " self.author = author\n", + " self.pages = pages\n", + "\n", + " def __str__(self):\n", + " return \"Title: %s, author: %s, pages: %s\" %(self.title, self.author, self.pages)\n", + "\n", + " def __len__(self):\n", + " return self.pages\n", + "\n", + " def __del__(self):\n", + " print(\"A book is destroyed\")" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A book is created\n", + "Title: Python Rocks!, author: Jose Portilla, pages: 159\n", + "159\n", + "A book is destroyed\n" + ] + } + ], + "source": [ + "book = Book(\"Python Rocks!\", \"Jose Portilla\", 159)\n", + "\n", + "#Special Methods\n", + "print(book)\n", + "print(len(book))\n", + "del book" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " The __init__(), __str__(), __len__() and __del__() methods\n", + "These special methods are defined by their use of underscores. They allow us to use Python specific functions on objects created through our class.\n", + "\n", + "**Great! After this lecture you should have a basic understanding of how to create your own objects with class in Python. You will be utilizing this heavily in your next milestone project!**\n", + "\n", + "For more great resources on this topic, check out:\n", + "\n", + "[Jeff Knupp's Post](https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/)\n", + "\n", + "[Mozilla's Post](https://developer.mozilla.org/en-US/Learn/Python/Quickly_Learn_Object_Oriented_Programming)\n", + "\n", + "[Tutorial's Point](http://www.tutorialspoint.com/python/python_classes_objects.htm)\n", + "\n", + "[Official Documentation](https://docs.python.org/3/tutorial/classes.html)" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/02-Object Oriented Programming Homework-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/02-Object Oriented Programming Homework-checkpoint.ipynb new file mode 100644 index 0000000..3824be7 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/02-Object Oriented Programming Homework-checkpoint.ipynb @@ -0,0 +1,191 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Object Oriented Programming\n", + "## Homework Assignment\n", + "\n", + "#### Problem 1\n", + "Fill in the Line class methods to accept coordinates as a pair of tuples and return the slope and distance of the line." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class Line:\n", + " \n", + " def __init__(self,coor1,coor2):\n", + " pass\n", + " \n", + " def distance(self):\n", + " pass\n", + " \n", + " def slope(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# EXAMPLE OUTPUT\n", + "\n", + "coordinate1 = (3,2)\n", + "coordinate2 = (8,10)\n", + "\n", + "li = Line(coordinate1,coordinate2)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9.433981132056603" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "li.distance()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1.6" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "li.slope()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "________\n", + "#### Problem 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fill in the class " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "class Cylinder:\n", + " \n", + " def __init__(self,height=1,radius=1):\n", + " pass\n", + " \n", + " def volume(self):\n", + " pass\n", + " \n", + " def surface_area(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "# EXAMPLE OUTPUT\n", + "c = Cylinder(2,3)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "56.52" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.volume()" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "94.2" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.surface_area()" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/03-Object Oriented Programming Homework - Solution-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/03-Object Oriented Programming Homework - Solution-checkpoint.ipynb new file mode 100644 index 0000000..81328ce --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/03-Object Oriented Programming Homework - Solution-checkpoint.ipynb @@ -0,0 +1,195 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Object Oriented Programming\n", + "## Homework Assignment\n", + "\n", + "#### Problem 1\n", + "Fill in the Line class methods to accept coordinates as a pair of tuples and return the slope and distance of the line." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class Line(object):\n", + " \n", + " def __init__(self,coor1,coor2):\n", + " self.coor1 = coor1\n", + " self.coor2 = coor2\n", + " \n", + " def distance(self):\n", + " x1,y1 = self.coor1\n", + " x2,y2 = self.coor2\n", + " return ((x2-x1)**2 + (y2-y1)**2)**0.5\n", + " \n", + " def slope(self):\n", + " x1,y1 = self.coor1\n", + " x2,y2 = self.coor2\n", + " return (y2-y1)/(x2-x1)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "coordinate1 = (3,2)\n", + "coordinate2 = (8,10)\n", + "\n", + "li = Line(coordinate1,coordinate2)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9.433981132056603" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "li.distance()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1.6" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "li.slope()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "________\n", + "#### Problem 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fill in the class " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "class Cylinder:\n", + " \n", + " def __init__(self,height=1,radius=1):\n", + " self.height = height\n", + " self.radius = radius\n", + " \n", + " def volume(self):\n", + " return self.height*3.14*(self.radius)**2\n", + " \n", + " def surface_area(self):\n", + " top = 3.14 * (self.radius)**2\n", + " return (2*top) + (2*3.14*self.radius*self.height)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "c = Cylinder(2,3)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "56.52" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.volume()" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "94.2" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.surface_area()" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/04-OOP Challenge-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/04-OOP Challenge-checkpoint.ipynb new file mode 100644 index 0000000..fb60ffb --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/04-OOP Challenge-checkpoint.ipynb @@ -0,0 +1,187 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Object Oriented Programming Challenge\n", + "\n", + "For this challenge, create a bank account class that has two attributes:\n", + "\n", + "* owner\n", + "* balance\n", + "\n", + "and two methods:\n", + "\n", + "* deposit\n", + "* withdraw\n", + "\n", + "As an added requirement, withdrawals may not exceed the available balance.\n", + "\n", + "Instantiate your class, make several deposits and withdrawals, and test to make sure the account can't be overdrawn." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class Account:\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# 1. Instantiate the class\n", + "acct1 = Account('Jose',100)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Account owner: Jose\n", + "Account balance: $100\n" + ] + } + ], + "source": [ + "# 2. Print the object\n", + "print(acct1)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Jose'" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 3. Show the account owner attribute\n", + "acct1.owner" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 4. Show the account balance attribute\n", + "acct1.balance" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Deposit Accepted\n" + ] + } + ], + "source": [ + "# 5. Make a series of deposits and withdrawals\n", + "acct1.deposit(50)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Withdrawal Accepted\n" + ] + } + ], + "source": [ + "acct1.withdraw(75)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Funds Unavailable!\n" + ] + } + ], + "source": [ + "# 6. Make a withdrawal that exceeds the available balance\n", + "acct1.withdraw(500)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Good job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/05-OOP Challenge - Solution-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/05-OOP Challenge - Solution-checkpoint.ipynb new file mode 100644 index 0000000..8c71a3e --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/.ipynb_checkpoints/05-OOP Challenge - Solution-checkpoint.ipynb @@ -0,0 +1,203 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Object Oriented Programming Challenge - Solution\n", + "\n", + "For this challenge, create a bank account class that has two attributes:\n", + "\n", + "* owner\n", + "* balance\n", + "\n", + "and two methods:\n", + "\n", + "* deposit\n", + "* withdraw\n", + "\n", + "As an added requirement, withdrawals may not exceed the available balance.\n", + "\n", + "Instantiate your class, make several deposits and withdrawals, and test to make sure the account can't be overdrawn." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class Account:\n", + " def __init__(self,owner,balance=0):\n", + " self.owner = owner\n", + " self.balance = balance\n", + " \n", + " def __str__(self):\n", + " return f'Account owner: {self.owner}\\nAccount balance: ${self.balance}'\n", + " \n", + " def deposit(self,dep_amt):\n", + " self.balance += dep_amt\n", + " print('Deposit Accepted')\n", + " \n", + " def withdraw(self,wd_amt):\n", + " if self.balance >= wd_amt:\n", + " self.balance -= wd_amt\n", + " print('Withdrawal Accepted')\n", + " else:\n", + " print('Funds Unavailable!')" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# 1. Instantiate the class\n", + "acct1 = Account('Jose',100)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Account owner: Jose\n", + "Account balance: $100\n" + ] + } + ], + "source": [ + "# 2. Print the object\n", + "print(acct1)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Jose'" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 3. Show the account owner attribute\n", + "acct1.owner" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 4. Show the account balance attribute\n", + "acct1.balance" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Deposit Accepted\n" + ] + } + ], + "source": [ + "# 5. Make a series of deposits and withdrawals\n", + "acct1.deposit(50)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Withdrawal Accepted\n" + ] + } + ], + "source": [ + "acct1.withdraw(75)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Funds Unavailable!\n" + ] + } + ], + "source": [ + "# 6. Make a withdrawal that exceeds the available balance\n", + "acct1.withdraw(500)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Good job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/01-Object Oriented Programming.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/01-Object Oriented Programming.ipynb new file mode 100644 index 0000000..4d9e12e --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/01-Object Oriented Programming.ipynb @@ -0,0 +1,792 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Object Oriented Programming\n", + "\n", + "Object Oriented Programming (OOP) tends to be one of the major obstacles for beginners when they are first starting to learn Python.\n", + "\n", + "There are many, many tutorials and lessons covering OOP so feel free to Google search other lessons, and I have also put some links to other useful tutorials online at the bottom of this Notebook.\n", + "\n", + "For this lesson we will construct our knowledge of OOP in Python by building on the following topics:\n", + "\n", + "* Objects\n", + "* Using the *class* keyword\n", + "* Creating class attributes\n", + "* Creating methods in a class\n", + "* Learning about Inheritance\n", + "* Learning about Polymorphism\n", + "* Learning about Special Methods for classes\n", + "\n", + "Lets start the lesson by remembering about the Basic Python Objects. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "lst = [1,2,3]" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Remember how we could call methods on a list?" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "lst.count(2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What we will basically be doing in this lecture is exploring how we could create an Object type like a list. We've already learned about how to create functions. So let's explore Objects in general:\n", + "\n", + "## Objects\n", + "In Python, *everything is an object*. Remember from previous lectures we can use type() to check the type of object something is:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n", + "\n", + "\n", + "\n" + ] + } + ], + "source": [ + "print(type(1))\n", + "print(type([]))\n", + "print(type(()))\n", + "print(type({}))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So we know all these things are objects, so how can we create our own Object types? That is where the class keyword comes in.\n", + "## class\n", + "User defined objects are created using the class keyword. The class is a blueprint that defines the nature of a future object. From classes we can construct instances. An instance is a specific object created from a particular class. For example, above we created the object lst which was an instance of a list object. \n", + "\n", + "Let see how we can use class:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "\n" + ] + } + ], + "source": [ + "# Create a new object type called Sample\n", + "class Sample:\n", + " pass\n", + "\n", + "# Instance of Sample\n", + "x = Sample()\n", + "\n", + "print(type(x))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "By convention we give classes a name that starts with a capital letter. Note how x is now the reference to our new instance of a Sample class. In other words, we **instantiate** the Sample class.\n", + "\n", + "Inside of the class we currently just have pass. But we can define class attributes and methods.\n", + "\n", + "An **attribute** is a characteristic of an object.\n", + "A **method** is an operation we can perform with the object.\n", + "\n", + "For example, we can create a class called Dog. An attribute of a dog may be its breed or its name, while a method of a dog may be defined by a .bark() method which returns a sound.\n", + "\n", + "Let's get a better understanding of attributes through an example.\n", + "\n", + "## Attributes\n", + "The syntax for creating an attribute is:\n", + " \n", + " self.attribute = something\n", + " \n", + "There is a special method called:\n", + "\n", + " __init__()\n", + "\n", + "This method is used to initialize the attributes of an object. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "class Dog:\n", + " def __init__(self,breed):\n", + " self.breed = breed\n", + " \n", + "sam = Dog(breed='Lab')\n", + "frank = Dog(breed='Huskie')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Lets break down what we have above.The special method \n", + "\n", + " __init__() \n", + "is called automatically right after the object has been created:\n", + "\n", + " def __init__(self, breed):\n", + "Each attribute in a class definition begins with a reference to the instance object. It is by convention named self. The breed is the argument. The value is passed during the class instantiation.\n", + "\n", + " self.breed = breed" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we have created two instances of the Dog class. With two breed types, we can then access these attributes like this:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Lab'" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sam.breed" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Huskie'" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "frank.breed" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how we don't have any parentheses after breed; this is because it is an attribute and doesn't take any arguments.\n", + "\n", + "In Python there are also *class object attributes*. These Class Object Attributes are the same for any instance of the class. For example, we could create the attribute *species* for the Dog class. Dogs, regardless of their breed, name, or other attributes, will always be mammals. We apply this logic in the following manner:" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "class Dog:\n", + " \n", + " # Class Object Attribute\n", + " species = 'mammal'\n", + " \n", + " def __init__(self,breed,name):\n", + " self.breed = breed\n", + " self.name = name" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "sam = Dog('Lab','Sam')" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Sam'" + ] + }, + "execution_count": 10, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sam.name" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that the Class Object Attribute is defined outside of any methods in the class. Also by convention, we place them first before the init." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'mammal'" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "sam.species" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Methods\n", + "\n", + "Methods are functions defined inside the body of a class. They are used to perform operations with the attributes of our objects. Methods are a key concept of the OOP paradigm. They are essential to dividing responsibilities in programming, especially in large applications.\n", + "\n", + "You can basically think of methods as functions acting on an Object that take the Object itself into account through its *self* argument.\n", + "\n", + "Let's go through an example of creating a Circle class:" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Radius is: 1\n", + "Area is: 3.14\n", + "Circumference is: 6.28\n" + ] + } + ], + "source": [ + "class Circle:\n", + " pi = 3.14\n", + "\n", + " # Circle gets instantiated with a radius (default is 1)\n", + " def __init__(self, radius=1):\n", + " self.radius = radius \n", + " self.area = radius * radius * Circle.pi\n", + "\n", + " # Method for resetting Radius\n", + " def setRadius(self, new_radius):\n", + " self.radius = new_radius\n", + " self.area = new_radius * new_radius * self.pi\n", + "\n", + " # Method for getting Circumference\n", + " def getCircumference(self):\n", + " return self.radius * self.pi * 2\n", + "\n", + "\n", + "c = Circle()\n", + "\n", + "print('Radius is: ',c.radius)\n", + "print('Area is: ',c.area)\n", + "print('Circumference is: ',c.getCircumference())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the \\__init__ method above, in order to calculate the area attribute, we had to call Circle.pi. This is because the object does not yet have its own .pi attribute, so we call the Class Object Attribute pi instead.
\n", + "In the setRadius method, however, we'll be working with an existing Circle object that does have its own pi attribute. Here we can use either Circle.pi or self.pi.

\n", + "Now let's change the radius and see how that affects our Circle object:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Radius is: 2\n", + "Area is: 12.56\n", + "Circumference is: 12.56\n" + ] + } + ], + "source": [ + "c.setRadius(2)\n", + "\n", + "print('Radius is: ',c.radius)\n", + "print('Area is: ',c.area)\n", + "print('Circumference is: ',c.getCircumference())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Notice how we used self. notation to reference attributes of the class within the method calls. Review how the code above works and try creating your own method.\n", + "\n", + "## Inheritance\n", + "\n", + "Inheritance is a way to form new classes using classes that have already been defined. The newly formed classes are called derived classes, the classes that we derive from are called base classes. Important benefits of inheritance are code reuse and reduction of complexity of a program. The derived classes (descendants) override or extend the functionality of base classes (ancestors).\n", + "\n", + "Let's see an example by incorporating our previous work on the Dog class:" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [], + "source": [ + "class Animal:\n", + " def __init__(self):\n", + " print(\"Animal created\")\n", + "\n", + " def whoAmI(self):\n", + " print(\"Animal\")\n", + "\n", + " def eat(self):\n", + " print(\"Eating\")\n", + "\n", + "\n", + "class Dog(Animal):\n", + " def __init__(self):\n", + " Animal.__init__(self)\n", + " print(\"Dog created\")\n", + "\n", + " def whoAmI(self):\n", + " print(\"Dog\")\n", + "\n", + " def bark(self):\n", + " print(\"Woof!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 15, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Animal created\n", + "Dog created\n" + ] + } + ], + "source": [ + "d = Dog()" + ] + }, + { + "cell_type": "code", + "execution_count": 16, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Dog\n" + ] + } + ], + "source": [ + "d.whoAmI()" + ] + }, + { + "cell_type": "code", + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Eating\n" + ] + } + ], + "source": [ + "d.eat()" + ] + }, + { + "cell_type": "code", + "execution_count": 18, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Woof!\n" + ] + } + ], + "source": [ + "d.bark()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In this example, we have two classes: Animal and Dog. The Animal is the base class, the Dog is the derived class. \n", + "\n", + "The derived class inherits the functionality of the base class. \n", + "\n", + "* It is shown by the eat() method. \n", + "\n", + "The derived class modifies existing behavior of the base class.\n", + "\n", + "* shown by the whoAmI() method. \n", + "\n", + "Finally, the derived class extends the functionality of the base class, by defining a new bark() method." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Polymorphism\n", + "\n", + "We've learned that while functions can take in different arguments, methods belong to the objects they act on. In Python, *polymorphism* refers to the way in which different object classes can share the same method name, and those methods can be called from the same place even though a variety of different objects might be passed in. The best way to explain this is by example:" + ] + }, + { + "cell_type": "code", + "execution_count": 19, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Niko says Woof!\n", + "Felix says Meow!\n" + ] + } + ], + "source": [ + "class Dog:\n", + " def __init__(self, name):\n", + " self.name = name\n", + "\n", + " def speak(self):\n", + " return self.name+' says Woof!'\n", + " \n", + "class Cat:\n", + " def __init__(self, name):\n", + " self.name = name\n", + "\n", + " def speak(self):\n", + " return self.name+' says Meow!' \n", + " \n", + "niko = Dog('Niko')\n", + "felix = Cat('Felix')\n", + "\n", + "print(niko.speak())\n", + "print(felix.speak())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we have a Dog class and a Cat class, and each has a `.speak()` method. When called, each object's `.speak()` method returns a result unique to the object.\n", + "\n", + "There a few different ways to demonstrate polymorphism. First, with a for loop:" + ] + }, + { + "cell_type": "code", + "execution_count": 20, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Niko says Woof!\n", + "Felix says Meow!\n" + ] + } + ], + "source": [ + "for pet in [niko,felix]:\n", + " print(pet.speak())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Another is with functions:" + ] + }, + { + "cell_type": "code", + "execution_count": 21, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Niko says Woof!\n", + "Felix says Meow!\n" + ] + } + ], + "source": [ + "def pet_speak(pet):\n", + " print(pet.speak())\n", + "\n", + "pet_speak(niko)\n", + "pet_speak(felix)" + ] + }, + { + "cell_type": "markdown", + "metadata": { + "slideshow": { + "slide_type": "slide" + } + }, + "source": [ + "In both cases we were able to pass in different object types, and we obtained object-specific results from the same mechanism.\n", + "\n", + "A more common practice is to use abstract classes and inheritance. An abstract class is one that never expects to be instantiated. For example, we will never have an Animal object, only Dog and Cat objects, although Dogs and Cats are derived from Animals:" + ] + }, + { + "cell_type": "code", + "execution_count": 22, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Fido says Woof!\n", + "Isis says Meow!\n" + ] + } + ], + "source": [ + "class Animal:\n", + " def __init__(self, name): # Constructor of the class\n", + " self.name = name\n", + "\n", + " def speak(self): # Abstract method, defined by convention only\n", + " raise NotImplementedError(\"Subclass must implement abstract method\")\n", + "\n", + "\n", + "class Dog(Animal):\n", + " \n", + " def speak(self):\n", + " return self.name+' says Woof!'\n", + " \n", + "class Cat(Animal):\n", + "\n", + " def speak(self):\n", + " return self.name+' says Meow!'\n", + " \n", + "fido = Dog('Fido')\n", + "isis = Cat('Isis')\n", + "\n", + "print(fido.speak())\n", + "print(isis.speak())" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Real life examples of polymorphism include:\n", + "* opening different file types - different tools are needed to display Word, pdf and Excel files\n", + "* adding different objects - the `+` operator performs arithmetic and concatenation" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Special Methods\n", + "Finally let's go over special methods. Classes in Python can implement certain operations with special method names. These methods are not actually called directly but by Python specific language syntax. For example let's create a Book class:" + ] + }, + { + "cell_type": "code", + "execution_count": 23, + "metadata": {}, + "outputs": [], + "source": [ + "class Book:\n", + " def __init__(self, title, author, pages):\n", + " print(\"A book is created\")\n", + " self.title = title\n", + " self.author = author\n", + " self.pages = pages\n", + "\n", + " def __str__(self):\n", + " return \"Title: %s, author: %s, pages: %s\" %(self.title, self.author, self.pages)\n", + "\n", + " def __len__(self):\n", + " return self.pages\n", + "\n", + " def __del__(self):\n", + " print(\"A book is destroyed\")" + ] + }, + { + "cell_type": "code", + "execution_count": 24, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "A book is created\n", + "Title: Python Rocks!, author: Jose Portilla, pages: 159\n", + "159\n", + "A book is destroyed\n" + ] + } + ], + "source": [ + "book = Book(\"Python Rocks!\", \"Jose Portilla\", 159)\n", + "\n", + "#Special Methods\n", + "print(book)\n", + "print(len(book))\n", + "del book" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + " The __init__(), __str__(), __len__() and __del__() methods\n", + "These special methods are defined by their use of underscores. They allow us to use Python specific functions on objects created through our class.\n", + "\n", + "**Great! After this lecture you should have a basic understanding of how to create your own objects with class in Python. You will be utilizing this heavily in your next milestone project!**\n", + "\n", + "For more great resources on this topic, check out:\n", + "\n", + "[Jeff Knupp's Post](https://jeffknupp.com/blog/2014/06/18/improve-your-python-python-classes-and-object-oriented-programming/)\n", + "\n", + "[Mozilla's Post](https://developer.mozilla.org/en-US/Learn/Python/Quickly_Learn_Object_Oriented_Programming)\n", + "\n", + "[Tutorial's Point](http://www.tutorialspoint.com/python/python_classes_objects.htm)\n", + "\n", + "[Official Documentation](https://docs.python.org/3/tutorial/classes.html)" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/02-Object Oriented Programming Homework.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/02-Object Oriented Programming Homework.ipynb new file mode 100644 index 0000000..3824be7 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/02-Object Oriented Programming Homework.ipynb @@ -0,0 +1,191 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Object Oriented Programming\n", + "## Homework Assignment\n", + "\n", + "#### Problem 1\n", + "Fill in the Line class methods to accept coordinates as a pair of tuples and return the slope and distance of the line." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class Line:\n", + " \n", + " def __init__(self,coor1,coor2):\n", + " pass\n", + " \n", + " def distance(self):\n", + " pass\n", + " \n", + " def slope(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# EXAMPLE OUTPUT\n", + "\n", + "coordinate1 = (3,2)\n", + "coordinate2 = (8,10)\n", + "\n", + "li = Line(coordinate1,coordinate2)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9.433981132056603" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "li.distance()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1.6" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "li.slope()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "________\n", + "#### Problem 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fill in the class " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "class Cylinder:\n", + " \n", + " def __init__(self,height=1,radius=1):\n", + " pass\n", + " \n", + " def volume(self):\n", + " pass\n", + " \n", + " def surface_area(self):\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "# EXAMPLE OUTPUT\n", + "c = Cylinder(2,3)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "56.52" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.volume()" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "94.2" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.surface_area()" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/03-Object Oriented Programming Homework - Solution.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/03-Object Oriented Programming Homework - Solution.ipynb new file mode 100644 index 0000000..81328ce --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/03-Object Oriented Programming Homework - Solution.ipynb @@ -0,0 +1,195 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Object Oriented Programming\n", + "## Homework Assignment\n", + "\n", + "#### Problem 1\n", + "Fill in the Line class methods to accept coordinates as a pair of tuples and return the slope and distance of the line." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class Line(object):\n", + " \n", + " def __init__(self,coor1,coor2):\n", + " self.coor1 = coor1\n", + " self.coor2 = coor2\n", + " \n", + " def distance(self):\n", + " x1,y1 = self.coor1\n", + " x2,y2 = self.coor2\n", + " return ((x2-x1)**2 + (y2-y1)**2)**0.5\n", + " \n", + " def slope(self):\n", + " x1,y1 = self.coor1\n", + " x2,y2 = self.coor2\n", + " return (y2-y1)/(x2-x1)" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "coordinate1 = (3,2)\n", + "coordinate2 = (8,10)\n", + "\n", + "li = Line(coordinate1,coordinate2)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "9.433981132056603" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "li.distance()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "1.6" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "li.slope()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "________\n", + "#### Problem 2" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Fill in the class " + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "class Cylinder:\n", + " \n", + " def __init__(self,height=1,radius=1):\n", + " self.height = height\n", + " self.radius = radius\n", + " \n", + " def volume(self):\n", + " return self.height*3.14*(self.radius)**2\n", + " \n", + " def surface_area(self):\n", + " top = 3.14 * (self.radius)**2\n", + " return (2*top) + (2*3.14*self.radius*self.height)" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "c = Cylinder(2,3)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "56.52" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.volume()" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "94.2" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "c.surface_area()" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/04-OOP Challenge.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/04-OOP Challenge.ipynb new file mode 100644 index 0000000..fb60ffb --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/04-OOP Challenge.ipynb @@ -0,0 +1,187 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Object Oriented Programming Challenge\n", + "\n", + "For this challenge, create a bank account class that has two attributes:\n", + "\n", + "* owner\n", + "* balance\n", + "\n", + "and two methods:\n", + "\n", + "* deposit\n", + "* withdraw\n", + "\n", + "As an added requirement, withdrawals may not exceed the available balance.\n", + "\n", + "Instantiate your class, make several deposits and withdrawals, and test to make sure the account can't be overdrawn." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class Account:\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# 1. Instantiate the class\n", + "acct1 = Account('Jose',100)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Account owner: Jose\n", + "Account balance: $100\n" + ] + } + ], + "source": [ + "# 2. Print the object\n", + "print(acct1)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Jose'" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 3. Show the account owner attribute\n", + "acct1.owner" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 4. Show the account balance attribute\n", + "acct1.balance" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Deposit Accepted\n" + ] + } + ], + "source": [ + "# 5. Make a series of deposits and withdrawals\n", + "acct1.deposit(50)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Withdrawal Accepted\n" + ] + } + ], + "source": [ + "acct1.withdraw(75)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Funds Unavailable!\n" + ] + } + ], + "source": [ + "# 6. Make a withdrawal that exceeds the available balance\n", + "acct1.withdraw(500)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Good job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/05-OOP Challenge - Solution.ipynb b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/05-OOP Challenge - Solution.ipynb new file mode 100644 index 0000000..8c71a3e --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/05-Object Oriented Programming/05-OOP Challenge - Solution.ipynb @@ -0,0 +1,203 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Object Oriented Programming Challenge - Solution\n", + "\n", + "For this challenge, create a bank account class that has two attributes:\n", + "\n", + "* owner\n", + "* balance\n", + "\n", + "and two methods:\n", + "\n", + "* deposit\n", + "* withdraw\n", + "\n", + "As an added requirement, withdrawals may not exceed the available balance.\n", + "\n", + "Instantiate your class, make several deposits and withdrawals, and test to make sure the account can't be overdrawn." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "class Account:\n", + " def __init__(self,owner,balance=0):\n", + " self.owner = owner\n", + " self.balance = balance\n", + " \n", + " def __str__(self):\n", + " return f'Account owner: {self.owner}\\nAccount balance: ${self.balance}'\n", + " \n", + " def deposit(self,dep_amt):\n", + " self.balance += dep_amt\n", + " print('Deposit Accepted')\n", + " \n", + " def withdraw(self,wd_amt):\n", + " if self.balance >= wd_amt:\n", + " self.balance -= wd_amt\n", + " print('Withdrawal Accepted')\n", + " else:\n", + " print('Funds Unavailable!')" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "# 1. Instantiate the class\n", + "acct1 = Account('Jose',100)" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Account owner: Jose\n", + "Account balance: $100\n" + ] + } + ], + "source": [ + "# 2. Print the object\n", + "print(acct1)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'Jose'" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 3. Show the account owner attribute\n", + "acct1.owner" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "100" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# 4. Show the account balance attribute\n", + "acct1.balance" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Deposit Accepted\n" + ] + } + ], + "source": [ + "# 5. Make a series of deposits and withdrawals\n", + "acct1.deposit(50)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Withdrawal Accepted\n" + ] + } + ], + "source": [ + "acct1.withdraw(75)" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Funds Unavailable!\n" + ] + } + ], + "source": [ + "# 6. Make a withdrawal that exceeds the available balance\n", + "acct1.withdraw(500)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Good job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/.ipynb_checkpoints/01-Modules and Packages-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/.ipynb_checkpoints/01-Modules and Packages-checkpoint.ipynb new file mode 100644 index 0000000..786b048 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/.ipynb_checkpoints/01-Modules and Packages-checkpoint.ipynb @@ -0,0 +1,205 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Modules and Packages\n", + "\n", + "There's no code here because it didn't really make sense for the section. Check out the video lectures for more info and the resources for this.\n", + "\n", + "Here is the best source the official docs!\n", + "https://docs.python.org/3/tutorial/modules.html#packages\n", + "\n", + "But I really like the info here: https://python4astronomers.github.io/installation/packages.html\n", + "\n", + "Here's some extra info to help:" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Modules in Python are simply Python files with the .py extension, which implement a set of functions. Modules are imported from other modules using the import command.\n", + "\n", + "To import a module, we use the import command. Check out the full list of built-in modules in the Python standard library [here](https://docs.python.org/3/py-modindex.html).\n", + "\n", + "The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will not be loaded twice but once only - so local variables inside the module act as a \"singleton\" - they are initialized only once.\n", + "\n", + "If we want to import the math module, we simply import the name of the module:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "# import the library\n", + "import math" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 2, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# use it (ceiling rounding)\n", + "math.ceil(2.4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exploring built-in modules\n", + "Two very important functions come in handy when exploring modules in Python - the dir and help functions.\n", + "\n", + "We can look for which functions are implemented in each module by using the dir function:" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']\n" + ] + } + ], + "source": [ + "print(dir(math))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When we find the function in the module we want to use, we can read about it more using the help function, inside the Python interpreter:\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on built-in function ceil in module math:\n", + "\n", + "ceil(...)\n", + " ceil(x)\n", + " \n", + " Return the ceiling of x as an Integral.\n", + " This is the smallest integer >= x.\n", + "\n" + ] + } + ], + "source": [ + "help(math.ceil)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Writing modules\n", + "Writing Python modules is very simple. To create a module of your own, simply create a new .py file with the module name, and then import it using the Python file name (without the .py extension) using the import command.\n", + "\n", + "## Writing packages\n", + "Packages are name-spaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.\n", + "\n", + "Each package in Python is a directory which MUST contain a special file called **\\__init\\__.py**. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.\n", + "\n", + "If we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the **\\__init\\__.py** file inside the foo directory.\n", + "\n", + "To use the module bar, we can import it in two ways:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Just an example, this won't work\n", + "import foo.bar" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# OR could do it this way\n", + "from foo import bar" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the first method, we must use the foo prefix whenever we access the module bar. In the second method, we don't, because we import the module to our module's name-space.\n", + "\n", + "The **\\__init\\__.py** file can also decide which modules the package exports as the API, while keeping other modules internal, by overriding the **\\__all\\__** variable, like so:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "__init__.py:\n", + "\n", + "__all__ = [\"bar\"]" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/.ipynb_checkpoints/Useful_Info_Notebook-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/.ipynb_checkpoints/Useful_Info_Notebook-checkpoint.ipynb new file mode 100644 index 0000000..f7317b7 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/.ipynb_checkpoints/Useful_Info_Notebook-checkpoint.ipynb @@ -0,0 +1,386 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Modules and Packages\n", + "\n", + "In this section we briefly:\n", + "* code out a basic module and show how to import it into a Python script\n", + "* run a Python script from a Jupyter cell\n", + "* show how command line arguments can be passed into a script\n", + "\n", + "Check out the video lectures for more info and resources for this.\n", + "\n", + "The best online resource is the official docs:\n", + "https://docs.python.org/3/tutorial/modules.html#packages\n", + "\n", + "But I really like the info here: https://python4astronomers.github.io/installation/packages.html\n", + "\n", + "## Writing modules" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Writing file1.py\n" + ] + } + ], + "source": [ + "%%writefile file1.py\n", + "def myfunc(x):\n", + " return [num for num in range(x) if num%2==0]\n", + "list1 = myfunc(11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**file1.py** is going to be used as a module.\n", + "\n", + "Note that it doesn't print or return anything,\n", + "it just defines a function called *myfunc* and a variable called *list1*.\n", + "## Writing scripts" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Writing file2.py\n" + ] + } + ], + "source": [ + "%%writefile file2.py\n", + "import file1\n", + "file1.list1.append(12)\n", + "print(file1.list1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**file2.py** is a Python script.\n", + "\n", + "First, we import our **file1** module (note the lack of a .py extension)
\n", + "Next, we access the *list1* variable inside **file1**, and perform a list method on it.
\n", + "`.append(12)` proves we're working with a Python list object, and not just a string.
\n", + "Finally, we tell our script to print the modified list.\n", + "## Running scripts" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 2, 4, 6, 8, 10, 12]\n" + ] + } + ], + "source": [ + "! python file2.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we run our script from the command line. The exclamation point is a Jupyter trick that lets you run command line statements from inside a jupyter cell." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 2, 4, 6, 8, 10]\n" + ] + } + ], + "source": [ + "import file1\n", + "print(file1.list1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The above cell proves that we never altered **file1.py**, we just appended a number to the list *after* it was brought into **file2**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Passing command line arguments\n", + "Python's `sys` module gives you access to command line arguments when calling scripts." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Writing file3.py\n" + ] + } + ], + "source": [ + "%%writefile file3.py\n", + "import sys\n", + "import file1\n", + "num = int(sys.argv[1])\n", + "print(file1.myfunc(num))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that we selected the second item in the list of arguments with `sys.argv[1]`.
\n", + "This is because the list created with `sys.argv` always starts with the name of the file being used.
" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]\n" + ] + } + ], + "source": [ + "! python file3.py 21" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we're passing 21 to be the upper range value used by the *myfunc* function in **list1.py**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Understanding modules\n", + "\n", + "Modules in Python are simply Python files with the .py extension, which implement a set of functions. Modules are imported from other modules using the import command.\n", + "\n", + "To import a module, we use the import command. Check out the full list of built-in modules in the Python standard library [here](https://docs.python.org/3/py-modindex.html).\n", + "\n", + "The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will not be loaded twice but once only - so local variables inside the module act as a \"singleton\" - they are initialized only once.\n", + "\n", + "If we want to import the math module, we simply import the name of the module:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "# import the library\n", + "import math" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# use it (ceiling rounding)\n", + "math.ceil(2.4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exploring built-in modules\n", + "Two very important functions come in handy when exploring modules in Python - the dir and help functions.\n", + "\n", + "We can look for which functions are implemented in each module by using the dir function:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']\n" + ] + } + ], + "source": [ + "print(dir(math))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When we find the function in the module we want to use, we can read about it more using the help function, inside the Python interpreter:\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on built-in function ceil in module math:\n", + "\n", + "ceil(...)\n", + " ceil(x)\n", + " \n", + " Return the ceiling of x as an Integral.\n", + " This is the smallest integer >= x.\n", + "\n" + ] + } + ], + "source": [ + "help(math.ceil)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Writing modules\n", + "Writing Python modules is very simple. To create a module of your own, simply create a new .py file with the module name, and then import it using the Python file name (without the .py extension) using the import command.\n", + "\n", + "## Writing packages\n", + "Packages are name-spaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.\n", + "\n", + "Each package in Python is a directory which MUST contain a special file called **\\__init\\__.py**. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.\n", + "\n", + "If we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the **\\__init\\__.py** file inside the foo directory.\n", + "\n", + "To use the module bar, we can import it in two ways:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Just an example, this won't work\n", + "import foo.bar" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# OR could do it this way\n", + "from foo import bar" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the first method, we must use the foo prefix whenever we access the module bar. In the second method, we don't, because we import the module to our module's name-space.\n", + "\n", + "The **\\__init\\__.py** file can also decide which modules the package exports as the API, while keeping other modules internal, by overriding the **\\__all\\__** variable, like so:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "__init__.py:\n", + "\n", + "__all__ = [\"bar\"]" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/__init__.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/__pycache__/__init__.cpython-36.pyc b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..d4fedf2 Binary files /dev/null and b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/__pycache__/__init__.cpython-36.pyc differ diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/__pycache__/mysubscript.cpython-36.pyc b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/__pycache__/mysubscript.cpython-36.pyc new file mode 100644 index 0000000..24a8ba4 Binary files /dev/null and b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/__pycache__/mysubscript.cpython-36.pyc differ diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/mysubscript.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/mysubscript.py new file mode 100644 index 0000000..0c4217f --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/SubPackage/mysubscript.py @@ -0,0 +1,2 @@ +def sub_report(): + print("Hey Im a function inside mysubscript") \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/__init__.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/__pycache__/__init__.cpython-36.pyc b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/__pycache__/__init__.cpython-36.pyc new file mode 100644 index 0000000..36ec225 Binary files /dev/null and b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/__pycache__/__init__.cpython-36.pyc differ diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/__pycache__/some_main_script.cpython-36.pyc b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/__pycache__/some_main_script.cpython-36.pyc new file mode 100644 index 0000000..c0b0864 Binary files /dev/null and b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/__pycache__/some_main_script.cpython-36.pyc differ diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/some_main_script.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/some_main_script.py new file mode 100644 index 0000000..b1c7287 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/MyMainPackage/some_main_script.py @@ -0,0 +1,2 @@ +def report_main(): + print("Hey I am in some_main_script in main package.") \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/mymodule.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/mymodule.py new file mode 100644 index 0000000..5970453 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/mymodule.py @@ -0,0 +1,2 @@ +def my_func(): + print("Hey I am in mymodule.py") \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/myprogram.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/myprogram.py new file mode 100644 index 0000000..e08a2cb --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/00-Modules_and_Packages/myprogram.py @@ -0,0 +1,6 @@ +from MyMainPackage.some_main_script import report_main +from MyMainPackage.SubPackage import mysubscript + +report_main() + +mysubscript.sub_report() diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/01-Name_and_Main/Explanation.txt b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/01-Name_and_Main/Explanation.txt new file mode 100644 index 0000000..19eb661 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/01-Name_and_Main/Explanation.txt @@ -0,0 +1,76 @@ +Sometimes when you are importing from a module, you would like to know whether +a modules function is being used as an import, or if you are using the original +.py file of that module. In this case we can use the: + + if __name__ == "__main__": + +line to determine this. For example: + +When your script is run by passing it as a command to the Python interpreter: + + python myscript.py + +all of the code that is at indentation level 0 gets executed. Functions and +classes that are defined are, well, defined, but none of their code gets ran. +Unlike other languages, there's no main() function that gets run automatically +- the main() function is implicitly all the code at the top level. + +In this case, the top-level code is an if block. __name__ is a built-in variable + which evaluate to the name of the current module. However, if a module is being + run directly (as in myscript.py above), then __name__ instead is set to the + string "__main__". Thus, you can test whether your script is being run directly + or being imported by something else by testing + + if __name__ == "__main__": + ... + +If that code is being imported into another module, the various function and +class definitions will be imported, but the main() code won't get run. As a +basic example, consider the following two scripts: + + # file one.py + def func(): + print("func() in one.py") + + print("top-level in one.py") + + if __name__ == "__main__": + print("one.py is being run directly") + else: + print("one.py is being imported into another module") + +and then: + + # file two.py + import one + + print("top-level in two.py") + one.func() + + if __name__ == "__main__": + print("two.py is being run directly") + else: + print("two.py is being imported into another module") + +Now, if you invoke the interpreter as + + python one.py + +The output will be + + top-level in one.py + +one.py is being run directly +If you run two.py instead: + + python two.py + +You get + + top-level in one.py + one.py is being imported into another module + top-level in two.py + func() in one.py + two.py is being run directly + +Thus, when module one gets loaded, its __name__ equals "one" instead of __main__. diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/01-Name_and_Main/one.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/01-Name_and_Main/one.py new file mode 100644 index 0000000..41818a6 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/01-Name_and_Main/one.py @@ -0,0 +1,9 @@ +def func(): + print("func() ran in one.py") + +print("top-level print inside of one.py") + +if __name__ == "__main__": + print("one.py is being run directly") +else: + print("one.py is being imported into another module") diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/01-Name_and_Main/two.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/01-Name_and_Main/two.py new file mode 100644 index 0000000..ec63049 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/01-Name_and_Main/two.py @@ -0,0 +1,10 @@ +import one + +print("top-level in two.py") + +one.func() + +if __name__ == "__main__": + print("two.py is being run directly") +else: + print("two.py is being imported into another module") diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/Useful_Info_Notebook.ipynb b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/Useful_Info_Notebook.ipynb new file mode 100644 index 0000000..f7317b7 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/Useful_Info_Notebook.ipynb @@ -0,0 +1,386 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Modules and Packages\n", + "\n", + "In this section we briefly:\n", + "* code out a basic module and show how to import it into a Python script\n", + "* run a Python script from a Jupyter cell\n", + "* show how command line arguments can be passed into a script\n", + "\n", + "Check out the video lectures for more info and resources for this.\n", + "\n", + "The best online resource is the official docs:\n", + "https://docs.python.org/3/tutorial/modules.html#packages\n", + "\n", + "But I really like the info here: https://python4astronomers.github.io/installation/packages.html\n", + "\n", + "## Writing modules" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Writing file1.py\n" + ] + } + ], + "source": [ + "%%writefile file1.py\n", + "def myfunc(x):\n", + " return [num for num in range(x) if num%2==0]\n", + "list1 = myfunc(11)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**file1.py** is going to be used as a module.\n", + "\n", + "Note that it doesn't print or return anything,\n", + "it just defines a function called *myfunc* and a variable called *list1*.\n", + "## Writing scripts" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Writing file2.py\n" + ] + } + ], + "source": [ + "%%writefile file2.py\n", + "import file1\n", + "file1.list1.append(12)\n", + "print(file1.list1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**file2.py** is a Python script.\n", + "\n", + "First, we import our **file1** module (note the lack of a .py extension)
\n", + "Next, we access the *list1* variable inside **file1**, and perform a list method on it.
\n", + "`.append(12)` proves we're working with a Python list object, and not just a string.
\n", + "Finally, we tell our script to print the modified list.\n", + "## Running scripts" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 2, 4, 6, 8, 10, 12]\n" + ] + } + ], + "source": [ + "! python file2.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we run our script from the command line. The exclamation point is a Jupyter trick that lets you run command line statements from inside a jupyter cell." + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 2, 4, 6, 8, 10]\n" + ] + } + ], + "source": [ + "import file1\n", + "print(file1.list1)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "The above cell proves that we never altered **file1.py**, we just appended a number to the list *after* it was brought into **file2**." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Passing command line arguments\n", + "Python's `sys` module gives you access to command line arguments when calling scripts." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Writing file3.py\n" + ] + } + ], + "source": [ + "%%writefile file3.py\n", + "import sys\n", + "import file1\n", + "num = int(sys.argv[1])\n", + "print(file1.myfunc(num))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note that we selected the second item in the list of arguments with `sys.argv[1]`.
\n", + "This is because the list created with `sys.argv` always starts with the name of the file being used.
" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "[0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20]\n" + ] + } + ], + "source": [ + "! python file3.py 21" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Here we're passing 21 to be the upper range value used by the *myfunc* function in **list1.py**" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Understanding modules\n", + "\n", + "Modules in Python are simply Python files with the .py extension, which implement a set of functions. Modules are imported from other modules using the import command.\n", + "\n", + "To import a module, we use the import command. Check out the full list of built-in modules in the Python standard library [here](https://docs.python.org/3/py-modindex.html).\n", + "\n", + "The first time a module is loaded into a running Python script, it is initialized by executing the code in the module once. If another module in your code imports the same module again, it will not be loaded twice but once only - so local variables inside the module act as a \"singleton\" - they are initialized only once.\n", + "\n", + "If we want to import the math module, we simply import the name of the module:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [], + "source": [ + "# import the library\n", + "import math" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "3" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "# use it (ceiling rounding)\n", + "math.ceil(2.4)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Exploring built-in modules\n", + "Two very important functions come in handy when exploring modules in Python - the dir and help functions.\n", + "\n", + "We can look for which functions are implemented in each module by using the dir function:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc']\n" + ] + } + ], + "source": [ + "print(dir(math))" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "When we find the function in the module we want to use, we can read about it more using the help function, inside the Python interpreter:\n", + "\n" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Help on built-in function ceil in module math:\n", + "\n", + "ceil(...)\n", + " ceil(x)\n", + " \n", + " Return the ceiling of x as an Integral.\n", + " This is the smallest integer >= x.\n", + "\n" + ] + } + ], + "source": [ + "help(math.ceil)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Writing modules\n", + "Writing Python modules is very simple. To create a module of your own, simply create a new .py file with the module name, and then import it using the Python file name (without the .py extension) using the import command.\n", + "\n", + "## Writing packages\n", + "Packages are name-spaces which contain multiple packages and modules themselves. They are simply directories, but with a twist.\n", + "\n", + "Each package in Python is a directory which MUST contain a special file called **\\__init\\__.py**. This file can be empty, and it indicates that the directory it contains is a Python package, so it can be imported the same way a module can be imported.\n", + "\n", + "If we create a directory called foo, which marks the package name, we can then create a module inside that package called bar. We also must not forget to add the **\\__init\\__.py** file inside the foo directory.\n", + "\n", + "To use the module bar, we can import it in two ways:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "# Just an example, this won't work\n", + "import foo.bar" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# OR could do it this way\n", + "from foo import bar" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "In the first method, we must use the foo prefix whenever we access the module bar. In the second method, we don't, because we import the module to our module's name-space.\n", + "\n", + "The **\\__init\\__.py** file can also decide which modules the package exports as the API, while keeping other modules internal, by overriding the **\\__all\\__** variable, like so:" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": { + "collapsed": true + }, + "outputs": [], + "source": [ + "__init__.py:\n", + "\n", + "__all__ = [\"bar\"]" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/__pycache__/file1.cpython-36.pyc b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/__pycache__/file1.cpython-36.pyc new file mode 100644 index 0000000..33faa98 Binary files /dev/null and b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/__pycache__/file1.cpython-36.pyc differ diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/file1.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/file1.py new file mode 100644 index 0000000..67b5936 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/file1.py @@ -0,0 +1,3 @@ +def myfunc(x): + return [num for num in range(x) if num%2==0] +list1 = myfunc(11) \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/file2.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/file2.py new file mode 100644 index 0000000..4b63a64 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/file2.py @@ -0,0 +1,3 @@ +import file1 +file1.list1.append(12) +print(file1.list1) \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/06-Modules and Packages/file3.py b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/file3.py new file mode 100644 index 0000000..dcc44ea --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/06-Modules and Packages/file3.py @@ -0,0 +1,4 @@ +import sys +import file1 +num = int(sys.argv[1]) +print(file1.myfunc(num)) \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/01-Errors and Exceptions Handling-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/01-Errors and Exceptions Handling-checkpoint.ipynb new file mode 100644 index 0000000..c135164 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/01-Errors and Exceptions Handling-checkpoint.ipynb @@ -0,0 +1,463 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Errors and Exception Handling\n", + "\n", + "In this lecture we will learn about Errors and Exception Handling in Python. You've definitely already encountered errors by this point in the course. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "EOL while scanning string literal (, line 1)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m print('Hello)\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m EOL while scanning string literal\n" + ] + } + ], + "source": [ + "print('Hello)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how we get a SyntaxError, with the further description that it was an EOL (End of Line Error) while scanning the string literal. This is specific enough for us to see that we forgot a single quote at the end of the line. Understanding these various error types will help you debug your code much faster. \n", + "\n", + "This type of error and description is known as an Exception. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal.\n", + "\n", + "You can check out the full list of built-in exceptions [here](https://docs.python.org/3/library/exceptions.html). Now let's learn how to handle errors and exceptions in our own code." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## try and except\n", + "\n", + "The basic terminology and syntax used to handle errors in Python are the try and except statements. The code which can cause an exception to occur is put in the try block and the handling of the exception is then implemented in the except block of code. The syntax follows:\n", + "\n", + " try:\n", + " You do your operations here...\n", + " ...\n", + " except ExceptionI:\n", + " If there is ExceptionI, then execute this block.\n", + " except ExceptionII:\n", + " If there is ExceptionII, then execute this block.\n", + " ...\n", + " else:\n", + " If there is no exception then execute this block. \n", + "\n", + "We can also just check for any exception with just using except: To get a better understanding of all this let's check out an example: We will look at some code that opens and writes a file:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Content written successfully\n" + ] + } + ], + "source": [ + "try:\n", + " f = open('testfile','w')\n", + " f.write('Test write this')\n", + "except IOError:\n", + " # This will only check for an IOError exception and then execute this print statement\n", + " print(\"Error: Could not find file or read data\")\n", + "else:\n", + " print(\"Content written successfully\")\n", + " f.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now let's see what would happen if we did not have write permission (opening only with 'r'):" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error: Could not find file or read data\n" + ] + } + ], + "source": [ + "try:\n", + " f = open('testfile','r')\n", + " f.write('Test write this')\n", + "except IOError:\n", + " # This will only check for an IOError exception and then execute this print statement\n", + " print(\"Error: Could not find file or read data\")\n", + "else:\n", + " print(\"Content written successfully\")\n", + " f.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Notice how we only printed a statement! The code still ran and we were able to continue doing actions and running code blocks. This is extremely useful when you have to account for possible input errors in your code. You can be prepared for the error and keep running code, instead of your code just breaking as we saw above.\n", + "\n", + "We could have also just said except: if we weren't sure what exception would occur. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error: Could not find file or read data\n" + ] + } + ], + "source": [ + "try:\n", + " f = open('testfile','r')\n", + " f.write('Test write this')\n", + "except:\n", + " # This will check for any exception and then execute this print statement\n", + " print(\"Error: Could not find file or read data\")\n", + "else:\n", + " print(\"Content written successfully\")\n", + " f.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Now we don't actually need to memorize that list of exception types! Now what if we kept wanting to run code after the exception occurred? This is where finally comes in.\n", + "## finally\n", + "The finally: block of code will always be run regardless if there was an exception in the try code block. The syntax is:\n", + "\n", + " try:\n", + " Code block here\n", + " ...\n", + " Due to any exception, this code may be skipped!\n", + " finally:\n", + " This code block would always be executed.\n", + "\n", + "For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Always execute finally code blocks\n" + ] + } + ], + "source": [ + "try:\n", + " f = open(\"testfile\", \"w\")\n", + " f.write(\"Test write statement\")\n", + " f.close()\n", + "finally:\n", + " print(\"Always execute finally code blocks\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use this in conjunction with except. Let's see a new example that will take into account a user providing the wrong input:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "def askint():\n", + " try:\n", + " val = int(input(\"Please enter an integer: \"))\n", + " except:\n", + " print(\"Looks like you did not enter an integer!\")\n", + "\n", + " finally:\n", + " print(\"Finally, I executed!\")\n", + " print(val)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: 5\n", + "Finally, I executed!\n", + "5\n" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: five\n", + "Looks like you did not enter an integer!\n", + "Finally, I executed!\n" + ] + }, + { + "ename": "UnboundLocalError", + "evalue": "local variable 'val' referenced before assignment", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0maskint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;32m\u001b[0m in \u001b[0;36maskint\u001b[1;34m()\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[1;32mfinally\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Finally, I executed!\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 9\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mval\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mUnboundLocalError\u001b[0m: local variable 'val' referenced before assignment" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how we got an error when trying to print val (because it was never properly assigned). Let's remedy this by asking the user and checking to make sure the input type is an integer:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "def askint():\n", + " try:\n", + " val = int(input(\"Please enter an integer: \"))\n", + " except:\n", + " print(\"Looks like you did not enter an integer!\")\n", + " val = int(input(\"Try again-Please enter an integer: \"))\n", + " finally:\n", + " print(\"Finally, I executed!\")\n", + " print(val)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: five\n", + "Looks like you did not enter an integer!\n", + "Try again-Please enter an integer: four\n", + "Finally, I executed!\n" + ] + }, + { + "ename": "ValueError", + "evalue": "invalid literal for int() with base 10: 'four'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36maskint\u001b[1;34m()\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mval\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Please enter an integer: \"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[1;32mexcept\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: 'five'", + "\nDuring handling of the above exception, another exception occurred:\n", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0maskint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;32m\u001b[0m in \u001b[0;36maskint\u001b[1;34m()\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mexcept\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Looks like you did not enter an integer!\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[0mval\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Try again-Please enter an integer: \"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 7\u001b[0m \u001b[1;32mfinally\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Finally, I executed!\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: 'four'" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hmmm...that only did one check. How can we continually keep checking? We can use a while loop!" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def askint():\n", + " while True:\n", + " try:\n", + " val = int(input(\"Please enter an integer: \"))\n", + " except:\n", + " print(\"Looks like you did not enter an integer!\")\n", + " continue\n", + " else:\n", + " print(\"Yep that's an integer!\")\n", + " break\n", + " finally:\n", + " print(\"Finally, I executed!\")\n", + " print(val)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: five\n", + "Looks like you did not enter an integer!\n", + "Finally, I executed!\n", + "Please enter an integer: four\n", + "Looks like you did not enter an integer!\n", + "Finally, I executed!\n", + "Please enter an integer: 3\n", + "Yep that's an integer!\n", + "Finally, I executed!\n" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So why did our function print \"Finally, I executed!\" after each trial, yet it never printed `val` itself? This is because with a try/except/finally clause, any continue or break statements are reserved until *after* the try clause is completed. This means that even though a successful input of **3** brought us to the else: block, and a break statement was thrown, the try clause continued through to finally: before breaking out of the while loop. And since print(val) was outside the try clause, the break statement prevented it from running.\n", + "\n", + "Let's make one final adjustment:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def askint():\n", + " while True:\n", + " try:\n", + " val = int(input(\"Please enter an integer: \"))\n", + " except:\n", + " print(\"Looks like you did not enter an integer!\")\n", + " continue\n", + " else:\n", + " print(\"Yep that's an integer!\")\n", + " print(val)\n", + " break\n", + " finally:\n", + " print(\"Finally, I executed!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: six\n", + "Looks like you did not enter an integer!\n", + "Finally, I executed!\n", + "Please enter an integer: 6\n", + "Yep that's an integer!\n", + "6\n", + "Finally, I executed!\n" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Great! Now you know how to handle errors and exceptions in Python with the try, except, else, and finally notation!**" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/02-Errors and Exceptions Homework-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/02-Errors and Exceptions Homework-checkpoint.ipynb new file mode 100644 index 0000000..f873f23 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/02-Errors and Exceptions Homework-checkpoint.ipynb @@ -0,0 +1,139 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Errors and Exceptions Homework" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 1\n", + "Handle the exception thrown by the code below by using try and except blocks." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "TypeError", + "evalue": "unsupported operand type(s) for ** or pow(): 'str' and 'int'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[1;32min\u001b[0m \u001b[1;33m[\u001b[0m\u001b[1;34m'a'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'b'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'c'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m**\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for ** or pow(): 'str' and 'int'" + ] + } + ], + "source": [ + "for i in ['a','b','c']:\n", + " print(i**2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 2\n", + "Handle the exception thrown by the code below by using try and except blocks. Then use a finally block to print 'All Done.'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0my\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mz\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m/\u001b[0m\u001b[0my\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "x = 5\n", + "y = 0\n", + "\n", + "z = x/y" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 3\n", + "Write a function that asks for an integer and prints the square of it. Use a while loop with a try, except, else block to account for incorrect inputs." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def ask():\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Input an integer: null\n", + "An error occurred! Please try again!\n", + "Input an integer: 2\n", + "Thank you, your number squared is: 4\n" + ] + } + ], + "source": [ + "ask()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/03-Errors and Exceptions Homework - Solution-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/03-Errors and Exceptions Homework - Solution-checkpoint.ipynb new file mode 100644 index 0000000..b4f9c52 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/03-Errors and Exceptions Homework - Solution-checkpoint.ipynb @@ -0,0 +1,150 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Errors and Exceptions Homework - Solution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 1\n", + "Handle the exception thrown by the code below by using try and except blocks." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "An error occurred!\n" + ] + } + ], + "source": [ + "try:\n", + " for i in ['a','b','c']:\n", + " print(i**2)\n", + "except:\n", + " print(\"An error occurred!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 2\n", + "Handle the exception thrown by the code below by using try and except blocks. Then use a finally block to print 'All Done.'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Can't divide by Zero!\n", + "All Done!\n" + ] + } + ], + "source": [ + "x = 5\n", + "y = 0\n", + "try:\n", + " z = x/y\n", + "except ZeroDivisionError:\n", + " print(\"Can't divide by Zero!\")\n", + "finally:\n", + " print('All Done!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 3\n", + "Write a function that asks for an integer and prints the square of it. Use a while loop with a try, except, else block to account for incorrect inputs." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def ask():\n", + " \n", + " while True:\n", + " try:\n", + " n = int(input('Input an integer: '))\n", + " except:\n", + " print('An error occurred! Please try again!')\n", + " continue\n", + " else:\n", + " break\n", + " \n", + " \n", + " print('Thank you, your number squared is: ',n**2)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Input an integer: null\n", + "An error occurred! Please try again!\n", + "Input an integer: 2\n", + "Thank you, your number squared is: 4\n" + ] + } + ], + "source": [ + "ask()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/04-Unit Testing-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/04-Unit Testing-checkpoint.ipynb new file mode 100644 index 0000000..8445547 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/.ipynb_checkpoints/04-Unit Testing-checkpoint.ipynb @@ -0,0 +1,553 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Unit Testing\n", + "\n", + "Equally important as writing good code is writing good tests. Better to find bugs yourself than have them reported to you by end users!\n", + "\n", + "For this section we'll be working with files outside the notebook. We'll save our code to a .py file, and then save our test script to another .py file. Normally we would code these files using a text editor like Brackets or Atom, or inside an IDE like Spyder or Pycharm. But, since we're here, let's use Jupyter!\n", + "\n", + "Recall that with some IPython magic we can write the contents of a cell to a file using `%%writefile`.
\n", + "Something we haven't seen yet; you can run terminal commands from a jupyter cell using `!`\n", + "\n", + "## Testing tools\n", + "\n", + "There are dozens of good testing libraries out there. Most are third-party packages that require an install, such as:\n", + "\n", + "* [pylint](https://www.pylint.org/)\n", + "* [pyflakes](https://pypi.python.org/pypi/pyflakes/)\n", + "* [pep8](https://pypi.python.org/pypi/pep8)\n", + "\n", + "These are simple tools that merely look at your code, and they'll tell you if there are style issues or simple problems like variable names being called before assignment.\n", + "\n", + "A far better way to test your code is to write tests that send sample data to your program, and compare what's returned to a desired outcome.
Two such tools are available from the standard library:\n", + "\n", + "* [unittest](https://docs.python.org/3/library/unittest.html)\n", + "* [doctest](https://docs.python.org/3/library/doctest.html)\n", + "\n", + "Let's look at pylint first, then we'll do some heavier lifting with unittest.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `pylint`\n", + "\n", + "`pylint` tests for style as well as some very basic program logic." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "First, if you don't have it already (and you probably do, as it's part of the Anaconda distribution), you should install `pylint`.
Once that's done feel free to comment out the cell, you won't need it anymore." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "! pip install pylint" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's save a very simple script:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting simple1.py\n" + ] + } + ], + "source": [ + "%%writefile simple1.py\n", + "a = 1\n", + "b = 2\n", + "print(a)\n", + "print(B)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now let's check it using pylint" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "************* Module simple1\n", + "C: 4, 0: Final newline missing (missing-final-newline)\n", + "C: 1, 0: Missing module docstring (missing-docstring)\n", + "C: 1, 0: Invalid constant name \"a\" (invalid-name)\n", + "C: 2, 0: Invalid constant name \"b\" (invalid-name)\n", + "E: 4, 6: Undefined variable 'B' (undefined-variable)\n", + "\n", + "---------------------------------------------------------------------\n", + "\n", + "Your code has been rated at -12.50/10 (previous run: 8.33/10, -20.83)\n", + "\n", + "\n", + "\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "No config file found, using default configuration\n" + ] + } + ], + "source": [ + "! pylint simple1.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Pylint first lists some styling issues - it would like to see an extra newline at the end, modules and function definitions should have descriptive docstrings, and single characters are a poor choice for variable names.\n", + "\n", + "More importantly, however, pylint identified an error in the program - a variable called before assignment. This needs fixing.\n", + "\n", + "Note that pylint scored our program a negative 12.5 out of 10. Let's try to improve that!" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting simple1.py\n" + ] + } + ], + "source": [ + "%%writefile simple1.py\n", + "\"\"\"\n", + "A very simple script.\n", + "\"\"\"\n", + "\n", + "def myfunc():\n", + " \"\"\"\n", + " An extremely simple function.\n", + " \"\"\"\n", + " first = 1\n", + " second = 2\n", + " print(first)\n", + " print(second)\n", + "\n", + "myfunc()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "************* Module simple1\n", + "C: 14, 0: Final newline missing (missing-final-newline)\n", + "\n", + "---------------------------------------------------------------------\n", + "\n", + "Your code has been rated at 8.33/10 (previous run: -12.50/10, +20.83)\n", + "\n", + "\n", + "\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "No config file found, using default configuration\n" + ] + } + ], + "source": [ + "! pylint simple1.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Much better! Our score climbed to 8.33 out of 10. Unfortunately, the final newline has to do with how jupyter writes to a file, and there's not much we can do about that here. Still, pylint helped us troubleshoot some of our problems. But what if the problem was more complex?" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting simple2.py\n" + ] + } + ], + "source": [ + "%%writefile simple2.py\n", + "\"\"\"\n", + "A very simple script.\n", + "\"\"\"\n", + "\n", + "def myfunc():\n", + " \"\"\"\n", + " An extremely simple function.\n", + " \"\"\"\n", + " first = 1\n", + " second = 2\n", + " print(first)\n", + " print('second')\n", + "\n", + "myfunc()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "************* Module simple2\n", + "C: 14, 0: Final newline missing (missing-final-newline)\n", + "W: 10, 4: Unused variable 'second' (unused-variable)\n", + "\n", + "------------------------------------------------------------------\n", + "\n", + "Your code has been rated at 6.67/10 (previous run: 6.67/10, +0.00)\n", + "\n", + "\n", + "\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "No config file found, using default configuration\n" + ] + } + ], + "source": [ + "! pylint simple2.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "pylint tells us there's an unused variable in line 10, but it doesn't know that we might get an unexpected output from line 12! For this we need a more robust set of tools. That's where `unittest` comes in." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `unittest`\n", + "`unittest` lets you write your own test programs. The goal is to send a specific set of data to your program, and analyze the returned results against an expected result. \n", + "\n", + "Let's generate a simple script that capitalizes words in a given string. We'll call it **cap.py**." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting cap.py\n" + ] + } + ], + "source": [ + "%%writefile cap.py\n", + "def cap_text(text):\n", + " return text.capitalize()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we'll write a test script. We can call it whatever we want, but **test_cap.py** seems an obvious choice.\n", + "\n", + "When writing test functions, it's best to go from simple to complex, as each function will be run in order. Here we'll test simple, one-word strings, followed by a test of multiple word strings." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting test_cap.py\n" + ] + } + ], + "source": [ + "%%writefile test_cap.py\n", + "import unittest\n", + "import cap\n", + "\n", + "class TestCap(unittest.TestCase):\n", + " \n", + " def test_one_word(self):\n", + " text = 'python'\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, 'Python')\n", + " \n", + " def test_multiple_words(self):\n", + " text = 'monty python'\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, 'Monty Python')\n", + " \n", + "if __name__ == '__main__':\n", + " unittest.main()" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "F.\n", + "======================================================================\n", + "FAIL: test_multiple_words (__main__.TestCap)\n", + "----------------------------------------------------------------------\n", + "Traceback (most recent call last):\n", + " File \"test_cap.py\", line 14, in test_multiple_words\n", + " self.assertEqual(result, 'Monty Python')\n", + "AssertionError: 'Monty python' != 'Monty Python'\n", + "- Monty python\n", + "? ^\n", + "+ Monty Python\n", + "? ^\n", + "\n", + "\n", + "----------------------------------------------------------------------\n", + "Ran 2 tests in 0.000s\n", + "\n", + "FAILED (failures=1)\n" + ] + } + ], + "source": [ + "! python test_cap.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What happened? It turns out that the `.capitalize()` method only capitalizes the first letter of the first word in a string. Doing a little research on string methods, we find that `.title()` might give us what we want." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting cap.py\n" + ] + } + ], + "source": [ + "%%writefile cap.py\n", + "def cap_text(text):\n", + " return text.title() # replace .capitalize() with .title()" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "..\n", + "----------------------------------------------------------------------\n", + "Ran 2 tests in 0.000s\n", + "\n", + "OK\n" + ] + } + ], + "source": [ + "! python test_cap.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hey, it passed! But have we tested all cases? Let's add another test to **test_cap.py** to see if it handles words with apostrophes, like *don't*.\n", + "\n", + "In a text editor this would be easy, but in Jupyter we have to start from scratch." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting test_cap.py\n" + ] + } + ], + "source": [ + "%%writefile test_cap.py\n", + "import unittest\n", + "import cap\n", + "\n", + "class TestCap(unittest.TestCase):\n", + " \n", + " def test_one_word(self):\n", + " text = 'python'\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, 'Python')\n", + " \n", + " def test_multiple_words(self):\n", + " text = 'monty python'\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, 'Monty Python')\n", + " \n", + " def test_with_apostrophes(self):\n", + " text = \"monty python's flying circus\"\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, \"Monty Python's Flying Circus\")\n", + " \n", + "if __name__ == '__main__':\n", + " unittest.main()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "..F\n", + "======================================================================\n", + "FAIL: test_with_apostrophes (__main__.TestCap)\n", + "----------------------------------------------------------------------\n", + "Traceback (most recent call last):\n", + " File \"test_cap.py\", line 19, in test_with_apostrophes\n", + " self.assertEqual(result, \"Monty Python's Flying Circus\")\n", + "AssertionError: \"Monty Python'S Flying Circus\" != \"Monty Python's Flying Circus\"\n", + "- Monty Python'S Flying Circus\n", + "? ^\n", + "+ Monty Python's Flying Circus\n", + "? ^\n", + "\n", + "\n", + "----------------------------------------------------------------------\n", + "Ran 3 tests in 0.000s\n", + "\n", + "FAILED (failures=1)\n" + ] + } + ], + "source": [ + "! python test_cap.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we have to find a solution that handles apostrophes! There is one (look up `capwords` from the `string` module) but we'll leave that as an exercise for the reader." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Now you should have a basic understanding of unit testing!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/01-Errors and Exceptions Handling.ipynb b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/01-Errors and Exceptions Handling.ipynb new file mode 100644 index 0000000..c135164 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/01-Errors and Exceptions Handling.ipynb @@ -0,0 +1,463 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Errors and Exception Handling\n", + "\n", + "In this lecture we will learn about Errors and Exception Handling in Python. You've definitely already encountered errors by this point in the course. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "SyntaxError", + "evalue": "EOL while scanning string literal (, line 1)", + "output_type": "error", + "traceback": [ + "\u001b[1;36m File \u001b[1;32m\"\"\u001b[1;36m, line \u001b[1;32m1\u001b[0m\n\u001b[1;33m print('Hello)\u001b[0m\n\u001b[1;37m ^\u001b[0m\n\u001b[1;31mSyntaxError\u001b[0m\u001b[1;31m:\u001b[0m EOL while scanning string literal\n" + ] + } + ], + "source": [ + "print('Hello)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Note how we get a SyntaxError, with the further description that it was an EOL (End of Line Error) while scanning the string literal. This is specific enough for us to see that we forgot a single quote at the end of the line. Understanding these various error types will help you debug your code much faster. \n", + "\n", + "This type of error and description is known as an Exception. Even if a statement or expression is syntactically correct, it may cause an error when an attempt is made to execute it. Errors detected during execution are called exceptions and are not unconditionally fatal.\n", + "\n", + "You can check out the full list of built-in exceptions [here](https://docs.python.org/3/library/exceptions.html). Now let's learn how to handle errors and exceptions in our own code." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## try and except\n", + "\n", + "The basic terminology and syntax used to handle errors in Python are the try and except statements. The code which can cause an exception to occur is put in the try block and the handling of the exception is then implemented in the except block of code. The syntax follows:\n", + "\n", + " try:\n", + " You do your operations here...\n", + " ...\n", + " except ExceptionI:\n", + " If there is ExceptionI, then execute this block.\n", + " except ExceptionII:\n", + " If there is ExceptionII, then execute this block.\n", + " ...\n", + " else:\n", + " If there is no exception then execute this block. \n", + "\n", + "We can also just check for any exception with just using except: To get a better understanding of all this let's check out an example: We will look at some code that opens and writes a file:" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Content written successfully\n" + ] + } + ], + "source": [ + "try:\n", + " f = open('testfile','w')\n", + " f.write('Test write this')\n", + "except IOError:\n", + " # This will only check for an IOError exception and then execute this print statement\n", + " print(\"Error: Could not find file or read data\")\n", + "else:\n", + " print(\"Content written successfully\")\n", + " f.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now let's see what would happen if we did not have write permission (opening only with 'r'):" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error: Could not find file or read data\n" + ] + } + ], + "source": [ + "try:\n", + " f = open('testfile','r')\n", + " f.write('Test write this')\n", + "except IOError:\n", + " # This will only check for an IOError exception and then execute this print statement\n", + " print(\"Error: Could not find file or read data\")\n", + "else:\n", + " print(\"Content written successfully\")\n", + " f.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Notice how we only printed a statement! The code still ran and we were able to continue doing actions and running code blocks. This is extremely useful when you have to account for possible input errors in your code. You can be prepared for the error and keep running code, instead of your code just breaking as we saw above.\n", + "\n", + "We could have also just said except: if we weren't sure what exception would occur. For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Error: Could not find file or read data\n" + ] + } + ], + "source": [ + "try:\n", + " f = open('testfile','r')\n", + " f.write('Test write this')\n", + "except:\n", + " # This will check for any exception and then execute this print statement\n", + " print(\"Error: Could not find file or read data\")\n", + "else:\n", + " print(\"Content written successfully\")\n", + " f.close()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Now we don't actually need to memorize that list of exception types! Now what if we kept wanting to run code after the exception occurred? This is where finally comes in.\n", + "## finally\n", + "The finally: block of code will always be run regardless if there was an exception in the try code block. The syntax is:\n", + "\n", + " try:\n", + " Code block here\n", + " ...\n", + " Due to any exception, this code may be skipped!\n", + " finally:\n", + " This code block would always be executed.\n", + "\n", + "For example:" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Always execute finally code blocks\n" + ] + } + ], + "source": [ + "try:\n", + " f = open(\"testfile\", \"w\")\n", + " f.write(\"Test write statement\")\n", + " f.close()\n", + "finally:\n", + " print(\"Always execute finally code blocks\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We can use this in conjunction with except. Let's see a new example that will take into account a user providing the wrong input:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [], + "source": [ + "def askint():\n", + " try:\n", + " val = int(input(\"Please enter an integer: \"))\n", + " except:\n", + " print(\"Looks like you did not enter an integer!\")\n", + "\n", + " finally:\n", + " print(\"Finally, I executed!\")\n", + " print(val)" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: 5\n", + "Finally, I executed!\n", + "5\n" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: five\n", + "Looks like you did not enter an integer!\n", + "Finally, I executed!\n" + ] + }, + { + "ename": "UnboundLocalError", + "evalue": "local variable 'val' referenced before assignment", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mUnboundLocalError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0maskint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;32m\u001b[0m in \u001b[0;36maskint\u001b[1;34m()\u001b[0m\n\u001b[0;32m 7\u001b[0m \u001b[1;32mfinally\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Finally, I executed!\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 9\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mval\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mUnboundLocalError\u001b[0m: local variable 'val' referenced before assignment" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Notice how we got an error when trying to print val (because it was never properly assigned). Let's remedy this by asking the user and checking to make sure the input type is an integer:" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "def askint():\n", + " try:\n", + " val = int(input(\"Please enter an integer: \"))\n", + " except:\n", + " print(\"Looks like you did not enter an integer!\")\n", + " val = int(input(\"Try again-Please enter an integer: \"))\n", + " finally:\n", + " print(\"Finally, I executed!\")\n", + " print(val)" + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: five\n", + "Looks like you did not enter an integer!\n", + "Try again-Please enter an integer: four\n", + "Finally, I executed!\n" + ] + }, + { + "ename": "ValueError", + "evalue": "invalid literal for int() with base 10: 'four'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36maskint\u001b[1;34m()\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[1;32mtry\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 3\u001b[1;33m \u001b[0mval\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Please enter an integer: \"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 4\u001b[0m \u001b[1;32mexcept\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: 'five'", + "\nDuring handling of the above exception, another exception occurred:\n", + "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0maskint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;32m\u001b[0m in \u001b[0;36maskint\u001b[1;34m()\u001b[0m\n\u001b[0;32m 4\u001b[0m \u001b[1;32mexcept\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 5\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Looks like you did not enter an integer!\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 6\u001b[1;33m \u001b[0mval\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0minput\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Try again-Please enter an integer: \"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 7\u001b[0m \u001b[1;32mfinally\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 8\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Finally, I executed!\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", + "\u001b[1;31mValueError\u001b[0m: invalid literal for int() with base 10: 'four'" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hmmm...that only did one check. How can we continually keep checking? We can use a while loop!" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def askint():\n", + " while True:\n", + " try:\n", + " val = int(input(\"Please enter an integer: \"))\n", + " except:\n", + " print(\"Looks like you did not enter an integer!\")\n", + " continue\n", + " else:\n", + " print(\"Yep that's an integer!\")\n", + " break\n", + " finally:\n", + " print(\"Finally, I executed!\")\n", + " print(val)" + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: five\n", + "Looks like you did not enter an integer!\n", + "Finally, I executed!\n", + "Please enter an integer: four\n", + "Looks like you did not enter an integer!\n", + "Finally, I executed!\n", + "Please enter an integer: 3\n", + "Yep that's an integer!\n", + "Finally, I executed!\n" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "So why did our function print \"Finally, I executed!\" after each trial, yet it never printed `val` itself? This is because with a try/except/finally clause, any continue or break statements are reserved until *after* the try clause is completed. This means that even though a successful input of **3** brought us to the else: block, and a break statement was thrown, the try clause continued through to finally: before breaking out of the while loop. And since print(val) was outside the try clause, the break statement prevented it from running.\n", + "\n", + "Let's make one final adjustment:" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def askint():\n", + " while True:\n", + " try:\n", + " val = int(input(\"Please enter an integer: \"))\n", + " except:\n", + " print(\"Looks like you did not enter an integer!\")\n", + " continue\n", + " else:\n", + " print(\"Yep that's an integer!\")\n", + " print(val)\n", + " break\n", + " finally:\n", + " print(\"Finally, I executed!\")" + ] + }, + { + "cell_type": "code", + "execution_count": 14, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Please enter an integer: six\n", + "Looks like you did not enter an integer!\n", + "Finally, I executed!\n", + "Please enter an integer: 6\n", + "Yep that's an integer!\n", + "6\n", + "Finally, I executed!\n" + ] + } + ], + "source": [ + "askint()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Great! Now you know how to handle errors and exceptions in Python with the try, except, else, and finally notation!**" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/02-Errors and Exceptions Homework.ipynb b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/02-Errors and Exceptions Homework.ipynb new file mode 100644 index 0000000..f873f23 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/02-Errors and Exceptions Homework.ipynb @@ -0,0 +1,139 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Errors and Exceptions Homework" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 1\n", + "Handle the exception thrown by the code below by using try and except blocks." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "ename": "TypeError", + "evalue": "unsupported operand type(s) for ** or pow(): 'str' and 'int'", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mfor\u001b[0m \u001b[0mi\u001b[0m \u001b[1;32min\u001b[0m \u001b[1;33m[\u001b[0m\u001b[1;34m'a'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'b'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;34m'c'\u001b[0m\u001b[1;33m]\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mi\u001b[0m\u001b[1;33m**\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mTypeError\u001b[0m: unsupported operand type(s) for ** or pow(): 'str' and 'int'" + ] + } + ], + "source": [ + "for i in ['a','b','c']:\n", + " print(i**2)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 2\n", + "Handle the exception thrown by the code below by using try and except blocks. Then use a finally block to print 'All Done.'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "ename": "ZeroDivisionError", + "evalue": "division by zero", + "output_type": "error", + "traceback": [ + "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[1;31mZeroDivisionError\u001b[0m Traceback (most recent call last)", + "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m()\u001b[0m\n\u001b[0;32m 2\u001b[0m \u001b[0my\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 3\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 4\u001b[1;33m \u001b[0mz\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mx\u001b[0m\u001b[1;33m/\u001b[0m\u001b[0my\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[1;31mZeroDivisionError\u001b[0m: division by zero" + ] + } + ], + "source": [ + "x = 5\n", + "y = 0\n", + "\n", + "z = x/y" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 3\n", + "Write a function that asks for an integer and prints the square of it. Use a while loop with a try, except, else block to account for incorrect inputs." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def ask():\n", + " pass" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Input an integer: null\n", + "An error occurred! Please try again!\n", + "Input an integer: 2\n", + "Thank you, your number squared is: 4\n" + ] + } + ], + "source": [ + "ask()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/03-Errors and Exceptions Homework - Solution.ipynb b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/03-Errors and Exceptions Homework - Solution.ipynb new file mode 100644 index 0000000..b4f9c52 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/03-Errors and Exceptions Homework - Solution.ipynb @@ -0,0 +1,150 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Errors and Exceptions Homework - Solution" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 1\n", + "Handle the exception thrown by the code below by using try and except blocks." + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "An error occurred!\n" + ] + } + ], + "source": [ + "try:\n", + " for i in ['a','b','c']:\n", + " print(i**2)\n", + "except:\n", + " print(\"An error occurred!\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 2\n", + "Handle the exception thrown by the code below by using try and except blocks. Then use a finally block to print 'All Done.'" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Can't divide by Zero!\n", + "All Done!\n" + ] + } + ], + "source": [ + "x = 5\n", + "y = 0\n", + "try:\n", + " z = x/y\n", + "except ZeroDivisionError:\n", + " print(\"Can't divide by Zero!\")\n", + "finally:\n", + " print('All Done!')" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Problem 3\n", + "Write a function that asks for an integer and prints the square of it. Use a while loop with a try, except, else block to account for incorrect inputs." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "def ask():\n", + " \n", + " while True:\n", + " try:\n", + " n = int(input('Input an integer: '))\n", + " except:\n", + " print('An error occurred! Please try again!')\n", + " continue\n", + " else:\n", + " break\n", + " \n", + " \n", + " print('Thank you, your number squared is: ',n**2)" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Input an integer: null\n", + "An error occurred! Please try again!\n", + "Input an integer: 2\n", + "Thank you, your number squared is: 4\n" + ] + } + ], + "source": [ + "ask()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Great Job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/04-Unit Testing.ipynb b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/04-Unit Testing.ipynb new file mode 100644 index 0000000..8445547 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/04-Unit Testing.ipynb @@ -0,0 +1,553 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Unit Testing\n", + "\n", + "Equally important as writing good code is writing good tests. Better to find bugs yourself than have them reported to you by end users!\n", + "\n", + "For this section we'll be working with files outside the notebook. We'll save our code to a .py file, and then save our test script to another .py file. Normally we would code these files using a text editor like Brackets or Atom, or inside an IDE like Spyder or Pycharm. But, since we're here, let's use Jupyter!\n", + "\n", + "Recall that with some IPython magic we can write the contents of a cell to a file using `%%writefile`.
\n", + "Something we haven't seen yet; you can run terminal commands from a jupyter cell using `!`\n", + "\n", + "## Testing tools\n", + "\n", + "There are dozens of good testing libraries out there. Most are third-party packages that require an install, such as:\n", + "\n", + "* [pylint](https://www.pylint.org/)\n", + "* [pyflakes](https://pypi.python.org/pypi/pyflakes/)\n", + "* [pep8](https://pypi.python.org/pypi/pep8)\n", + "\n", + "These are simple tools that merely look at your code, and they'll tell you if there are style issues or simple problems like variable names being called before assignment.\n", + "\n", + "A far better way to test your code is to write tests that send sample data to your program, and compare what's returned to a desired outcome.
Two such tools are available from the standard library:\n", + "\n", + "* [unittest](https://docs.python.org/3/library/unittest.html)\n", + "* [doctest](https://docs.python.org/3/library/doctest.html)\n", + "\n", + "Let's look at pylint first, then we'll do some heavier lifting with unittest.\n" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `pylint`\n", + "\n", + "`pylint` tests for style as well as some very basic program logic." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "First, if you don't have it already (and you probably do, as it's part of the Anaconda distribution), you should install `pylint`.
Once that's done feel free to comment out the cell, you won't need it anymore." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "! pip install pylint" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's save a very simple script:" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting simple1.py\n" + ] + } + ], + "source": [ + "%%writefile simple1.py\n", + "a = 1\n", + "b = 2\n", + "print(a)\n", + "print(B)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now let's check it using pylint" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "************* Module simple1\n", + "C: 4, 0: Final newline missing (missing-final-newline)\n", + "C: 1, 0: Missing module docstring (missing-docstring)\n", + "C: 1, 0: Invalid constant name \"a\" (invalid-name)\n", + "C: 2, 0: Invalid constant name \"b\" (invalid-name)\n", + "E: 4, 6: Undefined variable 'B' (undefined-variable)\n", + "\n", + "---------------------------------------------------------------------\n", + "\n", + "Your code has been rated at -12.50/10 (previous run: 8.33/10, -20.83)\n", + "\n", + "\n", + "\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "No config file found, using default configuration\n" + ] + } + ], + "source": [ + "! pylint simple1.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Pylint first lists some styling issues - it would like to see an extra newline at the end, modules and function definitions should have descriptive docstrings, and single characters are a poor choice for variable names.\n", + "\n", + "More importantly, however, pylint identified an error in the program - a variable called before assignment. This needs fixing.\n", + "\n", + "Note that pylint scored our program a negative 12.5 out of 10. Let's try to improve that!" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting simple1.py\n" + ] + } + ], + "source": [ + "%%writefile simple1.py\n", + "\"\"\"\n", + "A very simple script.\n", + "\"\"\"\n", + "\n", + "def myfunc():\n", + " \"\"\"\n", + " An extremely simple function.\n", + " \"\"\"\n", + " first = 1\n", + " second = 2\n", + " print(first)\n", + " print(second)\n", + "\n", + "myfunc()" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "************* Module simple1\n", + "C: 14, 0: Final newline missing (missing-final-newline)\n", + "\n", + "---------------------------------------------------------------------\n", + "\n", + "Your code has been rated at 8.33/10 (previous run: -12.50/10, +20.83)\n", + "\n", + "\n", + "\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "No config file found, using default configuration\n" + ] + } + ], + "source": [ + "! pylint simple1.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Much better! Our score climbed to 8.33 out of 10. Unfortunately, the final newline has to do with how jupyter writes to a file, and there's not much we can do about that here. Still, pylint helped us troubleshoot some of our problems. But what if the problem was more complex?" + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting simple2.py\n" + ] + } + ], + "source": [ + "%%writefile simple2.py\n", + "\"\"\"\n", + "A very simple script.\n", + "\"\"\"\n", + "\n", + "def myfunc():\n", + " \"\"\"\n", + " An extremely simple function.\n", + " \"\"\"\n", + " first = 1\n", + " second = 2\n", + " print(first)\n", + " print('second')\n", + "\n", + "myfunc()" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "************* Module simple2\n", + "C: 14, 0: Final newline missing (missing-final-newline)\n", + "W: 10, 4: Unused variable 'second' (unused-variable)\n", + "\n", + "------------------------------------------------------------------\n", + "\n", + "Your code has been rated at 6.67/10 (previous run: 6.67/10, +0.00)\n", + "\n", + "\n", + "\n" + ] + }, + { + "name": "stderr", + "output_type": "stream", + "text": [ + "No config file found, using default configuration\n" + ] + } + ], + "source": [ + "! pylint simple2.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "pylint tells us there's an unused variable in line 10, but it doesn't know that we might get an unexpected output from line 12! For this we need a more robust set of tools. That's where `unittest` comes in." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## `unittest`\n", + "`unittest` lets you write your own test programs. The goal is to send a specific set of data to your program, and analyze the returned results against an expected result. \n", + "\n", + "Let's generate a simple script that capitalizes words in a given string. We'll call it **cap.py**." + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting cap.py\n" + ] + } + ], + "source": [ + "%%writefile cap.py\n", + "def cap_text(text):\n", + " return text.capitalize()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we'll write a test script. We can call it whatever we want, but **test_cap.py** seems an obvious choice.\n", + "\n", + "When writing test functions, it's best to go from simple to complex, as each function will be run in order. Here we'll test simple, one-word strings, followed by a test of multiple word strings." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting test_cap.py\n" + ] + } + ], + "source": [ + "%%writefile test_cap.py\n", + "import unittest\n", + "import cap\n", + "\n", + "class TestCap(unittest.TestCase):\n", + " \n", + " def test_one_word(self):\n", + " text = 'python'\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, 'Python')\n", + " \n", + " def test_multiple_words(self):\n", + " text = 'monty python'\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, 'Monty Python')\n", + " \n", + "if __name__ == '__main__':\n", + " unittest.main()" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "F.\n", + "======================================================================\n", + "FAIL: test_multiple_words (__main__.TestCap)\n", + "----------------------------------------------------------------------\n", + "Traceback (most recent call last):\n", + " File \"test_cap.py\", line 14, in test_multiple_words\n", + " self.assertEqual(result, 'Monty Python')\n", + "AssertionError: 'Monty python' != 'Monty Python'\n", + "- Monty python\n", + "? ^\n", + "+ Monty Python\n", + "? ^\n", + "\n", + "\n", + "----------------------------------------------------------------------\n", + "Ran 2 tests in 0.000s\n", + "\n", + "FAILED (failures=1)\n" + ] + } + ], + "source": [ + "! python test_cap.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "What happened? It turns out that the `.capitalize()` method only capitalizes the first letter of the first word in a string. Doing a little research on string methods, we find that `.title()` might give us what we want." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting cap.py\n" + ] + } + ], + "source": [ + "%%writefile cap.py\n", + "def cap_text(text):\n", + " return text.title() # replace .capitalize() with .title()" + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "..\n", + "----------------------------------------------------------------------\n", + "Ran 2 tests in 0.000s\n", + "\n", + "OK\n" + ] + } + ], + "source": [ + "! python test_cap.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Hey, it passed! But have we tested all cases? Let's add another test to **test_cap.py** to see if it handles words with apostrophes, like *don't*.\n", + "\n", + "In a text editor this would be easy, but in Jupyter we have to start from scratch." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Overwriting test_cap.py\n" + ] + } + ], + "source": [ + "%%writefile test_cap.py\n", + "import unittest\n", + "import cap\n", + "\n", + "class TestCap(unittest.TestCase):\n", + " \n", + " def test_one_word(self):\n", + " text = 'python'\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, 'Python')\n", + " \n", + " def test_multiple_words(self):\n", + " text = 'monty python'\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, 'Monty Python')\n", + " \n", + " def test_with_apostrophes(self):\n", + " text = \"monty python's flying circus\"\n", + " result = cap.cap_text(text)\n", + " self.assertEqual(result, \"Monty Python's Flying Circus\")\n", + " \n", + "if __name__ == '__main__':\n", + " unittest.main()" + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [ + { + "name": "stderr", + "output_type": "stream", + "text": [ + "..F\n", + "======================================================================\n", + "FAIL: test_with_apostrophes (__main__.TestCap)\n", + "----------------------------------------------------------------------\n", + "Traceback (most recent call last):\n", + " File \"test_cap.py\", line 19, in test_with_apostrophes\n", + " self.assertEqual(result, \"Monty Python's Flying Circus\")\n", + "AssertionError: \"Monty Python'S Flying Circus\" != \"Monty Python's Flying Circus\"\n", + "- Monty Python'S Flying Circus\n", + "? ^\n", + "+ Monty Python's Flying Circus\n", + "? ^\n", + "\n", + "\n", + "----------------------------------------------------------------------\n", + "Ran 3 tests in 0.000s\n", + "\n", + "FAILED (failures=1)\n" + ] + } + ], + "source": [ + "! python test_cap.py" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Now we have to find a solution that handles apostrophes! There is one (look up `capwords` from the `string` module) but we'll leave that as an exercise for the reader." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Now you should have a basic understanding of unit testing!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 2 +} diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/__pycache__/cap.cpython-36.pyc b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/__pycache__/cap.cpython-36.pyc new file mode 100644 index 0000000..5dc144f Binary files /dev/null and b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/__pycache__/cap.cpython-36.pyc differ diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/cap.py b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/cap.py new file mode 100644 index 0000000..6f0a9db --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/cap.py @@ -0,0 +1,2 @@ +def cap_text(text): + return text.title() # replace .capitalize() with .title() \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/simple1.py b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/simple1.py new file mode 100644 index 0000000..ccc2100 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/simple1.py @@ -0,0 +1,14 @@ +""" +A very simple script. +""" + +def myfunc(): + """ + An extremely simple function. + """ + first = 1 + second = 2 + print(first) + print(second) + +myfunc() \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/simple2.py b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/simple2.py new file mode 100644 index 0000000..269ac81 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/simple2.py @@ -0,0 +1,14 @@ +""" +A very simple script. +""" + +def myfunc(): + """ + An extremely simple function. + """ + first = 1 + second = 2 + print(first) + print('second') + +myfunc() \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/test_cap.py b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/test_cap.py new file mode 100644 index 0000000..467aaab --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/test_cap.py @@ -0,0 +1,22 @@ +import unittest +import cap + +class TestCap(unittest.TestCase): + + def test_one_word(self): + text = 'python' + result = cap.cap_text(text) + self.assertEqual(result, 'Python') + + def test_multiple_words(self): + text = 'monty python' + result = cap.cap_text(text) + self.assertEqual(result, 'Monty Python') + + def test_with_apostrophes(self): + text = "monty python's flying circus" + result = cap.cap_text(text) + self.assertEqual(result, "Monty Python's Flying Circus") + +if __name__ == '__main__': + unittest.main() \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/testfile b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/testfile new file mode 100644 index 0000000..b599dc9 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/07-Errors and Exception Handling/testfile @@ -0,0 +1 @@ +Test write statement \ No newline at end of file diff --git a/Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/.ipynb_checkpoints/01-Milestone Project 2 - Assignment-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/.ipynb_checkpoints/01-Milestone Project 2 - Assignment-checkpoint.ipynb new file mode 100644 index 0000000..53b7486 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/.ipynb_checkpoints/01-Milestone Project 2 - Assignment-checkpoint.ipynb @@ -0,0 +1,51 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "# Milestone Project 2 - Blackjack Game\n", + "In this milestone project you will be creating a Complete BlackJack Card Game in Python.\n", + "\n", + "Here are the requirements:\n", + "\n", + "* You need to create a simple text-based [BlackJack](https://en.wikipedia.org/wiki/Blackjack) game\n", + "* The game needs to have one player versus an automated dealer.\n", + "* The player can stand or hit.\n", + "* The player must be able to pick their betting amount.\n", + "* You need to keep track of the player's total money.\n", + "* You need to alert the player of wins, losses, or busts, etc...\n", + "\n", + "And most importantly:\n", + "\n", + "* **You must use OOP and classes in some portion of your game. You can not just use functions in your game. Use classes to help you define the Deck and the Player's hand. There are many right ways to do this, so explore it well!**\n", + "\n", + "\n", + "Feel free to expand this game. Try including multiple players. Try adding in Double-Down and card splits! Remember to you are free to use any resources you want and as always:\n", + "\n", + "# HAVE FUN!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/.ipynb_checkpoints/02-Milestone Project 2 - Walkthrough Steps Workbook-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/.ipynb_checkpoints/02-Milestone Project 2 - Walkthrough Steps Workbook-checkpoint.ipynb new file mode 100644 index 0000000..12a43cf --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/.ipynb_checkpoints/02-Milestone Project 2 - Walkthrough Steps Workbook-checkpoint.ipynb @@ -0,0 +1,425 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Milestone Project 2 - Walkthrough Steps Workbook\n", + "Below is a set of steps for you to follow to try to create the Blackjack Milestone Project game!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Game Play\n", + "To play a hand of Blackjack the following steps must be followed:\n", + "1. Create a deck of 52 cards\n", + "2. Shuffle the deck\n", + "3. Ask the Player for their bet\n", + "4. Make sure that the Player's bet does not exceed their available chips\n", + "5. Deal two cards to the Dealer and two cards to the Player\n", + "6. Show only one of the Dealer's cards, the other remains hidden\n", + "7. Show both of the Player's cards\n", + "8. Ask the Player if they wish to Hit, and take another card\n", + "9. If the Player's hand doesn't Bust (go over 21), ask if they'd like to Hit again.\n", + "10. If a Player Stands, play the Dealer's hand. The dealer will always Hit until the Dealer's value meets or exceeds 17\n", + "11. Determine the winner and adjust the Player's chips accordingly\n", + "12. Ask the Player if they'd like to play again" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Playing Cards\n", + "A standard deck of playing cards has four suits (Hearts, Diamonds, Spades and Clubs) and thirteen ranks (2 through 10, then the face cards Jack, Queen, King and Ace) for a total of 52 cards per deck. Jacks, Queens and Kings all have a rank of 10. Aces have a rank of either 11 or 1 as needed to reach 21 without busting. As a starting point in your program, you may want to assign variables to store a list of suits, ranks, and then use a dictionary to map ranks to values." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The Game\n", + "### Imports and Global Variables\n", + "** Step 1: Import the random module. This will be used to shuffle the deck prior to dealing. Then, declare variables to store suits, ranks and values. You can develop your own system, or copy ours below. Finally, declare a Boolean value to be used to control while loops. This is a common practice used to control the flow of the game.**\n", + "\n", + " suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\n", + " ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\n", + " values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,\n", + " 'Queen':10, 'King':10, 'Ace':11}" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "suits = pass\n", + "ranks = pass\n", + "values = pass\n", + "\n", + "playing = True" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Class Definitions\n", + "Consider making a Card class where each Card object has a suit and a rank, then a Deck class to hold all 52 Card objects, and can be shuffled, and finally a Hand class that holds those Cards that have been dealt to each player from the Deck." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 2: Create a Card Class**
\n", + "A Card object really only needs two attributes: suit and rank. You might add an attribute for \"value\" - we chose to handle value later when developing our Hand class.
In addition to the Card's \\_\\_init\\_\\_ method, consider adding a \\_\\_str\\_\\_ method that, when asked to print a Card, returns a string in the form \"Two of Hearts\"" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class Card:\n", + " \n", + " def __init__(self):\n", + " pass\n", + " \n", + " def __str__(self):\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 3: Create a Deck Class**
\n", + "Here we might store 52 card objects in a list that can later be shuffled. First, though, we need to *instantiate* all 52 unique card objects and add them to our list. So long as the Card class definition appears in our code, we can build Card objects inside our Deck \\_\\_init\\_\\_ method. Consider iterating over sequences of suits and ranks to build out each card. This might appear inside a Deck class \\_\\_init\\_\\_ method:\n", + "\n", + " for suit in suits:\n", + " for rank in ranks:\n", + "\n", + "In addition to an \\_\\_init\\_\\_ method we'll want to add methods to shuffle our deck, and to deal out cards during gameplay.

\n", + "OPTIONAL: We may never need to print the contents of the deck during gameplay, but having the ability to see the cards inside it may help troubleshoot any problems that occur during development. With this in mind, consider adding a \\_\\_str\\_\\_ method to the class definition." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class Deck:\n", + " \n", + " def __init__(self):\n", + " self.deck = [] # start with an empty list\n", + " for suit in suits:\n", + " for rank in ranks:\n", + " pass\n", + " \n", + " def __str__(self):\n", + " pass\n", + "\n", + " def shuffle(self):\n", + " random.shuffle(self.deck)\n", + " \n", + " def deal(self):\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "TESTING: Just to see that everything works so far, let's see what our Deck looks like!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "test_deck = Deck()\n", + "print(test_deck)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Now let's move on to our Hand class." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 4: Create a Hand Class**
\n", + "In addition to holding Card objects dealt from the Deck, the Hand class may be used to calculate the value of those cards using the values dictionary defined above. It may also need to adjust for the value of Aces when appropriate." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class Hand:\n", + " def __init__(self):\n", + " self.cards = [] # start with an empty list as we did in the Deck class\n", + " self.value = 0 # start with zero value\n", + " self.aces = 0 # add an attribute to keep track of aces\n", + " \n", + " def add_card(self,card):\n", + " pass\n", + " \n", + " def adjust_for_ace(self):\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 5: Create a Chips Class**
\n", + "In addition to decks of cards and hands, we need to keep track of a Player's starting chips, bets, and ongoing winnings. This could be done using global variables, but in the spirit of object oriented programming, let's make a Chips class instead!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "class Chips:\n", + " \n", + " def __init__(self):\n", + " self.total = 100 # This can be set to a default value or supplied by a user input\n", + " self.bet = 0\n", + " \n", + " def win_bet(self):\n", + " pass\n", + " \n", + " def lose_bet(self):\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Function Defintions\n", + "A lot of steps are going to be repetitive. That's where functions come in! The following steps are guidelines - add or remove functions as needed in your own program." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 6: Write a function for taking bets**
\n", + "Since we're asking the user for an integer value, this would be a good place to use try/except. Remember to check that a Player's bet can be covered by their available chips." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def take_bet():\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 7: Write a function for taking hits**
\n", + "Either player can take hits until they bust. This function will be called during gameplay anytime a Player requests a hit, or a Dealer's hand is less than 17. It should take in Deck and Hand objects as arguments, and deal one card off the deck and add it to the Hand. You may want it to check for aces in the event that a player's hand exceeds 21." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def hit(deck,hand):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 8: Write a function prompting the Player to Hit or Stand**
\n", + "This function should accept the deck and the player's hand as arguments, and assign playing as a global variable.
\n", + "If the Player Hits, employ the hit() function above. If the Player Stands, set the playing variable to False - this will control the behavior of a while loop later on in our code." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def hit_or_stand(deck,hand):\n", + " global playing # to control an upcoming while loop\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 9: Write functions to display cards**
\n", + "When the game starts, and after each time Player takes a card, the dealer's first card is hidden and all of Player's cards are visible. At the end of the hand all cards are shown, and you may want to show each hand's total value. Write a function for each of these scenarios." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def show_some(player,dealer):\n", + " \n", + " pass\n", + " \n", + "def show_all(player,dealer):\n", + " \n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 10: Write functions to handle end of game scenarios**
\n", + "Remember to pass player's hand, dealer's hand and chips as needed." + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "def player_busts():\n", + " pass\n", + "\n", + "def player_wins():\n", + " pass\n", + "\n", + "def dealer_busts():\n", + " pass\n", + " \n", + "def dealer_wins():\n", + " pass\n", + " \n", + "def push():\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### And now on to the game!!" + ] + }, + { + "cell_type": "code", + "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "while True:\n", + " # Print an opening statement\n", + "\n", + " \n", + " # Create & shuffle the deck, deal two cards to each player\n", + "\n", + " \n", + " \n", + " # Set up the Player's chips\n", + " \n", + " \n", + " # Prompt the Player for their bet\n", + "\n", + " \n", + " # Show cards (but keep one dealer card hidden)\n", + "\n", + " \n", + " while playing: # recall this variable from our hit_or_stand function\n", + " \n", + " # Prompt for Player to Hit or Stand\n", + " \n", + " \n", + " # Show cards (but keep one dealer card hidden)\n", + " \n", + " \n", + " # If player's hand exceeds 21, run player_busts() and break out of loop\n", + " \n", + "\n", + " break\n", + "\n", + " # If Player hasn't busted, play Dealer's hand until Dealer reaches 17\n", + " \n", + " \n", + " # Show all cards\n", + " \n", + " # Run different winning scenarios\n", + " \n", + " \n", + " # Inform Player of their chips total \n", + " \n", + " # Ask to play again\n", + "\n", + " break" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "And that's it! Remember, these steps may differ significantly from your own solution. That's OK! Keep working on different sections of your program until you get the desired results. It takes a lot of time and patience! As always, feel free to post questions and comments to the QA Forums.\n", + "# Good job!" + ] + } + ], + "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.2" + } + }, + "nbformat": 4, + "nbformat_minor": 1 +} diff --git a/Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/.ipynb_checkpoints/03-Milestone Project 2 - Complete Walkthrough Solution-checkpoint.ipynb b/Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/.ipynb_checkpoints/03-Milestone Project 2 - Complete Walkthrough Solution-checkpoint.ipynb new file mode 100644 index 0000000..24cb151 --- /dev/null +++ b/Complete-Python-3-Bootcamp-master/08-Milestone Project - 2/.ipynb_checkpoints/03-Milestone Project 2 - Complete Walkthrough Solution-checkpoint.ipynb @@ -0,0 +1,807 @@ +{ + "cells": [ + { + "cell_type": "markdown", + "metadata": { + "collapsed": true + }, + "source": [ + "# Milestone Project 2 - Complete Walkthrough Solution\n", + "This notebook walks through a proposed solution to the Blackjack Game milestone project. The approach to solving and the specific code used are only suggestions - there are many different ways to code this out, and yours is likely to be different!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Game Play\n", + "To play a hand of Blackjack the following steps must be followed:\n", + "1. Create a deck of 52 cards\n", + "2. Shuffle the deck\n", + "3. Ask the Player for their bet\n", + "4. Make sure that the Player's bet does not exceed their available chips\n", + "5. Deal two cards to the Dealer and two cards to the Player\n", + "6. Show only one of the Dealer's cards, the other remains hidden\n", + "7. Show both of the Player's cards\n", + "8. Ask the Player if they wish to Hit, and take another card\n", + "9. If the Player's hand doesn't Bust (go over 21), ask if they'd like to Hit again.\n", + "10. If a Player Stands, play the Dealer's hand. The dealer will always Hit until the Dealer's value meets or exceeds 17\n", + "11. Determine the winner and adjust the Player's chips accordingly\n", + "12. Ask the Player if they'd like to play again" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## Playing Cards\n", + "A standard deck of playing cards has four suits (Hearts, Diamonds, Spades and Clubs) and thirteen ranks (2 through 10, then the face cards Jack, Queen, King and Ace) for a total of 52 cards per deck. Jacks, Queens and Kings all have a rank of 10. Aces have a rank of either 11 or 1 as needed to reach 21 without busting. As a starting point in your program, you may want to assign variables to store a list of suits, ranks, and then use a dictionary to map ranks to values." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "## The Game\n", + "### Imports and Global Variables\n", + "** Step 1: Import the random module. This will be used to shuffle the deck prior to dealing. Then, declare variables to store suits, ranks and values. You can develop your own system, or copy ours below. Finally, declare a Boolean value to be used to control while loops. This is a common practice used to control the flow of the game.**\n", + "\n", + " suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\n", + " ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\n", + " values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,\n", + " 'Queen':10, 'King':10, 'Ace':11}" + ] + }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [], + "source": [ + "import random\n", + "\n", + "suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs')\n", + "ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace')\n", + "values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10,\n", + " 'Queen':10, 'King':10, 'Ace':11}\n", + "\n", + "playing = True" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Class Definitions\n", + "Consider making a Card class where each Card object has a suit and a rank, then a Deck class to hold all 52 Card objects, and can be shuffled, and finally a Hand class that holds those Cards that have been dealt to each player from the Deck." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 2: Create a Card Class**
\n", + "A Card object really only needs two attributes: suit and rank. You might add an attribute for \"value\" - we chose to handle value later when developing our Hand class.
In addition to the Card's \\_\\_init\\_\\_ method, consider adding a \\_\\_str\\_\\_ method that, when asked to print a Card, returns a string in the form \"Two of Hearts\"" + ] + }, + { + "cell_type": "code", + "execution_count": 2, + "metadata": {}, + "outputs": [], + "source": [ + "class Card:\n", + "\n", + " def __init__(self,suit,rank):\n", + " self.suit = suit\n", + " self.rank = rank\n", + " \n", + " def __str__(self):\n", + " return self.rank + ' of ' + self.suit" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 3: Create a Deck Class**
\n", + "Here we might store 52 card objects in a list that can later be shuffled. First, though, we need to *instantiate* all 52 unique card objects and add them to our list. So long as the Card class definition appears in our code, we can build Card objects inside our Deck \\_\\_init\\_\\_ method. Consider iterating over sequences of suits and ranks to build out each card. This might appear inside a Deck class \\_\\_init\\_\\_ method:\n", + "\n", + " for suit in suits:\n", + " for rank in ranks:\n", + "\n", + "In addition to an \\_\\_init\\_\\_ method we'll want to add methods to shuffle our deck, and to deal out cards during gameplay.

\n", + "OPTIONAL: We may never need to print the contents of the deck during gameplay, but having the ability to see the cards inside it may help troubleshoot any problems that occur during development. With this in mind, consider adding a \\_\\_str\\_\\_ method to the class definition." + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [], + "source": [ + "class Deck:\n", + " \n", + " def __init__(self):\n", + " self.deck = [] # start with an empty list\n", + " for suit in suits:\n", + " for rank in ranks:\n", + " self.deck.append(Card(suit,rank)) # build Card objects and add them to the list\n", + " \n", + " def __str__(self):\n", + " deck_comp = '' # start with an empty string\n", + " for card in self.deck:\n", + " deck_comp += '\\n '+card.__str__() # add each Card object's print string\n", + " return 'The deck has:' + deck_comp\n", + "\n", + " def shuffle(self):\n", + " random.shuffle(self.deck)\n", + " \n", + " def deal(self):\n", + " single_card = self.deck.pop()\n", + " return single_card" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "TESTING: Just to see that everything works so far, let's see what our Deck looks like!" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "The deck has:\n", + " Two of Hearts\n", + " Three of Hearts\n", + " Four of Hearts\n", + " Five of Hearts\n", + " Six of Hearts\n", + " Seven of Hearts\n", + " Eight of Hearts\n", + " Nine of Hearts\n", + " Ten of Hearts\n", + " Jack of Hearts\n", + " Queen of Hearts\n", + " King of Hearts\n", + " Ace of Hearts\n", + " Two of Diamonds\n", + " Three of Diamonds\n", + " Four of Diamonds\n", + " Five of Diamonds\n", + " Six of Diamonds\n", + " Seven of Diamonds\n", + " Eight of Diamonds\n", + " Nine of Diamonds\n", + " Ten of Diamonds\n", + " Jack of Diamonds\n", + " Queen of Diamonds\n", + " King of Diamonds\n", + " Ace of Diamonds\n", + " Two of Spades\n", + " Three of Spades\n", + " Four of Spades\n", + " Five of Spades\n", + " Six of Spades\n", + " Seven of Spades\n", + " Eight of Spades\n", + " Nine of Spades\n", + " Ten of Spades\n", + " Jack of Spades\n", + " Queen of Spades\n", + " King of Spades\n", + " Ace of Spades\n", + " Two of Clubs\n", + " Three of Clubs\n", + " Four of Clubs\n", + " Five of Clubs\n", + " Six of Clubs\n", + " Seven of Clubs\n", + " Eight of Clubs\n", + " Nine of Clubs\n", + " Ten of Clubs\n", + " Jack of Clubs\n", + " Queen of Clubs\n", + " King of Clubs\n", + " Ace of Clubs\n" + ] + } + ], + "source": [ + "test_deck = Deck()\n", + "print(test_deck)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Now let's move on to our Hand class." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 4: Create a Hand Class**
\n", + "In addition to holding Card objects dealt from the Deck, the Hand class may be used to calculate the value of those cards using the values dictionary defined above. It may also need to adjust for the value of Aces when appropriate." + ] + }, + { + "cell_type": "code", + "execution_count": 5, + "metadata": {}, + "outputs": [], + "source": [ + "class Hand:\n", + " def __init__(self):\n", + " self.cards = [] # start with an empty list as we did in the Deck class\n", + " self.value = 0 # start with zero value\n", + " self.aces = 0 # add an attribute to keep track of aces\n", + " \n", + " def add_card(self,card):\n", + " self.cards.append(card)\n", + " self.value += values[card.rank]\n", + " \n", + " def adjust_for_ace(self):\n", + " pass" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "TESTING: Before we tackle the issue of changing Aces, let's make sure we can add two cards to a player's hand and obtain their value:" + ] + }, + { + "cell_type": "code", + "execution_count": 6, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "14" + ] + }, + "execution_count": 6, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "test_deck = Deck()\n", + "test_deck.shuffle()\n", + "test_player = Hand()\n", + "test_player.add_card(test_deck.deal())\n", + "test_player.add_card(test_deck.deal())\n", + "test_player.value" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Let's see what these two cards are:" + ] + }, + { + "cell_type": "code", + "execution_count": 7, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Nine of Hearts\n", + "Five of Hearts\n" + ] + } + ], + "source": [ + "for card in test_player.cards:\n", + " print(card)" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "Great! Now let's tackle the Aces issue. If a hand's value exceeds 21 but it contains an Ace, we can reduce the Ace's value from 11 to 1 and continue playing." + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [], + "source": [ + "class Hand:\n", + " \n", + " def __init__(self):\n", + " self.cards = [] # start with an empty list as we did in the Deck class\n", + " self.value = 0 # start with zero value\n", + " self.aces = 0 # add an attribute to keep track of aces\n", + " \n", + " def add_card(self,card):\n", + " self.cards.append(card)\n", + " self.value += values[card.rank]\n", + " if card.rank == 'Ace':\n", + " self.aces += 1 # add to self.aces\n", + " \n", + " def adjust_for_ace(self):\n", + " while self.value > 21 and self.aces:\n", + " self.value -= 10\n", + " self.aces -= 1 " + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We added code to the add_card method to bump self.aces whenever an ace is brought into the hand, and added code to the adjust_for_aces method that decreases the number of aces any time we make an adjustment to stay under 21." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 5: Create a Chips Class**
\n", + "In addition to decks of cards and hands, we need to keep track of a Player's starting chips, bets, and ongoing winnings. This could be done using global variables, but in the spirit of object oriented programming, let's make a Chips class instead!" + ] + }, + { + "cell_type": "code", + "execution_count": 9, + "metadata": {}, + "outputs": [], + "source": [ + "class Chips:\n", + " \n", + " def __init__(self):\n", + " self.total = 100 # This can be set to a default value or supplied by a user input\n", + " self.bet = 0\n", + " \n", + " def win_bet(self):\n", + " self.total += self.bet\n", + " \n", + " def lose_bet(self):\n", + " self.total -= self.bet" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A NOTE ABOUT OUR DEFAULT TOTAL VALUE:
\n", + "Alternatively, we could have passed a default total value as an parameter in the \\_\\_init\\_\\_. This would have let us pass in an override value at the time the object was created rather than wait until later to change it. The code would have looked like this:\n", + "\n", + " def __init__(self,total=100):\n", + " self.total = total\n", + " self.bet = 0\n", + "\n", + "Either technique is fine, it only depends on how you plan to start your game parameters." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Function Defintions\n", + "A lot of steps are going to be repetitive. That's where functions come in! The following steps are guidelines - add or remove functions as needed in your own program." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 6: Write a function for taking bets**
\n", + "Since we're asking the user for an integer value, this would be a good place to use try/except. Remember to check that a Player's bet can be covered by their available chips." + ] + }, + { + "cell_type": "code", + "execution_count": 10, + "metadata": {}, + "outputs": [], + "source": [ + "def take_bet(chips):\n", + " \n", + " while True:\n", + " try:\n", + " chips.bet = int(input('How many chips would you like to bet? '))\n", + " except ValueError:\n", + " print('Sorry, a bet must be an integer!')\n", + " else:\n", + " if chips.bet > chips.total:\n", + " print(\"Sorry, your bet can't exceed\",chips.total)\n", + " else:\n", + " break" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "We used a while loop here to continually prompt the user for input until we received an integer value that was within the Player's betting limit." + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "A QUICK NOTE ABOUT FUNCTIONS:
\n", + "If we knew in advance what we were going to call our Player's Chips object, we could have written the above function like this:\n", + "\n", + " def take_bet():\n", + " while True:\n", + " try:\n", + " player_chips.bet = int(input('How many chips would you like to bet? '))\n", + " except ValueError:\n", + " print('Sorry, a bet must be an integer!')\n", + " else:\n", + " if player_chips.bet > player_chips.total:\n", + " print(\"Sorry, your bet can't exceed\",player_chips.total)\n", + " else:\n", + " break\n", + "\n", + "and then we could call the function without passing any arguments. This is generally not a good idea! It's better to have functions be self-contained, able to accept any incoming value than depend on some future naming convention. Also, this makes it easier to add players in future versions of our program!" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 7: Write a function for taking hits**
\n", + "Either player can take hits until they bust. This function will be called during gameplay anytime a Player requests a hit, or a Dealer's hand is less than 17. It should take in Deck and Hand objects as arguments, and deal one card off the deck and add it to the Hand. You may want it to check for aces in the event that a player's hand exceeds 21." + ] + }, + { + "cell_type": "code", + "execution_count": 11, + "metadata": {}, + "outputs": [], + "source": [ + "def hit(deck,hand):\n", + " \n", + " hand.add_card(deck.deal())\n", + " hand.adjust_for_ace()" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 8: Write a function prompting the Player to Hit or Stand**
\n", + "This function should accept the deck and the player's hand as arguments, and assign playing as a global variable.
\n", + "If the Player Hits, employ the hit() function above. If the Player Stands, set the playing variable to False - this will control the behavior of a while loop later on in our code." + ] + }, + { + "cell_type": "code", + "execution_count": 12, + "metadata": {}, + "outputs": [], + "source": [ + "def hit_or_stand(deck,hand):\n", + " global playing # to control an upcoming while loop\n", + " \n", + " while True:\n", + " x = input(\"Would you like to Hit or Stand? Enter 'h' or 's' \")\n", + " \n", + " if x[0].lower() == 'h':\n", + " hit(deck,hand) # hit() function defined above\n", + "\n", + " elif x[0].lower() == 's':\n", + " print(\"Player stands. Dealer is playing.\")\n", + " playing = False\n", + "\n", + " else:\n", + " print(\"Sorry, please try again.\")\n", + " continue\n", + " break" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "**Step 9: Write functions to display cards**
\n", + "When the game starts, and after each time Player takes a card, the dealer's first card is hidden and all of Player's cards are visible. At the end of the hand all cards are shown, and you may want to show each hand's total value. Write a function for each of these scenarios." + ] + }, + { + "cell_type": "code", + "execution_count": 13, + "metadata": {}, + "outputs": [], + "source": [ + "def show_some(player,dealer):\n", + " print(\"\\nDealer's Hand:\")\n", + " print(\"