diff --git a/intro_python.ipynb b/intro_python.ipynb index 0401968..b72914d 100644 --- a/intro_python.ipynb +++ b/intro_python.ipynb @@ -95,7 +95,7 @@ } }, "source": [ - "## Data types and Variables\n", + "# Data types and Variables\n", "\n", "\n", "Variables in Python hide what is inside of them. It is _extremely_ important that, whenever you are working with variables, you have in mind what TYPE of thing the variable holds. One way to help yourself is to use helpful names with variables (hint: don't use \"x\"!).\n", @@ -112,22 +112,34 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 7, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "skip" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "float" + ] + }, + "execution_count": 7, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Numbers\n", "\n", "x = 3\n", - "y = 3.2" + "y = 3.2\n", + "\n", + "type(y)" ] }, { @@ -135,7 +147,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -155,7 +166,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -164,7 +174,7 @@ }, "outputs": [], "source": [ - "# Boolean\n", + "# Boolean; case sensitive\n", "\n", "x = True \n", "x = False " @@ -175,7 +185,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -267,17 +276,34 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 9, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "7.5\n" + ] + }, + { + "data": { + "text/plain": [ + "True" + ] + }, + "execution_count": 9, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Printing - note how Jupyter automatically prints \"y\" to \"out\", \n", "# but we need to manually print \"x\" if we want to see it!\n", @@ -311,7 +337,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -332,7 +357,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -353,7 +377,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -424,17 +447,24 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 12, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "low\n" + ] + } + ], "source": [ "# Practise control flow: \n", "# write some code that prints \"high\" if\n", @@ -443,7 +473,12 @@ "\n", "x = 5\n", "\n", - "# your code here! Hint: use if/else and print." + "# your code here! Hint: use if/else and print.\n", + "\n", + "if x > 5:\n", + " print(\"high\")\n", + "else:\n", + " print(\"low\")" ] }, { @@ -509,7 +544,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -529,24 +563,38 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 23, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "1\n", + "2\n", + "10\n", + "100\n" + ] + } + ], "source": [ "# Challenge: repeat the above cell, but only print the age if the\n", "# age exists (i.e. is not None). HINT: Look back at the cells on\n", "# logical operations to see how to check if a value is None in Python\n", "\n", "\n", - "# Your code here" + "# Your code here\n", + "ages = [1, 2, 10, None, 100]\n", + "for age in ages:\n", + " if age != None:\n", + " print(age)\n" ] }, { @@ -619,17 +667,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "148.5" + ] + }, + "execution_count": 16, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Aggregation: \n", "# Summing the numbers in a list: \n", @@ -646,24 +704,34 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 25, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "1" + ] + }, + "execution_count": 25, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Aggregation: \n", "# Finding the minimum number in a list of number: \n", "\n", "nums = [30,1,4,3,10.5,100]\n", "\n", - "min_num = x[0] \n", + "min_num = nums[0] \n", "\n", "for num in nums: \n", " if num < min_num:\n", @@ -674,17 +742,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 38, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "2" + ] + }, + "execution_count": 38, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Challenge!\n", "\n", @@ -696,7 +774,8 @@ "total = 0 \n", "\n", "for num in nums:\n", - " # Your code here\n", + " if num is None:\n", + " total +=1\n", " \n", "total" ] @@ -706,7 +785,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -733,7 +811,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -756,17 +833,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 35, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[21, 45, 97]" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Filter:\n", "# Remove all values less than 18:\n", @@ -780,17 +867,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 39, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "['foo', 'bar', 'baz']" + ] + }, + "execution_count": 39, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Filter:\n", "# Remove NoneTypes from a list: \n", @@ -849,17 +946,26 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 40, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "om has scored 100 points\n", + "nandan has scored 10000 points\n", + "arapakis has scored 55 points\n" + ] + } + ], "source": [ "# Destructuring tuples in a for loop:\n", "\n", @@ -874,17 +980,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 44, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "'nandan'" + ] + }, + "execution_count": 44, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Aggregating a list of tuples: \n", "\n", @@ -894,6 +1010,15 @@ "\n", "scoreboard = [(\"om\", 100), (\"nandan\", 10000), (\"arapakis\", 55)]\n", "\n", + "teacher, score = scoreboard[0] #destrubture tuple\n", + "\n", + "for t,s in scoreboard: #destucture elements for each variatio of the tuple\n", + " if s > score: #check score against accumulated scopre\n", + " teacher,score = t,s #if greater, replace teacher and the score\n", + "\n", + "teacher\n", + "\n", + "\n", "# Your code here" ] }, @@ -934,12 +1059,32 @@ "Note that each key can ONLY HAVE ONE VALUE. In the above example, I have overwritten the original \"name\" key with a new value." ] }, + { + "cell_type": "code", + "execution_count": 1, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'nandan'" + ] + }, + "execution_count": 1, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "teacher = {\"name\": \"nandan\", \"score\": 10000}\n", + "teacher[\"name\"]\n" + ] + }, { "cell_type": "code", "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -948,18 +1093,37 @@ }, "outputs": [], "source": [ - "# Challenge: \n", - "# Collect all the likes of the teachers into one list: \n", - "# Hint: this is an aggregation!\n", + "# Functions are very useful for transforming data:\n", + "# Let's say we want the highest scores for each teacher: \n", "\n", - "# Notice: What is \"teachers\"? \n", - "# A list of dictionaries, but each dictionary has three keys \n", - "# and the \"likes\" key contains a list of strings!\n", - "teachers = [{\"name\": \"om\", \"score\": 100, \"likes\": [\"statistics\", \"more statistics\", \"even more statistics\"]},\n", - " {\"name\": \"nandan\", \"score\": 10000, \"likes\": [\"ice cream\"]},\n", - " {\"name\": \"arapakis\", \"score\": 55, \"likes\": [\"R\", \"D3\"]}]\n", + "teachers = [{\"name\": \"om\", \"scores\": [100, 200, 150]},\n", + " {\"name\": \"nandan\", \"scores\": [10000, 9999, 99987 ]},\n", + " {\"name\": \"arapakis\", \"scores\": [55, 100, 5]}]\n", "\n", - "# Your code here" + "\n", + "\n", + "# Fill in this function! \n", + "# It should take a dictionary, as in the list above, \n", + "# and it should return a 2-tuple with their name and\n", + "# their highest score: (name, score)\n", + "\n", + "def highest_score(person):\n", + " max_score = 0\n", + " print(person[\"name\"]) \n", + " for idx, score in enumerate(person['scores']):\n", + " previous_max = max_score\n", + " if score > max_score:\n", + " max_score = score\n", + " print(\"\\tScore #\" + str(idx) + \"\\tScore \" + str(score) + \"\\tCurrent max \" + str(max_score)\n", + " + \"\\tPrevious max \" + str(previous_max))\n", + " \n", + " return person['name'], max_score\n", + "\n", + "[highest_score(teacher) for teacher in teachers]\n", + "\n", + "# for teacher in teachers: # for item in list, list is teachers, defined above\n", + "# print(teacher)\n", + "# highest_score(teacher)" ] }, { @@ -1011,25 +1175,57 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 17, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'my python string'" + ] + }, + "execution_count": 17, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "z = \"My Python String\"\n", + "z.lower()" + ] + }, + { + "cell_type": "code", + "execution_count": 21, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "4" + ] + }, + "execution_count": 21, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Challenge: \n", "# Count the instances of \"foo\" in the following text, \n", "# ignoring case:\n", "\n", "x = \"Hello, I would like a foo. Foo went for a walk. Foo bar baz. Baz to the foo.\"\n", - "\n", - "# Your code here" + "x_lower = x.lower()\n", + "x_lower.count(\"foo\")\n", + "\n" ] }, { @@ -1087,17 +1283,27 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "[('om', 200), ('nandan', 99987), ('arapakis', 100)]" + ] + }, + "execution_count": 15, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Functions are very useful for transforming data:\n", "# Let's say we want the highest scores for each teacher: \n", @@ -1112,14 +1318,48 @@ "# It should take a dictionary, as in the list above, \n", "# and it should return a 2-tuple with their name and\n", "# their highest score: (name, score)\n", + "\n", "def highest_score(person):\n", - " # Your code here\n", + " max_score = 0\n", + " for score in person['scores']:\n", + " if score > max_score:\n", + " max_score = score\n", + " return person['name'], max_score\n", "\n", + "[highest_score(teacher) for teacher in teachers]\n", "\n", "\n", - "# Apply the function to each element in the list \"teachers\": \n", + "# Functions are very useful for transforming data:\n", + "# Let's say we want the highest scores for each teacher: \n", "\n", - "# Your code here" + "teachers = [{\"name\": \"om\", \"scores\": [100, 200, 150]},\n", + " {\"name\": \"nandan\", \"scores\": [10000, 9999, 99987 ]},\n", + " {\"name\": \"arapakis\", \"scores\": [55, 100, 5]}]\n", + "\n", + "\n", + "\n", + "# Fill in this function! \n", + "# It should take a dictionary, as in the list above, \n", + "# and it should return a 2-tuple with their name and\n", + "# their highest score: (name, score)\n", + "\n", + "def highest_score(person):\n", + " max_score = 0\n", + " print(person[\"name\"]) \n", + " for idx, score in enumerate(person['scores']):\n", + " previous_max = max_score\n", + " if score > max_score:\n", + " max_score = score\n", + " print(\"\\tScore #\" + str(idx) + \"\\tScore \" + str(score) + \"\\tCurrent max \" + str(max_score)\n", + " + \"\\tPrevious max \" + str(previous_max))\n", + " \n", + " return person['name'], max_score\n", + "\n", + "[highest_score(teacher) for teacher in teachers]\n", + "\n", + "# for teacher in teachers: # for item in list, list is teachers, defined above\n", + "# print(teacher)\n", + "# highest_score(teacher)" ] }, { @@ -1150,17 +1390,26 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 31, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "['Why Do People Use Python?\\n', '\\n', 'Because there are many programming languages available today, this is the usual first question of newcomers. Given that there are roughly 1 million Python users out there at the moment, there really is no way to answer this question with complete accuracy; the choice of development tools is sometimes based on unique constraints or personal preference.\\n', '\\n', 'But after teaching Python to roughly 225 groups and over 3,000 students during the last 12 years, some common themes have emerged. The primary factors cited by Python users seem to be these:\\n', '\\n', 'Software quality\\n', 'For many, Python’s focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Python code is designed to be readable, and hence reusable and maintainable—much more so than traditional scripting languages. The uniformity of Python code makes it easy to understand, even if you did not write it. In addition, Python has deep support for more advanced software reuse mechanisms, such as object-oriented programming (OOP).\\n', '\\n', 'Developer productivity\\n', 'Python boosts developer productivity many times beyond compiled or statically\\n', 'typed languages such as C, C++, and Java. Python code is typically one-third to\\n', 'one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps required by some other tools, further boosting programmer speed.\\n', '\\n', 'Program portability\\n', 'Most Python programs run unchanged on all major computer platforms. Porting\\n', 'Python code between Linux and Windows, for example, is usually just a matter of\\n', 'copying a script’s code between machines. Moreover, Python offers multiple options for coding portable graphical user interfaces, database access programs, web-based systems, and more. Even operating system interfaces, including program\\n', 'launches and directory processing, are as portable in Python as they can possibly be.\\n', '\\n', 'Support libraries\\n', 'Python comes with a large collection of prebuilt and portable functionality, known as the standard library. This library supports an array of application-level programming tasks, from text pattern matching to network scripting. In addition, Python can be extended with both homegrown libraries and a vast collection of third-party application support software. Python’s third-party domain offers tools for website construction, numeric programming, serial port access, game development, and much more. The NumPy extension, for instance, has been described as a free and more powerful equivalent to the Matlab numeric programming system.\\n', '\\n', 'Component integration\\n', 'Python scripts can easily communicate with other parts of an application, using a variety of integration mechanisms. Such integrations allow Python to be used as a product customization and extension tool. Today, Python code can invoke C and C++ libraries, can be called from C and C++ programs, can integrate with Java and .NET components, can communicate over frameworks such as COM, can\\n', 'interface with devices over serial ports, and can interact over networks with interfaces like SOAP, XML-RPC, and CORBA. It is not a standalone tool.\\n', '\\n', 'Enjoyment\\n', 'Because of Python’s ease of use and built-in toolset, it can make the act of programming more pleasure than chore. Although this may be an intangible benefit, its effect on productivity is an important asset.\\n', '\\n', 'Of these factors, the first two (quality and productivity) are probably the most compelling benefits to most Python users.\\n']\n", + "Why Do People Use Python?\n", + "\n" + ] + } + ], "source": [ "## Lets read the lines in the file\n", "with open(\"textfile.txt\",\"r\") as f:\n", @@ -1171,17 +1420,85 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 32, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Why Do People Use Python?\n", + "\n", + "\n", + "\n", + "Because there are many programming languages available today, this is the usual first question of newcomers. Given that there are roughly 1 million Python users out there at the moment, there really is no way to answer this question with complete accuracy; the choice of development tools is sometimes based on unique constraints or personal preference.\n", + "\n", + "\n", + "\n", + "But after teaching Python to roughly 225 groups and over 3,000 students during the last 12 years, some common themes have emerged. The primary factors cited by Python users seem to be these:\n", + "\n", + "\n", + "\n", + "Software quality\n", + "\n", + "For many, Python’s focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Python code is designed to be readable, and hence reusable and maintainable—much more so than traditional scripting languages. The uniformity of Python code makes it easy to understand, even if you did not write it. In addition, Python has deep support for more advanced software reuse mechanisms, such as object-oriented programming (OOP).\n", + "\n", + "\n", + "\n", + "Developer productivity\n", + "\n", + "Python boosts developer productivity many times beyond compiled or statically\n", + "\n", + "typed languages such as C, C++, and Java. Python code is typically one-third to\n", + "\n", + "one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps required by some other tools, further boosting programmer speed.\n", + "\n", + "\n", + "\n", + "Program portability\n", + "\n", + "Most Python programs run unchanged on all major computer platforms. Porting\n", + "\n", + "Python code between Linux and Windows, for example, is usually just a matter of\n", + "\n", + "copying a script’s code between machines. Moreover, Python offers multiple options for coding portable graphical user interfaces, database access programs, web-based systems, and more. Even operating system interfaces, including program\n", + "\n", + "launches and directory processing, are as portable in Python as they can possibly be.\n", + "\n", + "\n", + "\n", + "Support libraries\n", + "\n", + "Python comes with a large collection of prebuilt and portable functionality, known as the standard library. This library supports an array of application-level programming tasks, from text pattern matching to network scripting. In addition, Python can be extended with both homegrown libraries and a vast collection of third-party application support software. Python’s third-party domain offers tools for website construction, numeric programming, serial port access, game development, and much more. The NumPy extension, for instance, has been described as a free and more powerful equivalent to the Matlab numeric programming system.\n", + "\n", + "\n", + "\n", + "Component integration\n", + "\n", + "Python scripts can easily communicate with other parts of an application, using a variety of integration mechanisms. Such integrations allow Python to be used as a product customization and extension tool. Today, Python code can invoke C and C++ libraries, can be called from C and C++ programs, can integrate with Java and .NET components, can communicate over frameworks such as COM, can\n", + "\n", + "interface with devices over serial ports, and can interact over networks with interfaces like SOAP, XML-RPC, and CORBA. It is not a standalone tool.\n", + "\n", + "\n", + "\n", + "Enjoyment\n", + "\n", + "Because of Python’s ease of use and built-in toolset, it can make the act of programming more pleasure than chore. Although this may be an intangible benefit, its effect on productivity is an important asset.\n", + "\n", + "\n", + "\n", + "Of these factors, the first two (quality and productivity) are probably the most compelling benefits to most Python users.\n", + "\n" + ] + } + ], "source": [ "# Since we have a list, we can resort to the usual tricks, e.g. \n", "with open(\"textfile.txt\",\"r\") as f:\n", @@ -1192,17 +1509,25 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 33, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Why Do People Use Python?\n", + "\n" + ] + } + ], "source": [ "# We can also read single lines\n", "\n", @@ -1236,24 +1561,436 @@ }, { "cell_type": "code", - "execution_count": null, - "metadata": { - "autoscroll": false, - "collapsed": false, - "ein.hycell": false, - "ein.tags": "worksheet-0", - "slideshow": { - "slide_type": "-" + "execution_count": 129, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Why Do People Use Python?\n", + "\n", + "Because there are many programming languages available today, this is the usual first question of newcomers. Given that there are roughly 1 million Python users out there at the moment, there really is no way to answer this question with complete accuracy; the choice of development tools is sometimes based on unique constraints or personal preference.\n", + "\n", + "But after teaching Python to roughly 225 groups and over 3,000 students during the last 12 years, some common themes have emerged. The primary factors cited by Python users seem to be these:\n", + "\n", + "Software quality\n", + "For many, Python’s focus on readability, coherence, and software quality in general sets it apart from other tools in the scripting world. Python code is designed to be readable, and hence reusable and maintainable—much more so than traditional scripting languages. The uniformity of Python code makes it easy to understand, even if you did not write it. In addition, Python has deep support for more advanced software reuse mechanisms, such as object-oriented programming (OOP).\n", + "\n", + "Developer productivity\n", + "Python boosts developer productivity many times beyond compiled or statically\n", + "typed languages such as C, C++, and Java. Python code is typically one-third to\n", + "one-fifth the size of equivalent C++ or Java code. That means there is less to type, less to debug, and less to maintain after the fact. Python programs also run immediately, without the lengthy compile and link steps required by some other tools, further boosting programmer speed.\n", + "\n", + "Program portability\n", + "Most Python programs run unchanged on all major computer platforms. Porting\n", + "Python code between Linux and Windows, for example, is usually just a matter of\n", + "copying a script’s code between machines. Moreover, Python offers multiple options for coding portable graphical user interfaces, database access programs, web-based systems, and more. Even operating system interfaces, including program\n", + "launches and directory processing, are as portable in Python as they can possibly be.\n", + "\n", + "Support libraries\n", + "Python comes with a large collection of prebuilt and portable functionality, known as the standard library. This library supports an array of application-level programming tasks, from text pattern matching to network scripting. In addition, Python can be extended with both homegrown libraries and a vast collection of third-party application support software. Python’s third-party domain offers tools for website construction, numeric programming, serial port access, game development, and much more. The NumPy extension, for instance, has been described as a free and more powerful equivalent to the Matlab numeric programming system.\n", + "\n", + "Component integration\n", + "Python scripts can easily communicate with other parts of an application, using a variety of integration mechanisms. Such integrations allow Python to be used as a product customization and extension tool. Today, Python code can invoke C and C++ libraries, can be called from C and C++ programs, can integrate with Java and .NET components, can communicate over frameworks such as COM, can\n", + "interface with devices over serial ports, and can interact over networks with interfaces like SOAP, XML-RPC, and CORBA. It is not a standalone tool.\n", + "\n", + "Enjoyment\n", + "Because of Python’s ease of use and built-in toolset, it can make the act of programming more pleasure than chore. Although this may be an intangible benefit, its effect on productivity is an important asset.\n", + "\n", + "Of these factors, the first two (quality and productivity) are probably the most compelling benefits to most Python users.\n", + "\n" + ] } - }, - "outputs": [], - "source": [] + ], + "source": [ + "#read the file and see what it looks like\n", + "with open (\"textfile.txt\", \"r\") as f:\n", + " linesf = f.read()\n", + " print(linesf)" + ] + }, + { + "cell_type": "code", + "execution_count": 130, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "550\n" + ] + } + ], + "source": [ + "#count the number of words\n", + "with open (\"textfile.txt\", \"r\") as f:\n", + " wordsf = f.read().replace('\\n', ' ').split()\n", + "# print(wordsf)\n", + " print(len(wordsf))" + ] + }, + { + "cell_type": "code", + "execution_count": 131, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "29\n" + ] + } + ], + "source": [ + "#count the number of sentences\n", + "with open (\"textfile.txt\", \"r\") as f:\n", + " sentencesf = f.read().replace('\\n', ' ').replace('?', '.').count('.')\n", + " print(sentencesf)" + ] + }, + { + "cell_type": "code", + "execution_count": 132, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "Why\n", + "Do\n", + "People\n", + "Use\n", + "Python\n", + "Because\n", + "there\n", + "are\n", + "many\n", + "programming\n", + "languages\n", + "available\n", + "today\n", + "this\n", + "is\n", + "the\n", + "usual\n", + "first\n", + "question\n", + "of\n", + "newcomers\n", + "Given\n", + "that\n", + "roughly\n", + "1\n", + "million\n", + "users\n", + "out\n", + "at\n", + "moment\n", + "really\n", + "no\n", + "way\n", + "to\n", + "answer\n", + "with\n", + "complete\n", + "accuracy\n", + "choice\n", + "development\n", + "tools\n", + "sometimes\n", + "based\n", + "on\n", + "unique\n", + "constraints\n", + "or\n", + "personal\n", + "preference\n", + "But\n", + "after\n", + "teaching\n", + "225\n", + "groups\n", + "and\n", + "over\n", + "3000\n", + "students\n", + "during\n", + "last\n", + "12\n", + "years\n", + "some\n", + "common\n", + "themes\n", + "have\n", + "emerged\n", + "The\n", + "primary\n", + "factors\n", + "cited\n", + "by\n", + "seem\n", + "be\n", + "these\n", + "Software\n", + "quality\n", + "For\n", + "Python’s\n", + "focus\n", + "readability\n", + "coherence\n", + "software\n", + "in\n", + "general\n", + "sets\n", + "it\n", + "apart\n", + "from\n", + "other\n", + "scripting\n", + "world\n", + "code\n", + "designed\n", + "readable\n", + "hence\n", + "reusable\n", + "maintainable—much\n", + "more\n", + "so\n", + "than\n", + "traditional\n", + "uniformity\n", + "makes\n", + "easy\n", + "understand\n", + "even\n", + "if\n", + "you\n", + "did\n", + "not\n", + "write\n", + "In\n", + "addition\n", + "has\n", + "deep\n", + "support\n", + "for\n", + "advanced\n", + "reuse\n", + "mechanisms\n", + "such\n", + "as\n", + "object-oriented\n", + "OOP\n", + "Developer\n", + "productivity\n", + "boosts\n", + "developer\n", + "times\n", + "beyond\n", + "compiled\n", + "statically\n", + "typed\n", + "C\n", + "C++\n", + "Java\n", + "typically\n", + "one-third\n", + "one-fifth\n", + "size\n", + "equivalent\n", + "That\n", + "means\n", + "less\n", + "type\n", + "debug\n", + "maintain\n", + "fact\n", + "programs\n", + "also\n", + "run\n", + "immediately\n", + "without\n", + "lengthy\n", + "compile\n", + "link\n", + "steps\n", + "required\n", + "further\n", + "boosting\n", + "programmer\n", + "speed\n", + "Program\n", + "portability\n", + "Most\n", + "unchanged\n", + "all\n", + "major\n", + "computer\n", + "platforms\n", + "Porting\n", + "between\n", + "Linux\n", + "Windows\n", + "example\n", + "usually\n", + "just\n", + "a\n", + "matter\n", + "copying\n", + "script’s\n", + "machines\n", + "Moreover\n", + "offers\n", + "multiple\n", + "options\n", + "coding\n", + "portable\n", + "graphical\n", + "user\n", + "interfaces\n", + "database\n", + "access\n", + "web-based\n", + "systems\n", + "Even\n", + "operating\n", + "system\n", + "including\n", + "program\n", + "launches\n", + "directory\n", + "processing\n", + "they\n", + "can\n", + "possibly\n", + "Support\n", + "libraries\n", + "comes\n", + "large\n", + "collection\n", + "prebuilt\n", + "functionality\n", + "known\n", + "standard\n", + "library\n", + "This\n", + "supports\n", + "an\n", + "array\n", + "application-level\n", + "tasks\n", + "text\n", + "pattern\n", + "matching\n", + "network\n", + "extended\n", + "both\n", + "homegrown\n", + "vast\n", + "third-party\n", + "application\n", + "domain\n", + "website\n", + "construction\n", + "numeric\n", + "serial\n", + "port\n", + "game\n", + "much\n", + "NumPy\n", + "extension\n", + "instance\n", + "been\n", + "described\n", + "free\n", + "powerful\n", + "Matlab\n", + "Component\n", + "integration\n", + "scripts\n", + "easily\n", + "communicate\n", + "parts\n", + "using\n", + "variety\n", + "Such\n", + "integrations\n", + "allow\n", + "used\n", + "product\n", + "customization\n", + "tool\n", + "Today\n", + "invoke\n", + "called\n", + "integrate\n", + "NET\n", + "components\n", + "frameworks\n", + "COM\n", + "interface\n", + "devices\n", + "ports\n", + "interact\n", + "networks\n", + "like\n", + "SOAP\n", + "XML-RPC\n", + "CORBA\n", + "It\n", + "standalone\n", + "Enjoyment\n", + "ease\n", + "use\n", + "built-in\n", + "toolset\n", + "make\n", + "act\n", + "pleasure\n", + "chore\n", + "Although\n", + "may\n", + "intangible\n", + "benefit\n", + "its\n", + "effect\n", + "important\n", + "asset\n", + "Of\n", + "two\n", + "probably\n", + "most\n", + "compelling\n", + "benefits\n" + ] + } + ], + "source": [ + "with open (\"textfile.txt\", \"r\") as f:\n", + " wordsf = f.read().replace('\\n', ' ').replace(\".\",\"\").replace(\",\",\"\").replace(\"?\",\"\").replace(\";\",\"\").replace(\":\",\"\").replace(\"(\",\"\").replace(\")\",\"\").split()\n", + " \n", + " def unique(wordsf):\n", + " unique_list = []\n", + " \n", + " for word in wordsf:\n", + " if word not in unique_list:\n", + " unique_list.append(word)\n", + " for word in unique_list:\n", + " print(word)\n", + " \n", + "unique(wordsf)" + ] } ], "metadata": { "celltoolbar": "Slideshow", "kernelspec": { "display_name": "Python 3", + "language": "python", "name": "python3" }, "language_info": { diff --git a/more_python.ipynb b/more_python.ipynb index 53912a1..6332872 100644 --- a/more_python.ipynb +++ b/more_python.ipynb @@ -9,19 +9,7 @@ } }, "source": [ - "# More advanced concepts in Python!" - ] - }, - { - "cell_type": "markdown", - "metadata": { - "ein.tags": "worksheet-0", - "slideshow": { - "slide_type": "-" - } - }, - "source": [ - "# Behind the scenes of value assignement\n", + "# Behind the scenes of value assignment\n", "\n", "This is a deep concept, that relates to how python uses memory under-the-hood, but a working knowledge of how it works is critical to avoid creating an unintentional mess!\n", "\n", @@ -30,21 +18,83 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 3, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "([1, 2, 10], [1, 2, 10])" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "a = [1,2,5]\n", "b = a\n", - "b[2] = 10" + "b[2] = 10\n", + "\n", + "a,b" + ] + }, + { + "cell_type": "code", + "execution_count": 4, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "('hello', 'hello')" + ] + }, + "execution_count": 4, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "a = 'hello'\n", + "b = a\n", + "a,b" + ] + }, + { + "cell_type": "code", + "execution_count": 8, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "('bahbahahah', 'bahbahahah')" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "def data_cleaning(a):\n", + " a[2] = 'bahbahahah'\n", + " return a\n", + "\n", + "my_raw_data = [1,2,3,4]\n", + "\n", + "my_clean_data = data_cleaning(my_raw_data)\n", + "\n", + "my_clean_data[2], my_raw_data[2] #return the 2nd element for each of the data sets\n" ] }, { @@ -56,7 +106,7 @@ } }, "source": [ - "## Copy vs assignement\n", + "## Copy vs assignment\n", "\n", "What happens is that really a and b point to the same place in the memory and share the same data. \n", "\n", @@ -71,22 +121,33 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 11, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "([1, [2, 3, 100], 5, 'om'], [1, [2, 3, 100], 5, 'om'])" + ] + }, + "execution_count": 11, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "a = [1,[2,3],5,\"om\"] \n", - "b = a.copy()\n", + "b = a.copy() #copy the data set so you don't override the original\n", "b[1].append(100)\n", - "## Print a, b and be surprised!" + "## Print a, b and be surprised!\n", + "a,b" ] }, { @@ -94,7 +155,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -134,10 +194,9 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 13, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -151,7 +210,7 @@ "Exception" ] }, - "execution_count": 58, + "execution_count": 13, "metadata": {}, "output_type": "execute_result" } @@ -161,24 +220,35 @@ "# Exceptions are created as follows:\n", "\n", "e = Exception()\n", - "type(e)" + "type(e) #<== Created an exception but did not throw an exception" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 14, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "ename": "Exception", + "evalue": "Oops!", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;31m# Exceptions are raised with the \"raise\" keyword:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'Oops!'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mException\u001b[0m: Oops!" + ] + } + ], "source": [ - "# There is no point in creating an exception with \"raising\"\n", + "# There is no point in creating an exception without \"raising\"\n", "# the exception. \n", "# Exceptions are raised with the \"raise\" keyword: \n", "\n", @@ -187,17 +257,29 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 15, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "ename": "Exception", + "evalue": "The person must have an age attribute! Given: notaperson", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 10\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mperson\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 12\u001b[0;31m \u001b[0mage_a_person\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'notaperson'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mage_a_person\u001b[0;34m(person)\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mage_a_person\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mperson\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mhasattr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mperson\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'age'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;31m#raises an exception if the person does not have the required age attribute\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf'The person must have an age attribute! Given: {person}'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mperson\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mException\u001b[0m: The person must have an age attribute! Given: notaperson" + ] + } + ], "source": [ "# Every \"part\" of your program, for example each function, must be in charge\n", "# of things \"going as expected\" inside its body. If something goes wrong, it should\n", @@ -206,7 +288,7 @@ "# One way to do this is to check for possible problems before they occur: \n", "\n", "def age_a_person(person):\n", - " if not hasattr(person, 'age'):\n", + " if not hasattr(person, 'age'): #raises an exception if the person does not have the required age attribute\n", " raise Exception(f'The person must have an age attribute! Given: {person}')\n", " return person.age + 1\n", "\n", @@ -215,17 +297,29 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 16, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "ename": "Exception", + "evalue": "The person must have an age attribute! Given: notaperson", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mException\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[1;32m 12\u001b[0m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf'The person must have an age attribute! Given: {person}'\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32mfrom\u001b[0m \u001b[0me\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 13\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 14\u001b[0;31m \u001b[0mage_a_person\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m'notaperson'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;32m\u001b[0m in \u001b[0;36mage_a_person\u001b[0;34m(person)\u001b[0m\n\u001b[1;32m 7\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0mage_a_person\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mperson\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 8\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0;32mnot\u001b[0m \u001b[0mhasattr\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mperson\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0;34m'age'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m \u001b[0;31m#raises an exception if the person does not have the required age attribute\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 9\u001b[0;31m \u001b[0;32mraise\u001b[0m \u001b[0mException\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34mf'The person must have an age attribute! Given: {person}'\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m 10\u001b[0m \u001b[0;32mreturn\u001b[0m \u001b[0mperson\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mage\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m1\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 11\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n", + "\u001b[0;31mException\u001b[0m: The person must have an age attribute! Given: notaperson" + ] + } + ], "source": [ "# However, Python encourages a pattern referred to as \"EAFP\":\n", "# Easier to Ask Forgiveness then Permission \n", @@ -267,6 +361,8 @@ "\n", "To do things more complicated than we can keep in our heads at once, we need to break things down into component parts. Object Oriented Programming is a design pattern to do just that. \n", "\n", + "#Benefits of object oriented programming: saves time, more efficient and allows you to share code\n", + "\n", "## Understanding State\n", "\n", "To understand object-oriented programming, it's important first to understand the term **state**.\n", @@ -301,6 +397,9 @@ "\n", "This is single-dispatch polymorphism!\n", "\n", + "#the idea that different classes can share an interface or part of an interface. Allows they to be really decoupled. You just need to know that they share an interaface. \n", + "\n", + "\n", "## Methods\n", "\n", "Again, in O-O programming, ojects are both responsible for keeping track of their own state, and also responsible for knowing how to change it.\n", @@ -316,10 +415,9 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 61, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -334,8 +432,8 @@ "# How do we construct a class? With a \"constructor\" method!\n", "# In python, the constructor method is called \"__init__\":\n", "\n", - "class Animal():\n", - " def __init__(self, location):\n", + "class Animal(): #convention is to capitalize the class name and don't leave spaces (e.g., AnimalFromForest - this is called camel case)\n", + " def __init__(self, location): #methods start with def, are indented and inside class\n", " # location is a tuple: (int, int)\n", " self.location = location\n", " self.water = 0\n", @@ -349,68 +447,156 @@ " def distance(self, loc):\n", " x,y = self.location\n", " xa,ya = loc\n", - " return (x - xa)**2 + (y - ya)**2" + " return (x - xa)**2 + (y - ya)**2\n", + " \n", + "animal = Animal((2,5)) #why doesn't this return 2,5 as Nandan's did?\n" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 32, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "True\n", + "True\n", + "True\n" + ] + } + ], "source": [ "# Instatiating the class\n", "\n", - "animal = Animal((10, 50))" + "animal = [Animal((10, 50)) for x,y in [(10,50), (5,10), (2,3)]]\n", + " \n", + "for animal in animals:\n", + " print(animal.is_thirsty())" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 35, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 35, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# See the methods at work! \n", "\n", "animal.is_thirsty()\n", "\n", + "animal.give_water(1)\n", + "animal.is_thirsty()\n", + "\n", + "\n", + "\n", "# Give it water! See if it's satiated!" ] }, + { + "cell_type": "code", + "execution_count": 50, + "metadata": {}, + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "heyoooo!\n" + ] + } + ], + "source": [ + "class Simple():\n", + " def __init__(self, a=1):\n", + " print('heyoooo!')\n", + " self.a = a #inside a class, you can define an attribute on the self within a class\n", + " \n", + "s = Simple('foo') #s is an instance of a Simple" + ] + }, + { + "cell_type": "code", + "execution_count": 51, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "'foo'" + ] + }, + "execution_count": 51, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "s.a" + ] + }, { "cell_type": "code", "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [] + }, + { + "cell_type": "code", + "execution_count": 58, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "False" + ] + }, + "execution_count": 58, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "import random\n", "\n", "# Example of inheritance\n", - "class Fox(Animal):\n", - " def __init__(self, location, slyness):\n", + "class Fox(Animal): #Fox is a child class. defined by putting the parent class in the ().\n", + " def __init__(self, location, slyness): #self is always automatically passed in a class\n", " # slyness is a float between [0., 1.]\n", " super().__init__(location)\n", " self.slyness = slyness\n", @@ -422,7 +608,34 @@ " return self.water < 1\n", "\n", "\n", - "# Try creating a fox. " + "# Try creating a fox.\n", + "\n", + "fox = Fox((0,10), .8)\n", + "\n", + "type(fox)\n", + "\n", + "fox.is_thirsty()" + ] + }, + { + "cell_type": "code", + "execution_count": 59, + "metadata": {}, + "outputs": [ + { + "ename": "AttributeError", + "evalue": "'list' object has no attribute 'give_water'", + "output_type": "error", + "traceback": [ + "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m", + "\u001b[0;31mAttributeError\u001b[0m Traceback (most recent call last)", + "\u001b[0;32m\u001b[0m in \u001b[0;36m\u001b[0;34m\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mb\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mgive_water\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;36m1\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m", + "\u001b[0;31mAttributeError\u001b[0m: 'list' object has no attribute 'give_water'" + ] + } + ], + "source": [ + "b.give_water(1)" ] }, { @@ -457,16 +670,46 @@ { "cell_type": "code", "execution_count": null, + "metadata": {}, + "outputs": [], + "source": [ + "# Every \"part\" of your program, for example each function, must be in charge\n", + "# of things \"going as expected\" inside its body. If something goes wrong, it should\n", + "# tell us what happened! \n", + "\n", + "# One way to do this is to check for possible problems before they occur: \n", + "\n", + "def age_a_person(person):\n", + " if not hasattr(person, 'age'): #raises an exception if the person does not have the required age attribute\n", + " raise Exception(f'The person must have an age attribute! Given: {person}')\n", + " return person.age + 1\n", + "\n", + "age_a_person('notaperson')" + ] + }, + { + "cell_type": "code", + "execution_count": 81, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "9" + ] + }, + "execution_count": 81, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Challenge: \n", "\n", @@ -475,6 +718,7 @@ "# This classifier should have two methods: fit, predict\n", "\n", "# The \"fit\" method should accept arguments: x,y (both lists of numbers)\n", + "\n", "# The \"predict\" method should accept arguments: x (a single number)\n", "\n", "# This classifier is getting very old. For any x value it is expected to predict, it simply guesses the last Y value that it has seen (the last value in the list, y, passed to \"fit\").\n", @@ -483,17 +727,30 @@ "\n", "\n", "class ForgetfulClassifier():\n", - " # Your code here\n", - " pass\n", + " def __init__(self):\n", + " self.x = None\n", + " self.y = None\n", + " pass\n", + " \n", + " def fit(self, x, y):\n", + " self.x = x\n", + " self.y = y\n", + " \n", + " def predict(self,x):\n", + " if ((self.x == None) or (self.y == None)):\n", + " raise Exception(f'Must call \"fit\" before \"predict\"')\n", + " return self.y[-1]\n", + " \n", "\n", "\n", "\n", "clf = ForgetfulClassifier()\n", "\n", "clf.fit([1,2,3,4,5], [5,6,7,8,9])\n", + "clf.predict(3)\n", "\n", - "assert(clf.predict(10) == 9)\n", - "assert(clf.predict(5000) == 9)" + "# assert(clf.predict(10) == 9)\n", + "# assert(clf.predict(5000) == 9)" ] }, { @@ -519,7 +776,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -536,7 +792,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -555,7 +810,6 @@ "execution_count": null, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { @@ -580,7 +834,7 @@ "## Typical import structures\n", "\n", "```python\n", - "from math import sin # imports a single function\n", + "from math import sin # imports a single function from the math module\n", "\n", "from math import sin as sinus # nickname, this is useful when the function imported has long and complicated name\n", "\n", @@ -588,24 +842,31 @@ "import math # this imports the module in the name space, methods can then be accessed e.g.\n", "math.sin(3)\n", "\n", - "from math import * #imports all methods in the namespace, not recommended!\n", + "from math import * #imports all methods in the namespace, not recommended! NEVER DO THIS as it would override the existing functions (e.g., if there's one called sin and math has one called sin, it would override)\n", "\n", "```" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 62, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "hello world\n" + ] + } + ], "source": [ "# Another import example: importing my own functions\n", "\n", @@ -665,29 +926,49 @@ }, { "cell_type": "code", - "execution_count": null, + "execution_count": 66, "metadata": { "autoscroll": false, - "collapsed": false, "ein.hycell": false, "ein.tags": "worksheet-0", "slideshow": { "slide_type": "-" } }, - "outputs": [], + "outputs": [ + { + "name": "stdout", + "output_type": "stream", + "text": [ + "(5, 10, 100, 200)\n" + ] + }, + { + "data": { + "text/plain": [ + "200" + ] + }, + "execution_count": 66, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "# Function for maximum of a variable number of inputs\n", "\n", - "def maxmany(x=float(\"inf\"),*extra): # this specification makes \n", - " # extra a tuple!!\n", + "def maxmany(x=float(\"inf\"),*args): # this specification makes \n", + " # extra a tuple!! ## put args if you don't know how many arguments you want\n", " runmax = x\n", - " for y in extra: \n", + " print(args)\n", + " for y in args: \n", " if runmax