diff --git a/.idea/.gitignore b/.idea/.gitignore
new file mode 100644
index 0000000..26d3352
--- /dev/null
+++ b/.idea/.gitignore
@@ -0,0 +1,3 @@
+# Default ignored files
+/shelf/
+/workspace.xml
diff --git a/.idea/Python3_Jupyter_Notebook.iml b/.idea/Python3_Jupyter_Notebook.iml
new file mode 100644
index 0000000..d0876a7
--- /dev/null
+++ b/.idea/Python3_Jupyter_Notebook.iml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/Project_Default.xml b/.idea/inspectionProfiles/Project_Default.xml
new file mode 100644
index 0000000..38e555a
--- /dev/null
+++ b/.idea/inspectionProfiles/Project_Default.xml
@@ -0,0 +1,28 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/inspectionProfiles/profiles_settings.xml b/.idea/inspectionProfiles/profiles_settings.xml
new file mode 100644
index 0000000..105ce2d
--- /dev/null
+++ b/.idea/inspectionProfiles/profiles_settings.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/misc.xml b/.idea/misc.xml
new file mode 100644
index 0000000..7d7a254
--- /dev/null
+++ b/.idea/misc.xml
@@ -0,0 +1,4 @@
+
+
+
+
\ No newline at end of file
diff --git a/.idea/modules.xml b/.idea/modules.xml
new file mode 100644
index 0000000..814676a
--- /dev/null
+++ b/.idea/modules.xml
@@ -0,0 +1,8 @@
+
+
+
+
+
+
+
+
\ No newline at end of file
diff --git a/.idea/vcs.xml b/.idea/vcs.xml
new file mode 100644
index 0000000..35eb1dd
--- /dev/null
+++ b/.idea/vcs.xml
@@ -0,0 +1,6 @@
+
+
+
+
+
+
\ No newline at end of file
diff --git a/PythonIntro.ipynb b/PythonIntro.ipynb
index d6b9a14..fc0d927 100644
--- a/PythonIntro.ipynb
+++ b/PythonIntro.ipynb
@@ -1,54 +1,54 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# An Introduction To Scripting in Python 3\n",
- "By __[Hans van der Kwast](http://www.linkedin.com/in/jvdkwast)__ \n",
- "__[IHE Delft Institute for Water Education](http://www.un-ihe.org)__ \n",
- "Twitter: @hansakwast\n",
- "\n",
- "\n",
- "## Contents\n",
- "### __[Lesson 1: Very Simple Programs](PythonIntroCh1.ipynb)__\n",
- "### __[Lesson 2: Programs in a file, variables and strings](PythonIntroCh2.ipynb)__\n",
- "### __[Lesson 3: Loops, Loops, Loops, Loops...](PythonIntroCh3.ipynb)__\n",
- "### __[Lesson 4: Functions](PythonIntroCh4.ipynb)__\n",
- "### __[Lesson 5: Tuples, Lists, and Dictionaries](PythonIntroCh5.ipynb)__\n",
- "### __[Lesson 6: For Loop](PythonIntroCh6.ipynb)__\n",
- "### __[Lesson 7: Classes](PythonIntroCh7.ipynb)__\n",
- "### __[Lesson 8: Modules](PythonIntroCh8.ipynb)__\n",
- "### __[Lesson 9: File I/O](PythonIntroCh9.ipynb)__\n",
- "### __[Lesson 10: Exception Handling](PythonIntroCh10.ipynb)__\n",
- " \n",
- " \n",
- "\n",
- "*This Jupyter Notebook has been developed based on \"A Beginner's Python Tutorial\" by Steven Thurlow. The __[original material](https://github.com/stoive/pythontutorial)__ has been ported to Python 3.*\n",
- "\n",
- "*This work is licensed under the Creative Commons Attribution 2.5 Australia License. To view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/au/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.*"
- ]
- }
- ],
- "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.5"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# An Introduction To Scripting in Python 3\n",
+ "By __[Hans van der Kwast](http://www.linkedin.com/in/jvdkwast)__ \n",
+ "__[IHE Delft Institute for Water Education](http://www.un-ihe.org)__ \n",
+ "X (Formerly Twitter): @hansakwast\n",
+ "\n",
+ "\n",
+ "## Contents\n",
+ "### __[Lesson 1: Very Simple Programs](PythonIntroCh1.ipynb)__\n",
+ "### __[Lesson 2: Programs in a file, variables and strings](PythonIntroCh2.ipynb)__\n",
+ "### __[Lesson 3: Loops, Loops, Loops, Loops...](PythonIntroCh3.ipynb)__\n",
+ "### __[Lesson 4: Functions](PythonIntroCh4.ipynb)__\n",
+ "### __[Lesson 5: Tuples, Lists, and Dictionaries](PythonIntroCh5.ipynb)__\n",
+ "### __[Lesson 6: For Loop](PythonIntroCh6.ipynb)__\n",
+ "### __[Lesson 7: Classes](PythonIntroCh7.ipynb)__\n",
+ "### __[Lesson 8: Modules](PythonIntroCh8.ipynb)__\n",
+ "### __[Lesson 9: File I/O](PythonIntroCh9.ipynb)__\n",
+ "### __[Lesson 10: Exception Handling](PythonIntroCh10.ipynb)__\n",
+ " \n",
+ " \n",
+ "\n",
+ "*This Jupyter Notebook has been developed based on \"A Beginner's Python Tutorial\" by Steven Thurlow. The __[original material](https://github.com/stoive/pythontutorial)__ has been ported to Python 3.*\n",
+ "\n",
+ "*This work is licensed under the Creative Commons Attribution 2.5 Australia License. To view a copy of this license, visit http://creativecommons.org/licenses/by/2.5/au/ or send a letter to Creative Commons, 444 Castro Street, Suite 900, Mountain View, California, 94041, USA.*"
+ ]
+ }
+ ],
+ "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.5"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/PythonIntroCh1.ipynb b/PythonIntroCh1.ipynb
index f6a6480..148908f 100644
--- a/PythonIntroCh1.ipynb
+++ b/PythonIntroCh1.ipynb
@@ -13,13 +13,12 @@
"source": [
"# 1. Very simple 'programs'\n",
"## 1.1 Running Python from the command line\n",
- "In order to test pieces of code we can run Python from the command line. In this Jupyter Notebook we are going to simulate this. You can type the commands in the fields and execute them. \n",
+ "In order to test pieces of code, we can run Python from the command line. In this Jupyter Notebook, we are going to simulate this. You can type the commands in the fields and execute them. \n",
"In the field type: \n",
"```python\n",
"print('Hello, World')\n",
"```\n",
- "Then press ` + ` to execute the command.\n",
- "\n"
+ "Then press Shift + Return to execute the command."
]
},
{
@@ -35,7 +34,7 @@
"source": [
"What happened?\n",
"\n",
- "You just created a program, that prints the words 'Hello, World'. The Python environment that you are in immediately compiles whatever you have typed in. This is useful for testing things, e.g. define a few variables, and then test to see if a certain line will work. That will come in a later lesson, though."
+ "You just created a program that prints the words 'Hello, World'. The Python environment that you are in immediately compiles whatever you have typed in. This is useful for testing things, e.g. define a few variables, and then test to see if a certain line will work. That will come in a later lesson, though."
]
},
{
@@ -178,7 +177,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "This demonstrates that you can print text and calculations in a sentence. The commas separating each section are a way of separating strings (text) from calculations or variable."
+ "This demonstrates that you can print text and calculations in a sentence. The commas separating each section are a way of separating strings (text) from calculations or variables."
]
},
{
@@ -233,7 +232,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Remember that thing called order of operation that they taught in maths? Well, it applies in Python, too. Here it is, if you need reminding: \n",
+ "Remember that thing called the order of operations that they taught in maths? Well, it applies in Python, too. Here it is, if you need reminding: \n",
"1. Parenthesis `()`\n",
"2. Exponents `**`\n",
"3. Multiplication `*`, division `/` and remainder `%`\n",
diff --git a/PythonIntroCh10.ipynb b/PythonIntroCh10.ipynb
index c538987..e4d2865 100644
--- a/PythonIntroCh10.ipynb
+++ b/PythonIntroCh10.ipynb
@@ -1,339 +1,339 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "< [File I/O](PythonIntroCh9.ipynb) | [Contents](PythonIntro.ipynb) >"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "# 10. Exception Handling\n",
- "## 10.1 Introduction\n",
- "If you haven't seen them before, you're not trying hard enough. What are they? Errors. Exceptions. Problems. Know what I'm talking about? I got it with this program: "
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "def menu(list, question):\n",
- " for entry in list:\n",
- " print(1 + list.index(entry),end=\"\")\n",
- " print(\") \" + entry)\n",
- "\n",
- " return input(question) - 1\n",
- "\n",
- "# running the function\n",
- "# remember what the backslash does\n",
- "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
- "'Which letter is your favourite? ')\n",
- "\n",
- "print('You picked answer ' + str(answer + 1))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "This is just an example of the menu program we made earlier. Appears perfectly fine to me. At least until when I first tried it. Run the program, and what happens?"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 10.2 Bugs - Human Errors\n",
- "The most common problems with your code are of your own doing. Sad, but true. What do we see when we try to run our crippled program?\n",
- "```Python\n",
- "---------------------------------------------------------------------------\n",
- "TypeError Traceback (most recent call last)\n",
- " in ()\n",
- " 8 # running the function\n",
- " 9 # remember what the backslash does\n",
- "---> 10 answer = menu(['A','B','C','D','E','F','H','I'],'Which letter is your favourite? ')\n",
- " 11 \n",
- " 12 print('You picked answer ' + str(answer + 1))\n",
- "\n",
- " in menu(list, question)\n",
- " 4 print(\") \" + entry)\n",
- " 5 \n",
- "----> 6 return input(question) - 1\n",
- " 7 \n",
- " 8 # running the function\n",
- "\n",
- "TypeError: unsupported operand type(s) for -: 'str' and 'int'\n",
- "```"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Say what? What Python is trying to tell you (but struggling to find a good word for it) is that you can't join a string of letters and a number into one string of text. Let's go through the error message and have a look at how it tells us that:\n",
- "* `--->` shows the lines where the error is detected. You can see that it first points out line 10 (the string) and then line 6 (the calculation where we subtract an integere from a string). Note that line 6 was in the function.\n",
- "* `TypeError: unsupported operand type(s) for -: 'str' and 'int'` tells you the error. In this case, it is a 'TypeError', where you tried to subtract incompatible variables"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "There are multiple file and code listings for a single error, because the error occurred with the interaction of two lines of code (e.g. when using a function, the error occurred on the line where the function was called, AND the line in the function where things went wrong).\n",
- "\n",
- "Now that we know what the problem is, how do we fix it. Well, the error message has isolated where the problem is, so we'll only concentrate on that bit of code.\n",
- "```Python\n",
- "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
- "'Which letter is your favourite? ')\n",
- "```\n",
- "This is a call to a function. The error occured in the function in the following line:\n",
- "```Python\n",
- " return input(question) - 1\n",
- "```\n",
- "`input` always returns a string, hence our problem. Let's change it to `eval(input())`, which, when you type in a number, it returns a number:\n",
- "```Python\n",
- " return eval(input(question)) - 1\n",
- "```\n",
- "Bug fixed!"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "## 10.3 Exceptions - Limitations of the Code\n",
- "OK, the program works when you do something normal. But what if you try something weird? Type in a letter (lets say, 'm') instead of a number? Whoops!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "def menu(list, question):\n",
- " for entry in list:\n",
- " print(1 + list.index(entry),end=\"\")\n",
- " print(\") \" + entry)\n",
- "\n",
- " return eval(input(question)) - 1\n",
- "\n",
- "# running the function\n",
- "# remember what the backslash does\n",
- "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
- "'Which letter is your favourite? ')\n",
- "\n",
- "print('You picked answer ' + str(answer + 1))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "An error occurs in line 10, and the other in line 6. What this is telling us is that when we called the menu function in line 10, an error occured in line 6 (where we take away 1). This makes sense if you know what the `input()` function does - I did a bit of reading and testing, and realised that if you type in a letter or word, it will assume that you are mentioning a variable! so in line 6, we are trying to take 1 away from the variable 'm', which doesn't exist. \n",
- "\n",
- "Have no clue on how to fix this? One of the best and easiest ways is to use the `try` and `except` operators. \n",
- "\n",
- "Here is an example of `try` being used in a program:\n",
- "```Python\n",
- "try:\n",
- " function(world,parameters)\n",
- "except:\n",
- " print(world.errormsg)\n",
- "```\n",
- "This is an example of a really messy bit of code that I was trying to fix. First, the code under `try:` is run. If there is an error, the compiler jumps to the except section and prints `world.errormsg`. The program doesn't stop right there and crash, it runs the code under `except:` then continues on. \n",
- "\n",
- "Lets try that where the error occured in our code (line 6). The menu function now is:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "def menu(list, question):\n",
- " for entry in list:\n",
- " print(1 + list.index(entry),end=\"\")\n",
- " print(\") \" + entry)\n",
- " try:\n",
- " return eval(input(question)) - 1\n",
- " except NameError:\n",
- " print(\"Enter a correct number\")\n",
- "\n",
- "# running the function\n",
- "# remember what the backslash does\n",
- "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
- "'Which letter is your favourite? ')\n",
- "\n",
- "print('You picked answer ' + str(answer + 1))"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Try entering a letter when you're asked for a number and see what happens. Dang. We fixed one problem, but now it has caused another problem further down the track. This happens all the time. (Sometimes you end up going around in circles, because your code is an absolute mess). Let's have a look at the error. \n",
- "\n",
- "What has happened this time is that the menu function has returned no value - it only printed an error message. When, at the end of the program, we try to print the returned value plus 1, what is the returned value? There is no returned value? So what is 1 + ... well, we have no clue what we are adding 1 to! \n",
- "\n",
- "We could just return any old number, but that would be lying. What we really should to is rewrite the program to cope with this exception. With what? `try` and `except`!"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "def menu(list, question):\n",
- " for entry in list:\n",
- " print(1 + list.index(entry),end=\"\")\n",
- " print(\") \" + entry)\n",
- " try:\n",
- " return eval(input(question)) - 1\n",
- " except NameError:\n",
- " print(\"Enter a correct number\")\n",
- "\n",
- "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
- "'Which letter is your favourite? ')\n",
- "try:\n",
- " print(\"You picked answer\", (answer + 1))\n",
- " # you can put stuff after a comma in the 'print' statement,\n",
- " # and it will continue as if you had typed in 'print' again\n",
- "except:\n",
- " print(\"\\nIncorrect answer.\")\n",
- " # the '\\n' is for formatting reasons. Try without it and see."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Problem solved again.\n",
- "## 10.4 Endless Errors\n",
- "The approach that we used above is not recomended. Why? Because apart from the error that we know can happen, `except:` catches every other error too. What if this means we never see an error that could cause problems down the track? If `except:` catches every error under the sun, we have no hope of controlling what errors we deal with, and the other ones that we want to see, because so far we haven't dealt with them. We also have little hope of dealing with more than one type of error in the same block of code. What should one do, when all is hopeless? Here is an example of code with such a situation:"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "print(\"Subtraction program, v0.0.1 (beta)\")\n",
- "a = eval(input('Enter a number to subtract from > '))\n",
- "b = eval(input('Enter the number to subtract > '))\n",
- "print(a - b)"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Ok, you enter your two numbers and it works. Enter a letter, and it gives you a `NameError`. Lets rewrite the code to deal with a `NameError` only. We'll put the program in a loop, so it restarts if an error occurs (using `continue`, which starts the loop from the top again, and `break`, which leaves the loop):"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "print(\"Subtraction program, v0.0.2 (beta)\")\n",
- "loop = 1\n",
- "while loop == 1:\n",
- " try:\n",
- " a = eval(input('Enter a number to subtract from > '))\n",
- " b = eval(input('Enter the number to subtract > '))\n",
- " except NameError:\n",
- " print(\"\\nYou cannot subtract a letter\")\n",
- " continue\n",
- " print(a - b)\n",
- " try:\n",
- " loop = eval(input('Press 1 to try again > '))\n",
- " except NameError:\n",
- " loop = 0"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "Here, we restarted the loop if you typed in something wrong. In line 12 we assumed you wanted to quit the program if you didn't press 1, so we quit the program. \n",
- "\n",
- "But there are still problems. If we leave something blank, or type in an unusual character like ! or ;, the program gives us a `SyntaxError`. Let's deal with this. When we are asking for the numbers to subtract, we will give a different error message. When we ask to press 1, we will again assume the user wants to quit."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "metadata": {},
- "outputs": [],
- "source": [
- "print(\"Subtraction program, v0.0.2 (beta)\")\n",
- "loop = 1\n",
- "while loop == 1:\n",
- " try:\n",
- " a = eval(input('Enter a number to subtract from > '))\n",
- " b = eval(input('Enter the number to subtract > '))\n",
- " except NameError:\n",
- " print(\"\\nYou cannot subtract a letter\")\n",
- " continue\n",
- " except SyntaxError:\n",
- " print(\"\\nPlease enter a number only.\")\n",
- " continue\n",
- " print(a - b)\n",
- " try:\n",
- " loop = eval(input('Press 1 to try again > '))\n",
- " except (NameError,SyntaxError):\n",
- " loop = 0"
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "As you can see, you can have multiple except uses, each dealing with a different problem. You can also have one except to deal with multiple exceptions, by putting them inside parentheses and separating them with commas. \n",
- "\n",
- "Now we have a program that is very difficult, to crash by an end user. As a final challenge, see if you can crash it. There is one way I have thought of - if you read the chapter on Human Error carefully, you might know what it is.\n",
- "\n",
- "## 10.5 Conclusion, Sweet Conclusion\n",
- "There you go! The final lesson on Python! Finally we are finished."
- ]
- },
- {
- "cell_type": "markdown",
- "metadata": {},
- "source": [
- "< [File I/O](PythonIntroCh9.ipynb) | [Contents](PythonIntro.ipynb) >"
- ]
- }
- ],
- "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.7.9"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 2
-}
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "< [File I/O](PythonIntroCh9.ipynb) | [Contents](PythonIntro.ipynb) >"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "# 10. Exception Handling\n",
+ "## 10.1 Introduction\n",
+ "If you haven't seen them before, you're not trying hard enough. What are they? Errors. Exceptions. Problems. Know what I'm talking about? I got it with this program: "
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def menu(list, question):\n",
+ " for entry in list:\n",
+ " print(1 + list.index(entry),end=\"\")\n",
+ " print(\") \" + entry)\n",
+ "\n",
+ " return input(question) - 1\n",
+ "\n",
+ "# running the function\n",
+ "# remember what the backslash does\n",
+ "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
+ "'Which letter is your favourite? ')\n",
+ "\n",
+ "print('You picked answer ' + str(answer + 1))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "This is just an example of the menu program we made earlier. Appears perfectly fine to me. At least until when I first tried it. Run the program, and what happens?"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 10.2 Bugs - Human Errors\n",
+ "The most common problems with your code are of your own doing. Sad, but true. What do we see when we try to run our crippled program?\n",
+ "```Python\n",
+ "---------------------------------------------------------------------------\n",
+ "TypeError Traceback (most recent call last)\n",
+ " in ()\n",
+ " 8 # running the function\n",
+ " 9 # remember what the backslash does\n",
+ "---> 10 answer = menu(['A','B','C','D','E','F','H','I'],'Which letter is your favourite? ')\n",
+ " 11 \n",
+ " 12 print('You picked answer ' + str(answer + 1))\n",
+ "\n",
+ " in menu(list, question)\n",
+ " 4 print(\") \" + entry)\n",
+ " 5 \n",
+ "----> 6 return input(question) - 1\n",
+ " 7 \n",
+ " 8 # running the function\n",
+ "\n",
+ "TypeError: unsupported operand type(s) for -: 'str' and 'int'\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Say what? What Python is trying to tell you (but struggling to find a good word for it) is that you can't join a string of letters and a number into one string of text. Let's go through the error message and have a look at how it tells us that:\n",
+ "* `--->` shows the lines where the error is detected. You can see that it first points out line 10 (the string) and then line 6 (the calculation where we subtract an integer from a string). Note that line 6 was in the function.\n",
+ "* `TypeError: unsupported operand type(s) for -: 'str' and 'int'` tells you the error. In this case, it is a 'TypeError', where you tried to subtract incompatible variables"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "There are multiple files and code listings for a single error, because the error occurred with the interaction of two lines of code (e.g. when using a function, the error occurred on the line where the function was called, AND the line in the function where things went wrong).\n",
+ "\n",
+ "Now that we know what the problem is, how do we fix it? Well, the error message has isolated where the problem is, so we'll only concentrate on that bit of code.\n",
+ "```Python\n",
+ "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
+ "'Which letter is your favourite? ')\n",
+ "```\n",
+ "This is a call to a function. The error occurred in the function in the following line:\n",
+ "```Python\n",
+ " return input(question) - 1\n",
+ "```\n",
+ "`input` always returns a string, hence our problem. Let's change it to `eval(input())`, which, when you type in a number, it returns a number:\n",
+ "```Python\n",
+ " return eval(input(question)) - 1\n",
+ "```\n",
+ "Bug fixed!"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "## 10.3 Exceptions - Limitations of the Code\n",
+ "OK, the program works when you do something normal. But what if you try something weird? Type in a letter (let's say, 'm') instead of a number? Whoops!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def menu(list, question):\n",
+ " for entry in list:\n",
+ " print(1 + list.index(entry),end=\"\")\n",
+ " print(\") \" + entry)\n",
+ "\n",
+ " return eval(input(question)) - 1\n",
+ "\n",
+ "# running the function\n",
+ "# remember what the backslash does\n",
+ "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
+ "'Which letter is your favourite? ')\n",
+ "\n",
+ "print('You picked answer ' + str(answer + 1))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "An error occurs in line 10, and another in line 6. What this is telling us is that when we called the menu function in line 10, an error occurred in line 6 (where we take away 1). This makes sense if you know what the `input()` function does - I did a bit of reading and testing, and realised that if you type in a letter or word, it will assume that you are mentioning a variable! So in line 6, we are trying to take 1 away from the variable 'm', which doesn't exist. \n",
+ "\n",
+ "Have no clue on how to fix this? One of the best and easiest ways is to use the `try` and `except` operators. \n",
+ "\n",
+ "Here is an example of `try` being used in a program:\n",
+ "```Python\n",
+ "try:\n",
+ " function(world,parameters)\n",
+ "except:\n",
+ " print(world.errormsg)\n",
+ "```\n",
+ "This is an example of a really messy bit of code that I was trying to fix. First, the code under `try:` is run. If there is an error, the compiler jumps to the except section and prints `world.errormsg`. The program doesn't stop right there and crash; it runs the code under `except:` then continues on. \n",
+ "\n",
+ "Let's try that where the error occurred in our code (line 6). The menu function now is:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def menu(list, question):\n",
+ " for entry in list:\n",
+ " print(1 + list.index(entry),end=\"\")\n",
+ " print(\") \" + entry)\n",
+ " try:\n",
+ " return eval(input(question)) - 1\n",
+ " except NameError:\n",
+ " print(\"Enter a correct number\")\n",
+ "\n",
+ "# running the function\n",
+ "# remember what the backslash does\n",
+ "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
+ "'Which letter is your favourite? ')\n",
+ "\n",
+ "print('You picked answer ' + str(answer + 1))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Try entering a letter when you're asked for a number and see what happens. Dang. We fixed one problem, but now it has caused another problem further down the track. This happens all the time. (Sometimes you end up going around in circles, because your code is an absolute mess). Let's have a look at the error. \n",
+ "\n",
+ "What has happened this time is that the menu function has returned no value - it only printed an error message. When, at the end of the program, we try to print the returned value plus 1, what is the returned value? There is no returned value? So what is 1 + ... well, we have no clue what we are adding 1 to! \n",
+ "\n",
+ "We could just return any old number, but that would be lying. What we really should to is rewrite the program to cope with this exception. With what? `try` and `except`!"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "def menu(list, question):\n",
+ " for entry in list:\n",
+ " print(1 + list.index(entry),end=\"\")\n",
+ " print(\") \" + entry)\n",
+ " try:\n",
+ " return eval(input(question)) - 1\n",
+ " except NameError:\n",
+ " print(\"Enter a correct number\")\n",
+ "\n",
+ "answer = menu(['A','B','C','D','E','F','H','I'],\\\n",
+ "'Which letter is your favourite? ')\n",
+ "try:\n",
+ " print(\"You picked answer\", (answer + 1))\n",
+ " # you can put stuff after a comma in the 'print' statement,\n",
+ " # and it will continue as if you had typed in 'print' again\n",
+ "except:\n",
+ " print(\"\\nIncorrect answer.\")\n",
+ " # the '\\n' is for formatting reasons. Try without it and see."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Problem solved again.\n",
+ "## 10.4 Endless Errors\n",
+ "The approach that we used above is not recommended. Why? Because apart from the error that we know can happen, `except:` catches every other error too. What if this means we never see an error that could cause problems down the track? If `except:` catches every error under the sun, we have no hope of controlling what errors we deal with, and the other ones that we want to see, because so far, we haven't dealt with them. We also have little hope of dealing with more than one type of error in the same block of code. What should one do, when all is hopeless? Here is an example of code with such a situation:"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"Subtraction program, v0.0.1 (beta)\")\n",
+ "a = eval(input('Enter a number to subtract from > '))\n",
+ "b = eval(input('Enter the number to subtract > '))\n",
+ "print(a - b)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Ok, you enter your two numbers, and it works. Enter a letter, and it gives you a `NameError`. Lets rewrite the code to deal with a `NameError` only. We'll put the program in a loop, so it restarts if an error occurs (using `continue`, which starts the loop from the top again, and `break`, which leaves the loop):"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"Subtraction program, v0.0.2 (beta)\")\n",
+ "loop = 1\n",
+ "while loop == 1:\n",
+ " try:\n",
+ " a = eval(input('Enter a number to subtract from > '))\n",
+ " b = eval(input('Enter the number to subtract > '))\n",
+ " except NameError:\n",
+ " print(\"\\nYou cannot subtract a letter\")\n",
+ " continue\n",
+ " print(a - b)\n",
+ " try:\n",
+ " loop = eval(input('Press 1 to try again > '))\n",
+ " except NameError:\n",
+ " loop = 0"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "Here, we restarted the loop if you typed in something wrong. In line 12 we assumed you wanted to quit the program if you didn't press 1, so we quit the program. \n",
+ "\n",
+ "But there are still problems. If we leave something blank, or type in an unusual character like `!` or `;`, the program gives us a `SyntaxError`. Let's deal with this. When we are asking for the numbers to subtract, we will give a different error message. When we ask to press 1, we will again assume the user wants to quit."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"Subtraction program, v0.0.2 (beta)\")\n",
+ "loop = 1\n",
+ "while loop == 1:\n",
+ " try:\n",
+ " a = eval(input('Enter a number to subtract from > '))\n",
+ " b = eval(input('Enter the number to subtract > '))\n",
+ " except NameError:\n",
+ " print(\"\\nYou cannot subtract a letter\")\n",
+ " continue\n",
+ " except SyntaxError:\n",
+ " print(\"\\nPlease enter a number only.\")\n",
+ " continue\n",
+ " print(a - b)\n",
+ " try:\n",
+ " loop = eval(input('Press 1 to try again > '))\n",
+ " except (NameError,SyntaxError):\n",
+ " loop = 0"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "As you can see, you can have multiple except uses, each dealing with a different problem. You can also have one except to deal with multiple exceptions, by putting them inside parentheses and separating them with commas. \n",
+ "\n",
+ "Now we have a program that is very difficult, to crash for an end user. As a final challenge, see if you can crash it. There is one way I have thought of - if you read the chapter on Human Error carefully, you might know what it is.\n",
+ "\n",
+ "## 10.5 Conclusion, Sweet Conclusion\n",
+ "There you go! The final lesson on Python! Finally, we are finished."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "metadata": {},
+ "source": [
+ "< [File I/O](PythonIntroCh9.ipynb) | [Contents](PythonIntro.ipynb) >"
+ ]
+ }
+ ],
+ "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.7.9"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 2
+}
diff --git a/PythonIntroCh2.ipynb b/PythonIntroCh2.ipynb
index d4008c6..9ab248f 100644
--- a/PythonIntroCh2.ipynb
+++ b/PythonIntroCh2.ipynb
@@ -15,10 +15,10 @@
"## 2.1 Introduction\n",
"Well, we can make one-liner programs. So What? You want to send programs to other people, so that they can use them, without knowing how to write them.\n",
"## 2.2 Writing scripts\n",
- "Writing programs in Python to a file is VERY easy. Python programs are simply text documents - you can open them up in notepad, and have a look at them, just like that.\n",
- "In practice, however, you will use a so called __[Integrated Development Environment (IDE)](https://en.wikipedia.org/wiki/Integrated_development_environment)__ to develop your scripts.\n",
+ "Writing programs in Python to a file is VERY easy. Python programs are simply text documents - you can open them up in Notepad and have a look at them, just like that.\n",
+ "In practice, however, you will use a so-called __[Integrated Development Environment (IDE)](https://en.wikipedia.org/wiki/Integrated_development_environment)__ to develop your scripts.\n",
"\n",
- "In this tutorial we'll use the Jupyter Notebook interactive fields as an IDE and simulate how we use pythons scripts in files.\n",
+ "In this tutorial, we'll use the Jupyter Notebook interactive fields as an IDE and simulate how we use Python scripts in files.\n",
"\n",
"Have a look at the program (`mary.py`) below:"
]
@@ -40,9 +40,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "If you run the script (` + `) it will execute lines 1 to 5 after each other. In an IDE there's always a screen where you can type the code with syntax highlighting (like in the cells of this Jupyter Notebook), a window where you can see the output and a button to run the script. The scripts are saved as `.py` files. These can be run from your command line - Open the terminal window, go to the folder and then type `Python mary.py`. Your program will now execute in the command line.\n",
+ "If you run the script (Shift + Return), it will execute lines 1 to 5 after each other. In an IDE, there's always a screen where you can type the code with syntax highlighting (like in the cells of this Jupyter Notebook), a window where you can see the output and a button to run the script. The scripts are saved as `.py` files. These can be run from your command line - Open the terminal window, go to the folder and then type `Python mary.py`. Your program will now execute in the command line.\n",
"\n",
- "In line 4 `end = \" \"` inserts a space instead of a new line at the end of the `print` operator."
+ "In line 4, `end = \" \"` inserts a space instead of a new line at the end of the `print` operator."
]
},
{
@@ -50,7 +50,7 @@
"metadata": {},
"source": [
"## 2.3 Variables\n",
- "Now let's start introducing variables. Variables store a value, that can be looked at or changed at a later time. Let's make a program that uses variables:"
+ "Now let's start introducing variables. Variables store a value that can be looked at or changed at a later time. Let's make a program that uses variables:"
]
},
{
@@ -96,7 +96,7 @@
"metadata": {},
"source": [
"## 2.5 Strings\n",
- "As you can see, variables store values, for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text. A variable that holds text is called a string. Try this program:"
+ "As you can see, variables store values for use at a later time. You can change them at any time. You can put in more than numbers, though. Variables can hold things like text. A variable that holds text is called a string. Try this program:"
]
},
{
@@ -120,7 +120,7 @@
"source": [
"As you see, the variables above were holding text. Variable names can also be longer than one letter - here, we had `word1`, `word2`, and `word3`. As you can also see, strings can be added together to make longer words or sentences. However, it doesn't add spaces in between the words - hence me putting in the `\" \"` things (there is one space between those).\n",
"\n",
- "Often we need to manipulate strings. For example if we want to edit file names or make selections from text. Strings are similar to `lists` that you will learn later. So similar operations (called *list slicing*) apply to strings.\n",
+ "Often, we need to manipulate strings. For example, if we want to edit file names or make selections from text. Strings are similar to `lists` that you will learn later. So similar operations (called *list slicing*) apply to strings.\n",
"\n",
"Try the following code and explain what it does:"
]
@@ -291,7 +291,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "So you can easily insert variables at the places of the accolades (`{}`). They will be substituted in the same order of the variables in `.format()`"
+ "So you can easily insert variables at the places of the accolades (`{}`). They will be substituted in the same order as the variables in `.format()`"
]
},
{
@@ -314,8 +314,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Besides *list slicing* there are also other operations that we can apply to strings.\n",
- "We can count the number of occurences of a specific character in a string:"
+ "Besides *list slicing*, there are also other operations that we can apply to strings.\n",
+ "We can count the number of occurrences of a specific character in a string:"
]
},
{
@@ -331,7 +331,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "We can also find the position of character:"
+ "We can also find the position of a character:"
]
},
{
@@ -357,9 +357,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "`rfind` returns the lasts occurance of a string. So in `sometext` we have the word \"you\" twice. `rfind` returns `17` meaning that the last time that it found \"you\" is starting at position 17 (counting from 0).\n",
+ "`rfind` returns the lasts occurance of a string. So in `sometext` we have the word \"you\" twice. `rfind` returns `17`, meaning that the last time that it found \"you\" is starting at position 17 (counting from 0).\n",
"\n",
- "There are a few other useful string operations. Run the code below and will be obvious what it does:"
+ "There are a few other useful string operations. Run the code below, and it will be obvious what it does:"
]
},
{
@@ -386,7 +386,7 @@
"\n",
"`\\n` jumps to a new line\n",
"\n",
- "`\\` is an escape character. You can put it before another character that has a meaning in the code and is not considered a string. This is often used to have strings with backslashes for file names on Windows (e.g. `\"C:\\\\folder\\\\filename.txt\"`). Because `\\` is already an escape character we need to use it twice to escape the escape character!\n",
+ "`\\` is an escape character. You can put it before another character that has a meaning in the code and is not considered a string. This is often used to have strings with backslashes for file names on Windows (e.g. `\"C:\\\\folder\\\\filename.txt\"`). Because `\\` is already an escape character, we need to use it twice to escape the escape character!\n",
"\n",
"Examples:"
]
@@ -408,7 +408,7 @@
"metadata": {},
"source": [
"## 2.6 Conclusion\n",
- "Well done! We now understand longer programs, and know the use of variables. We can also manipulate strings. Next lesson, we look at loops, what they are, and how to use them."
+ "Well done! We now understand longer programs and know the use of variables. We can also manipulate strings. Next lesson, we will look at loops, what they are, and how to use them."
]
},
{
diff --git a/PythonIntroCh3.ipynb b/PythonIntroCh3.ipynb
index 3de26ce..5cc90e5 100644
--- a/PythonIntroCh3.ipynb
+++ b/PythonIntroCh3.ipynb
@@ -37,7 +37,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "How does this program work? Lets go through it in English:\n",
+ "How does this program work? Let's go through it in English:\n",
"```\n",
"'a' now equals 0\n",
"As long as 'a' is less than 10, do the following:\n",
@@ -110,7 +110,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "So in short, try to think of it that way when you write 'while' loops. This is how you write them, by the way (syntax):\n",
+ "So, in short, try to think of it that way when you write 'while' loops. This is how you write them, by the way (syntax):\n",
"```\n",
"while {condition that the loop continues}:\n",
" {what to do in the loop}\n",
@@ -145,9 +145,9 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "## 3.3 Boolean Expressions (Boolen... what?!?)\n",
- "What do you type in the area marked `{conditions that the loop continues}`? The answer is a boolean expression. \n",
- "What? A forgotten concept for the non-math people here. Never mind, boolean expression just means a question that can be answered with a TRUE or FALSE response. For example, if you wanted to say your age is the same as the person next to you, you would type:\n",
+ "## 3.3 Boolean Expressions (Boolean... what?!?)\n",
+ "What do you type in the area marked `{conditions that the loop continues}`? The answer is a Boolean expression. \n",
+ "What? A forgotten concept for the non-math people here. Never mind, a Boolean expression just means a question that can be answered with a TRUE or FALSE response. For example, if you wanted to say your age is the same as the person next to you, you would type:\n",
"\n",
"`My age == the age of the person next to me`\n",
"\n",
@@ -169,9 +169,7 @@
"| `!=` | Not equal to |\n",
"| `==` | Equal to |\n",
"\n",
- "Don't get `=` and `==` mixed up - the `=` operator makes what is on the left equal to what is on the right. the `==` operator says whether the thing on the left is the same as what is on the right, and returns True or False.\n",
- "\n",
- "\n"
+ "Don't get `=` and `==` mixed up - the `=` operator makes what is on the left equal to what is on the right. The `==` operator says whether the thing on the left is the same as what is on the right, and returns True or False."
]
},
{
@@ -180,8 +178,8 @@
"source": [
"## 3.4 Conditional Statements\n",
"OK! We've (hopefully) covered 'while' loops. Now let's look at something a little different - conditionals. \n",
- "Conditionals are where a section of code is only run if certain conditions are met. This is similar to the 'while' loop you just wrote, which only runs when x doesn't equal 0. However, Conditionals are only run once. The most common conditional in any program language, is the 'if' statement. Here is how it works: \n",
- "```\n",
+ "Conditionals are where a section of code is only run if certain conditions are met. This is similar to the 'while' loop you just wrote, which only runs when x doesn't equal 0. However, Conditionals are only run once. The most common conditional in any programming language is the 'if' statement. Here is how it works: \n",
+ "```python\n",
"if {conditions to be met}:\n",
" {do this}\n",
" {and this}\n",
@@ -254,7 +252,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "`a` is not greater than five, therefore what is under `else` is done.\n",
+ "`a` is not greater than five, therefore, what is under `else` is done.\n",
"\n",
"`elif` is just a shortened way of saying `else if`. When the `if` statement fails to be true, `elif` will do what is under it IF the conditions are met. For example:"
]
@@ -277,7 +275,7 @@
"metadata": {},
"source": [
"The `if` statement, along with `else` and `elif` follow this form:\n",
- "```Python\n",
+ "```python\n",
"if {conditions}:\n",
" {run this code}\n",
"elif {conditions}:\n",
@@ -305,7 +303,7 @@
"metadata": {},
"source": [
"## 3.6 Indentation\n",
- "One other point is that the code to be executed if the conditions are met, MUST BE INDENTED. That means that if you want to loop the next five lines with a `while` loop, you must put a set number of spaces at the beginning of each of the next five lines. This is good programming practice in any language, but Python requires that you do it. Here is an example of both of the above points:"
+ "One other point is that the code to be executed if the conditions are met MUST BE INDENTED. That means that if you want to loop the next five lines with a `while` loop, you must put a set number of spaces at the beginning of each of the next five lines. This is good programming practice in any language, but Python requires that you do it. Here is an example of both of the above points:"
]
},
{
@@ -338,7 +336,7 @@
"metadata": {},
"source": [
"Notice the three levels of indents there:\n",
- "1. Each line in the first level starts with no spaces. It is the main program, and will always execute.\n",
+ "1. Each line in the first level starts with no spaces. It is the main program and will always execute.\n",
"2. Each line in the second level starts with four spaces. When there is an `if` or loop on the first level, everything on the second level after that will be looped/'ifed', until a new line starts back on the first level again.\n",
"3.\tEach line in the third level starts with eight spaces. When there is an `if` or loop on the second level, everything on the third level after that will be looped/'ifed', until a new line starts back on the second level again.\n",
"4.\tThis goes on infinitely, until the person writing the program has an internal brain explosion, and cannot understand anything he/she has written."
@@ -350,7 +348,7 @@
"source": [
"There is another loop, called the 'for' loop, but we will cover that in a later lesson, after we have learnt about lists.\n",
"## 3.7 Conclusion\n",
- "And that is lesson 3! In lesson 4, we get into user interaction, and writing programs that actually serve a purpose. Can't wait!"
+ "And that is lesson 3! In lesson 4, we get into user interaction and writing programs that actually serve a purpose. Can't wait!"
]
},
{
diff --git a/PythonIntroCh4.ipynb b/PythonIntroCh4.ipynb
index 7d20677..4125d4f 100644
--- a/PythonIntroCh4.ipynb
+++ b/PythonIntroCh4.ipynb
@@ -13,18 +13,18 @@
"source": [
"# 4. Functions\n",
"## 4.1 Introduction\n",
- "Last lesson I said that we would delve into purposeful programming. That involves user input, and user input requires a thing called functions.\n",
+ "Last lesson, I said that we would delve into purposeful programming. That involves user input, and user input requires a thing called functions.\n",
"\n",
- "What are functions? Well, in effect, functions are little self-contained programs that perform a specific task, which you can incorporate into your own, larger programs. After you have created a function, you can use it at any time, in any place. This saves you the time and effort of having to retell the computer what to do every time it does a common task, for example getting the user to type something in.\n",
+ "What are functions? Well, in effect, functions are little self-contained programs that perform a specific task, which you can incorporate into your own, larger programs. After you have created a function, you can use it at any time, in any place. This saves you the time and effort of having to retell the computer what to do every time it does a common task, for example, getting the user to type something in.\n",
"\n",
"## 4.2 Using a Function\n",
- "Python has lots of pre-made functions, that you can use right now, simply by 'calling' them. 'Calling' a function involves you giving a function input, and it will return a value (like a variable would) as output. Don't understand? Here is the general form that calling a function takes: \n",
+ "Python has lots of pre-made functions that you can use right now, simply by 'calling' them. 'Calling' a function involves you giving a function input, and it will return a value (like a variable would) as output. Don't understand? Here is the general form that calling a function takes: \n",
"`function_name(parameters)`\n",
"\n",
"See? Easy.\n",
"\n",
"- `Function_name` identifies which function it is you want to use (You'd figure...). For example, the function `raw_input`, which will be the first function that we will use.\n",
- "- `Parameters` are the values you pass to the function to tell it what is should do, and how to do it... for example, if a function multiplied any given number by five, the stuff in parameters tells the function which number it should multiply by five. Put the number 70 into parameters, and the function will do 70 x 5."
+ "- `Parameters` are the values you pass to the function to tell it what it should do, and how to do it... for example, if a function multiplied any given number by five, the stuff in parameters tells the function which number it should multiply by five. Put the number 70 into the parameters, and the function will do 70 x 5."
]
},
{
@@ -32,7 +32,7 @@
"metadata": {},
"source": [
"## 4.3 Parameters and Returned Values - Communicating with Functions\n",
- "Well, that's all well and good that the program can multiply a number by five, but what does it have to show for it? A warm fuzzy feeling? Your program needs to see the results of what happened, to see what 70 x 5 is, or to see if there is a problem somewhere (like you gave it a letter instead of a number). So how does a function show what is does?\n",
+ "Well, that's all well and good that the program can multiply a number by five, but what does it have to show for it? A warm fuzzy feeling? Your program needs to see the results of what happened, to see what 70 x 5 is, or to see if there is a problem somewhere (like you gave it a letter instead of a number). So how does a function show what it does?\n",
"\n",
"Well, in effect, when a computer runs a function, it doesn't actually see the function name, but the result of what the function did. Variables do the exact same thing - the computer doesn't see the variable name, it sees the value that the variable holds. Let's call this program that multiplied any number by five, `multiply()`. You put the number you want multiplied in the brackets. So if you typed this:\n",
"\n",
@@ -77,7 +77,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Remember, a variable is just a stored value. To the computer, the variable `a` doesn't look like `a` - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running."
+ "Remember, a variable is just a stored value. To the computer, the variable `a` doesn't look like `a` - it looks like the value that is stored inside it. Functions are similar to the main program (that is, the program that is running the function), they look like the value of what they give in return of running."
]
},
{
@@ -85,9 +85,9 @@
"metadata": {},
"source": [
"## 4.4 A Calculator Program\n",
- "Let's write another program, that will act as a calculator. This time it will do something more adventurous than what we have done before. There will be a menu, that will ask you whether you want to multiply two numbers together, add two numbers together, divide one number by another, or subtract one number from another. Only problem - the `input` function returns what you type in as a string - we want the number 1, not the letter 1 (and yes, in Python, there is a difference).\n",
+ "Let's write another program that will act as a calculator. This time, it will do something more adventurous than what we have done before. There will be a menu that will ask you whether you want to multiply two numbers together, add two numbers together, divide one number by another, or subtract one number from another. Only problem - the `input` function returns what you type in as a string - we want the number 1, not the letter 1 (and yes, in Python, there is a difference).\n",
"\n",
- "Luckily, somebody wrote the function `eval`, which returns what you typed in, to the main program - but this time, it puts it in as a number. If you type an integer (a whole number), what comes out of input is an integer. And if you put that integer into a variable, the variable will be an integer-type variable, which means you can add and subtract, etc."
+ "Luckily, somebody wrote the function `eval`, which returns what you typed in, to the main program - but this time, it puts it in as a number. If you type an integer (a whole number), what comes out of the input is an integer. And if you put that integer into a variable, the variable will be an integer-type variable, which means you can add and subtract, etc."
]
},
{
@@ -106,7 +106,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "Now, let's design this calculator properly. We want a menu that is returned to every time you finish adding, subtracting, etc. In other words, to loop (HINT!!!) while (BIG HINT!!!) you tell it the program should still run.\n",
+ "Now, let's design this calculator properly. We want a menu that is returned to every time you finish adding, subtracting, etc. In other words, to loop (HINT!!!) while (BIG HINT!!!), you tell it the program should still run.\n",
"We want it to do an option in the menu if you type in that number. That involves you typing in a number (a.k.a. input) and an `if` loop. \n",
"Let's write it out in understandable English first (pseudocode):\n",
"\n",
@@ -220,8 +220,8 @@
"\n",
"This is how the `def` operator works:\n",
"\n",
- "```\n",
- "def function_name(parameter_1,parameter_2):\n",
+ "```python\n",
+ "def function_name(parameter_1, parameter_2):\n",
" {this is the code in the function}\n",
" {more code}\n",
" {more code}\n",
@@ -237,22 +237,22 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "`function_name` is the name of the function. You write the code that is in the function below that line, and have it indented. (We will worry about `parameter_1` and `parameter_2` later, for now imagine there is nothing between the parentheses.\n",
+ "`function_name` is the name of the function. You write the code that is in the function below that line, and have it indented. (We will worry about `parameter_1` and `parameter_2` later, for now, imagine there is nothing between the parentheses.\n",
"\n",
- "Functions run completely independent of the main program. Remember when I said that when the computer comes to a function, it doesn't see the function, but a value, that the function returns? Here's the quote:\n",
+ "Functions run completely independent of the main program. Remember when I said that when the computer comes to a function, it doesn't see the function, but a value that the function returns? Here's the quote:\n",
"\n",
- "To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar - to the main program (that is, the program that is running the function), they look like the value of what they give in return of running."
+ "To the computer, the variable 'a' doesn't look like 'a' - it looks like the value that is stored inside it. Functions are similar to the main program (that is, the program that is running the function), they look like the value of what they give in return of running."
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
- "A function is like a miniature program that some parameters are given to - it then runs itself, and then returns a value. Your main program sees only the returned value. If that function flew to the moon and back, and then at the end had:\n",
+ "A function is like a miniature program that takes some parameters are given to it, then runs itself, and then returns a value. Your main program sees only the returned value. If that function flew to the moon and back, and then at the end had:\n",
"\n",
"`return \"hello\"`\n",
"\n",
- "then all your program would see is the string `\"hello\"`, where the name of the function was. It would have no idea what else the program did.\n",
+ "Then all your program would see is the string `\"hello\"`, where the name of the function was. It would have no idea what else the program did.\n",
"\n",
"Because it is a separate program, a function doesn't see any of the variables that are in your main program, and your main program doesn't see any of the variables that are in a function. For example, here is a function that prints the words `\"hello\"` onscreen, and then returns the number `'1234'` to the main program:"
]
@@ -277,7 +277,7 @@
"metadata": {},
"source": [
"So what happened?\n",
- "1.\twhen `def hello()` was run, a function called `hello` was created\n",
+ "1.\tWhen `def hello()` was run, a function called `hello` was created\n",
"2.\tWhen the line `print(hello())` was run, the function `hello` was executed (The code inside it was run)\n",
"3.\tThe function `hello` printed `\"hello\"` onscreen, then returned the number `1234` back to the main program\n",
"4.\tThe main program now sees the line as `print(\"1234\")` and as a result, printed `1234`"
@@ -294,17 +294,18 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "## 4.6 Passing Parameters to functions\n",
+ "## 4.6 Passing Parameters to Functions\n",
"There is one more thing we will cover in this (monstrously huge) lesson - passing parameters to a function. Think back to how we defined functions: \n",
- "```\n",
- "def function_name(parameter_1,parameter_2):\n",
+ "\n",
+ "```python\n",
+ "def function_name(parameter_1, parameter_2):\n",
" {this is the code in the function}\n",
" {more code}\n",
" {more code}\n",
" return {value (e.g. text or number) to return to the main program}\n",
"```\n",
"\n",
- "Where `parameter_1` and `parameter_2` are (between the parentheses), you put the names of variables that you want to put the parameters into. Put as many as you need, just have them seperated by commas. When you run a function, the first value you put inside the parentheses would go into the variable where `parameter_1` is. The second one (after the first comma) would go to the variable where `parameter_2` is. This goes on for however many parameters there are in the function (from zero, to the sky). For example:"
+ "Where `parameter_1` and `parameter_2` are (between the parentheses), you put the names of variables that you want to put the parameters into. Put as many as you need, just have them separated by commas. When you run a function, the first value you put inside the parentheses goes into the variable where `parameter_1` is. The second one (after the first comma) would go to the variable where `parameter_2` is. This goes on for however many parameters there are in the function (from zero to the sky). For example:"
]
},
{
@@ -322,7 +323,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "When you run the function above, you would type in something like this: `funnyfunction(\"meat\",\"eater\",\"man\")`. The first value (that is, \"meat\") would be put into the variable called first_word. The second value inside the brackets (that is, \"eater\") would be put into the variable called second_word, and so on. This is how values are passed from the main program to functions - inside the parentheses, after the function name.\n",
+ "When you run the function above, you would type in something like this: `funnyfunction(\"meat\", \"eater\", \"man\")`. The first value (that is, \"meat\") would be put into the variable called first_word. The second value inside the brackets (that is, \"eater\") would be put into the variable called second_word, and so on. This is how values are passed from the main program to functions - inside the parentheses, after the function name.\n",
"\n",
"Add a new line to the script above that invokes the function."
]
@@ -332,9 +333,9 @@
"metadata": {},
"source": [
"## 4.7 A Final Program\n",
- "Think back to that calculator program. Did it look a bit messy to you? I think it did, so let's re-write it, with functions.\n",
+ "Think back to that calculator program. Did it look a bit messy to you? I think it did, so let's re-write it with functions.\n",
"\n",
- "To design - First we will define all the functions we are going to use with the `def` operator (still remember what an operator is ;) ). Then we will have the main program, with all that messy code replaced with nice, neat functions. This will make it so much easier to look at again in the future."
+ "To design - First, we will define all the functions we are going to use with the `def` operator (still remember what an operator is ;) ). Then we will have the main program, with all that messy code replaced with nice, neat functions. This will make it so much easier to look at again in the future."
]
},
{
@@ -404,7 +405,7 @@
"source": [
"The initial program had 34 lines of code. The new one actually had 35 lines of code! It is a little longer, but if you look at it the right way, it is actually simpler.\n",
"\n",
- "You defined all your functions at the top. This really isn't part of your main program - they are just lots of little programs that you will call upon later. You could even re-use these in another program if you needed them, and didn't want to tell the computer how to add and subtract again.\n",
+ "You defined all your functions at the top. This really isn't part of your main program - they are just lots of little programs that you will call upon later. You could even re-use these in another program if you needed them and didn't want to tell the computer how to add and subtract again.\n",
"\n",
"If you look at the main part of the program (between the line `loop = 1` and `print(\"Thank you for...\")`), it is only 15 lines of code. That means that if you wanted to write this program differently, you would only have to write 15 or so lines, as opposed to the 34 lines you would normally have to without functions."
]
@@ -414,27 +415,27 @@
"metadata": {},
"source": [
"## 4.8 Tricky Ways You Can Pass Parameters\n",
- "Finally, as a bit of an interlude, I will explain what the line `add(eval(input(\"Add this: \")),eval(input(\"to this: \")))` means.\n",
+ "Finally, as a bit of an interlude, I will explain what the line `add(eval(input(\"Add this: \")), eval(input(\"to this: \")))` means.\n",
"\n",
- "I wanted to fit everything onto one line, with as few variables as possible. Remember what functions look like to the main program? Whatever value they return. If the numbers you passed to the add() function were 2 and 30, the main program would see this:\n",
+ "I wanted to fit everything onto one line, with as few variables as possible. Remember what functions look like to the main program? Whatever value they return. If the numbers you passed to the `add()` function were 2 and 30, the main program would see this:\n",
"\n",
"`add(2,30)`\n",
"\n",
"The add program would then run, adding 2 and 30, then printing the result. The add program has no `return` operator - it doesn't return anything to the main program. It simply adds two numbers and prints them onscreen, and the main program doesn't see anything of it.\n",
"\n",
- "Instead of `(eval(input(\"Add this: \")),eval(input(\"to this: \")))` as the parameters for the add program you could have variables. E.g.\n",
+ "Instead of `(eval(input(\"Add this: \")), eval(input(\"to this: \")))` as the parameters for the add program, you could have variables. E.g.\n",
"\n",
- "```\n",
+ "```python\n",
"num1 = 45\n",
"num2 = 7\n",
- "add(num1,num2)\n",
+ "add(num1, num2)\n",
"```\n",
"\n",
"For the above, remember that the function you are passing the variables to cannot change the variables themselves - they are simply used as values. You could even put the values straight into the function:\n",
"\n",
"`add(45,7)`\n",
"\n",
- "This is because the only thing the function sees are the values that are passed on as parameters. Those values are put into the variables that are mentioned when `add` is defined (the line `def add(a,b)`). The function then uses those parameters to do its job.\n",
+ "This is because the only thing the function sees are the values that are passed on as parameters. Those values are put into the variables that are mentioned when `add` is defined (the line `def add(a, b)`). The function then uses those parameters to do its job.\n",
"\n",
"In short:\n",
"* The only thing functions see of the main program is the parameters that are passed to it\n",
diff --git a/PythonIntroCh5.ipynb b/PythonIntroCh5.ipynb
index d360cb9..ae34ec8 100644
--- a/PythonIntroCh5.ipynb
+++ b/PythonIntroCh5.ipynb
@@ -13,11 +13,11 @@
"source": [
"# 5.\tTuples, Lists, and Dictionaries\n",
"## 5.1\tIntroduction\n",
- "Your brain still hurting from the last lesson? Never worry, this one will require a little less thought. We're going back to something simple - variables - but a little more in depth.\n",
+ "Is your brain still hurting from the last lesson? Never worry, this one will require a little less thought. We're going back to something simple - variables - but a little more in-depth.\n",
"\n",
"Think about it - variables store one bit of information. They may regurgitate (just not on the carpet...) that information at any point, and their bit of information can be changed at any time. Variables are great at what they do - storing a piece of information that may change over time.\n",
"\n",
- "But what if you need to store a long list of information, which doesn't change over time? Say, for example, the names of the months of the year. Or maybe a long list of information that does change over time? Say, for example, the names of all your cats. You might get new cats, some may die, some may become your dinner (we should trade recipies!). What about a phone book? For that you need to do a bit of referencing - you would have a list of names, and attached to each of those names, a phone number. How would you do that?"
+ "But what if you need to store a long list of information, which doesn't change over time? Say, for example, the names of the months of the year. Or maybe a long list of information that does change over time? Say, for example, the names of all your cats. You might get new cats, some may die, some may become your dinner (we should trade recipies!). What about a phone book? For that, you need to do a bit of referencing - you would have a list of names, and attached to each of those names, a phone number. How would you do that?"
]
},
{
@@ -26,9 +26,9 @@
"source": [
"## 5.2\tThe Solution - Lists, Tuples, and Dictionaries\n",
"For these three problems, Python uses three different solutions - Tuples, Lists, and Dictionaries:\n",
- "* **Lists** are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list, and add new values to the end. Example: Your many cats' names.\n",
- "* **Tuples** are just like lists, but you can't change their values. The values that you give it first up, are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.\n",
- "* **Dictionaries** are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them a definition. In Python, the word is called a 'key', and the definition a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book."
+ "* **Lists** are what they seem - a list of values. Each one of them is numbered, starting from zero - the first one is numbered zero, the second 1, the third 2, etc. You can remove values from the list and add new values to the end. Example: Your many cats' names.\n",
+ "* **Tuples** are just like lists, but you can't change their values. The values that you give it first up are the values that you are stuck with for the rest of the program. Again, each value is numbered starting from zero, for easy reference. Example: the names of the months of the year.\n",
+ "* **Dictionaries** are similar to what their name suggests - a dictionary. In a dictionary, you have an 'index' of words, and for each of them, a definition. In Python, the word is called a 'key', and the definition is a 'value'. The values in a dictionary aren't numbered - they aren't in any specific order, either - the key does the same thing. You can add, remove, and modify the values in dictionaries. Example: telephone book."
]
},
{
@@ -36,7 +36,7 @@
"metadata": {},
"source": [
"### 5.2.1 Tuples\n",
- "Tuples are pretty easy to make. You give your tuple a name, then after that the list of values it will carry. For example, the months of the year:"
+ "Tuples are pretty easy to make. You give your tuple a name, then after that, the list of values it will carry. For example, the months of the year:"
]
},
{
@@ -53,8 +53,8 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "* Note that the `\\` thingy at the end of the first line carries over that line of code to the next line. It is useful way of making big lines more readable.\n",
- "* Technically you don't have to put those parentheses there (the `(` and `)` thingies) but it stops Python from getting things confused.\n",
+ "* Note that the `\\` thingy at the end of the first line carries over that line of code to the next line. It is a useful way of making big lines more readable.\n",
+ "* Technically, you don't have to put those parentheses there (the `(` and `)` thingies), but it stops Python from getting things confused.\n",
"* You may have spaces after the commas if you feel it necessary - it doesn't really matter"
]
},
@@ -86,7 +86,7 @@
"metadata": {},
"source": [
"### 5.2.2 Lists\n",
- "Lists are extremely similar to tuples. Lists are modifiable (or 'mutable', as a programmer may say), so their values can be changed. Most of the time we use lists, not tuples, because we want to easily change the values of things if we need to.\n",
+ "Lists are extremely similar to tuples. Lists are modifiable (or 'mutable', as a programmer may say), so their values can be changed. Most of the time, we use lists, not tuples, because we want to easily change the values of things if we need to.\n",
"\n",
"Lists are defined very similarly to tuples. Say you have FIVE cats, called Tom, Snappy, Kitty, Jessie and Chester. To put them in a list, you would do this: "
]
@@ -106,7 +106,7 @@
"source": [
"As you see, the code is exactly the same as a tuple, EXCEPT that all the values are put between square brackets, not parentheses. Again, you don't have to have spaces after the comma.\n",
"\n",
- "You recall values from lists exactly the same as you do with tuples. For example, to print the name of your 3rd cat you would do this:"
+ "You recall values from lists exactly the same as you do with tuples. For example, to print the name of your 3rd cat, you would do this:"
]
},
{
@@ -124,7 +124,7 @@
"source": [
"You can also recall a range of examples, like above, for example - `cats[0:2]` would recall your 1st and 2nd cats. Try it in the field above.\n",
"\n",
- "Where lists come into their own is how they can be modified. To add a value to a list, you use the `append()` function. Let's say you got a new cat called Catherine. To add her to the list you'd do this:"
+ "Where lists come into their own is how they can be modified. To add a value to a list, you use the `append()` function. Let's say you got a new cat called Catherine. To add her to the list, you'd do this:"
]
},
{
@@ -204,12 +204,12 @@
"metadata": {},
"source": [
"### 5.3 Dictionaries\n",
- "Okay, so there is more to life than the names of your cats. You need to call your sister, mother, son, the fruit man, and anyone else who needs to know that their favourite cat is dead. For that you need a telephone book.\n",
+ "Okay, so there is more to life than the names of your cats. You need to call your sister, mother, son, the fruit man, and anyone else who needs to know that their favourite cat is dead. For that, you need a telephone book.\n",
"\n",
- "Now, the lists we've used above aren't really suitable for a telephone book. You need to know a number based on someone's name - not the other way around, like what we did with the cats. In the examples of months and cats, we gave the computer a number, and it gave us a name. This time we want to give the computer a name, and it gives us a number. For this we need *Dictionaries*.\n",
+ "Now, the lists we've used above aren't really suitable for a telephone book. You need to know a number based on someone's name - not the other way around, like what we did with the cats. In the examples of months and cats, we gave the computer a number, and it gave us a name. This time, we want to give the computer a name, and it gives us a number. For this, we need *Dictionaries*.\n",
"\n",
- "So how do we make a dictionary? Put away your binding equipment, it isn't that advanced.\n",
- "Remember, dictionaries have keys, and values. In a phone book, you have people's names, then their numbers. See a similarity?\n",
+ "So, how do we make a dictionary? Put away your binding equipment; it isn't that advanced.\n",
+ "Remember, dictionaries have keys and values. In a phone book, you have people's names, then their numbers. See a similarity?\n",
"\n",
"When you initially create a dictionary, it is very much like making a tuple or list. Tuples have `(` and `)` things, lists have `[` and `]` things. Guess what! Dictionaries have `{` and `}` things - curly braces. Here is an example below, showing a dictionary with four phone numbers in it:"
]
@@ -231,7 +231,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "When you run it you see that Lewis Lame's number is printed onscreen. Notice how instead of identifying the value by a number, like in the cats and months examples, we identify the value, using another value - in this case the person's name.\n",
+ "When you run it, you see that Lewis Lame's number is printed onscreen. Notice how, instead of identifying the value by a number, like in the cats and months examples, we identify the value using another value - in this case, the person's name.\n",
"\n",
"Ok, you've created a new phone book. Now you want to add new numbers to the book. What do you do? A very simple line of code:"
]
@@ -254,7 +254,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "All that line is saying is that there is a person called Gingerbread Man in the phone book, and his number is `1234567`. In other words - the key is `Gingerbread Man`, and the value is `1234567`."
+ "All that line is saying is that there is a person called Gingerbread Man in the phone book, and his number is `1234567`. In other words, the key is `Gingerbread Man`, and the value is `1234567`."
]
},
{
diff --git a/PythonIntroCh6.ipynb b/PythonIntroCh6.ipynb
index 30b9092..9b829e9 100644
--- a/PythonIntroCh6.ipynb
+++ b/PythonIntroCh6.ipynb
@@ -15,7 +15,7 @@
"## 6.1 Introduction\n",
"Well, in the first lesson about loops, I said I would put off teaching you the for loop, until we had reached lists. Well, here it is!\n",
"## 6.2 The `for` Loop\n",
- "Basically, the `for` loop does something for every value in a list. The way it is set out is a little confusing, but otherwise is very basic. Here is an example of it in code:"
+ "Basically, the `for` loop does something for every value in a list. The way it is set out is a little confusing, but otherwise it is very basic. Here is an example of it in code:"
]
},
{
@@ -40,7 +40,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "As you see, when the loop executes, it runs through all of the values in the list mentioned after `in`. It then puts them into `value`, and executes through the loop, each time with value being worth something different. Let's see it again, in a classic cheerleading call that we all know:"
+ "As you see, when the loop executes, it runs through all of the values in the list mentioned after `in`. It then puts them into `value`, and executes through the loop, each time with a value being worth something different. Let's see it again, in a classic cheerleading call that we all know:"
]
},
{
@@ -67,7 +67,7 @@
"source": [
"A couple of things you've just learnt:\n",
"* As you see, strings (remember - strings are lines of text) are just lists with lots of characters.\n",
- "* The program went through each of the letters (or values) in word, and it printed them onscreen. "
+ "* The program went through each of the letters (or values) in the word, and it printed them onscreen. "
]
},
{
@@ -82,7 +82,7 @@
"metadata": {},
"source": [
"## 6.3 Making a Menu Function\n",
- "Now to the business end of the lesson. Let's start writing programs. So far we have learnt variables, lists, loops, and functions. That is pretty much all we need for quite a bit of programming. So let's set ourselves a task."
+ "Now to the business end of the lesson. Let's start writing programs. So far, we have learnt variables, lists, loops, and functions. That is pretty much all we need for quite a bit of programming. So let's set ourselves a task."
]
},
{
@@ -134,9 +134,9 @@
"metadata": {},
"source": [
"## 6.4 Our First 'Game'\n",
- "What will our first example program be? How about a (very) simple text adventure game? Sounds like fun! It will only encompass one room of a house, and will be extremely simple. There will be five things, and a door. In one of the five things, is a key to the door. You need to find the key, then open the door. I will give a plain-english version first, then do it in Python: \n",
+ "What will our first example program be? How about a (very) simple text adventure game? Sounds like fun! It will only encompass one room of a house, and will be extremely simple. There will be five things and a door. One of the five things, is a key to the door. You need to find the key, then open the door. I will give a plain-English version first, then do it in Python: \n",
"```\n",
- "#Plain-english version of our 'game'\n",
+ "#Plain-English version of our 'game'\n",
"\n",
"Tell the computer about our menu function\n",
"\n",
@@ -162,7 +162,7 @@
" If the player has the key, let them open the door\n",
" Otherwise, tell them to look harder\n",
"\n",
- "Give the player a well done message, for completing the game.\n",
+ "Give the player a well-done message for completing the game.\n",
"```\n",
" \n",
"From this, we can write a real program. Ready? Here it is:"
@@ -280,9 +280,9 @@
"metadata": {},
"source": [
"## 6.5 Making the Game Better\n",
- "The first question you should ask is \"does this program work?\". The answer here is yes. Then you should ask \"does this program work well?\" - not quite. The `menu()` function is great - it reduces a lot of typing. The `while` loop that we have, however, is a little messy - four levels of indents, for a simple program. We can do better!\n",
+ "The first question you should ask is \"Does this program work?\" The answer here is yes. Then you should ask, \"Does this program work well?\" - not quite. The `menu()` function is great - it reduces a lot of typing. The `while` loop that we have, however, is a little messy - four levels of indents, for a simple program. We can do better!\n",
"\n",
- "Now, this will become much MUCH more straightforward when we introduce classes. But that will have to wait. Until then, let's make a function that reduces our mess. It we will pass two things to it - the menu choice we made, and the location of the key. It will return one thing - whether or not the key has been found. Lets see it:\n",
+ "Now, this will become much MUCH more straightforward when we introduce classes. But that will have to wait. Until then, let's make a function that reduces our mess. We will pass two things to it - the menu choice we made, and the location of the key. It will return one thing - whether or not the key has been found. Let's see it:\n",
"\n",
"```Python\n",
"def inspect(choice,location):\n",
diff --git a/PythonIntroCh7.ipynb b/PythonIntroCh7.ipynb
index ea29597..b328d2a 100644
--- a/PythonIntroCh7.ipynb
+++ b/PythonIntroCh7.ipynb
@@ -17,22 +17,22 @@
"\n",
"That is what functions cover in Python. You've already had your code do something special. Now you want to do it again. You put that special code into a function, and re-use it for all it is worth. You can refer to a function anywhere in your code, and the computer will always know what you are talking about. Handy, eh?\n",
"\n",
- "Of course, functions have their limitations. Functions don't store any information like variables do - every time a function is run, it starts afresh. However, certain functions and variables are related to each other very closely, and need to interact with each other a lot. For example, imagine you have a golf club. It has information about it (i.e. variables) like the length of the shaft, the material of the grip, and the material of the head. It also has functions associated with it, like the function of swinging your golf club, or the function of breaking it in pure frustration. For those functions, you need to know the variables of the shaft length, head material, etc.\n",
+ "Of course, functions have their limitations. Functions don't store any information like variables do - every time a function is run, it starts afresh. However, certain functions and variables are related to each other very closely and need to interact with each other a lot. For example, imagine you have a golf club. It has information about it (i.e. variables) like the length of the shaft, the material of the grip, and the material of the head. It also has functions associated with it, like the function of swinging your golf club, or the function of breaking it in pure frustration. For those functions, you need to know the variables of the shaft length, head material, etc.\n",
"\n",
"That can easily be worked around with normal functions. Parameters affect the effect of a function. But what if a function needs to affect variables? What happens if each time you use your golf club, the shaft gets weaker, the grip on the handle wears away a little, you get that little more frustrated, and a new scratch is formed on the head of the club? A function cannot do that. A function only makes one output, not four or five, or five hundred. What is needed is a way to group functions and variables that are closely related into one place so that they can interact with each other.\n",
"\n",
- "Chances are that you also have more than one golf club. Without classes, you need to write a whole heap of code for each different golf club. This is a pain, seeing that all clubs share common features, it is just that some have changed properties - like what the shaft is made of, and it's weight. The ideal situation would be to have a design of your basic golf club. Each time you create a new club, simply specify its attributes - the length of its shaft, its weight, etc.\n",
+ "Chances are that you also have more than one golf club. Without classes, you need to write a whole heap of code for each different golf club. This is a pain, seeing that all clubs share common features, it is just that some have changed properties, like what the shaft is made of, and its weight. The ideal situation would be to have a design of your basic golf club. Each time you create a new club, simply specify its attributes - the length of its shaft, its weight, etc.\n",
"\n",
- "Or what if you want a golf club, which has added extra features? Maybe you decide to attach a clock to your golf club (why, I don't know - it was your idea). Does this mean that we have to create this golf club from scratch? We would have to write code first for our basic golf club, plus all of that again, and the code for the clock, for our new design. Wouldn't it be better if we were to just take our existing golf club, and then tack the code for the clock to it?\n",
+ "Or what if you want a golf club which has added extra features? Maybe you decide to attach a clock to your golf club (why, I don't know - it was your idea). Does this mean that we have to create this golf club from scratch? We would have to write code first for our basic golf club, plus all of that again, and the code for the clock, for our new design. Wouldn't it be better if we were to just take our existing golf club, and then tack the code for the clock to it?\n",
"\n",
"These are problems that a thing called object-oriented-programming solves. It puts functions and variables together in a way that they can see each other and work together, be replicated, and altered as needed, and not when unneeded. And we use a thing called a `class` to do this.\n",
"\n",
"## 7.2 Creating a `Class`\n",
- "What is a class? Think of a class as a blueprint. It isn't something in itself, it simply describes how to make something. You can create lots of objects from that blueprint - known technically as an *instance*.\n",
+ "What is a class? Think of a class as a blueprint. It isn't something in itself; it simply describes how to make something. You can create lots of objects from that blueprint - known technically as an *instance*.\n",
"\n",
"So how do you make these so-called 'classes'? very easily, with the `class` operator:\n",
"\n",
- "```Python\n",
+ "```python\n",
"# Defining a class\n",
"class class_name:\n",
" [statement 1]\n",
@@ -41,9 +41,9 @@
" [etc]\n",
"```\n",
"\n",
- "Makes little sense? That's okay, here is an example, that creates the definition of a `Shape`:\n",
+ "Makes little sense? That's okay, here is an example that creates the definition of a `Shape`:\n",
"\n",
- "```Python\n",
+ "```python\n",
"#An example of a class\n",
"class Shape:\n",
" def __init__(self,x,y):\n",
@@ -64,16 +64,16 @@
" self.y = self.y * scale\n",
"```\n",
"\n",
- "What you have created is a description of a shape (that is, the variables) and what operations you can do with the shape (that is, the fuctions). This is very important - you have not made an actual shape, simply the description of what a shape is. The shape has a width (`x`), a height (`y`), and an area and perimeter (`area(self)` and `perimeter(self)`). No code is run when you define a class - you are simply making functions and variables.\n",
+ "What you have created is a description of a shape (that is, the variables) and what operations you can do with the shape (that is, the functions). This is very important - you have not made an actual shape, simply the description of what a shape is. The shape has a width (`x`), a height (`y`), and an area and perimeter (`area(self)` and `perimeter(self)`). No code is run when you define a class - you are simply making functions and variables.\n",
"\n",
"The function called `__init__` is run when we create an instance of `Shape` - that is, when we create an actual shape, as opposed to the 'blueprint' we have here, `__init__` is run. You will understand how this works later.\n",
"\n",
- "`self` is how we refer to things in the class from within itself. `self` is the first parameter in any function defined inside a class. Any function or variable created on the first level of indentation (that is, lines of code that start one TAB to the right of where we put class `Shape` is automatically put into self. To access these functions and variables elsewhere inside the class, their name must be preceeded with `self` and a full-stop (e.g. `self.variable_name`). Without `self` you can only use the variables inside the function where they are defined, not in other functions in the same `class`.\n",
+ "`self` is how we refer to things in the class from within itself. `self` is the first parameter in any function defined inside a class. Any function or variable created on the first level of indentation (that is, lines of code that start one TAB to the right of where we put class `Shape` is automatically put into self. To access these functions and variables elsewhere inside the class, their name must be preceded with `self` and a full-stop (e.g. `self.variable_name`). Without `self`, you can only use the variables inside the function where they are defined, not in other functions in the same `class`.\n",
"\n",
"## 7.3 Using a `class`\n",
"It's all well and good that we can make a class, but how do we use one? Here is an example of what we call creating an instance of a class. Assume that the code above has already been run:\n",
"\n",
- "```Python\n",
+ "```python\n",
"rectangle = Shape(100,45)\n",
"```\n",
"\n",
@@ -81,7 +81,7 @@
"\n",
"The `__init__` function really comes into play at this time. We create an instance of a class by first giving its name (in this case, `Shape`) and then, in brackets, the values to pass to the `__init__` function. The init function runs (using the parameters you gave it in brackets) and then spits out an instance of that class, which in this case is assigned to the name `rectangle`.\n",
"\n",
- "Think of our class instance, `rectangle`, as a self-contained collection of variables and functions. In the same way that we used `self` to access functions and variables of the class instance from within itself, we use the name that we assigned to it now (rectangle) to access functions and variables of the class instance from outside of itself. Adding all code above, we would do this:"
+ "Think of our class instance, `rectangle`, as a self-contained collection of variables and functions. In the same way that we used `self` to access functions and variables of the class instance from within itself, we use the name that we assigned to it now (rectangle) to access functions and variables of the class instance from outside of itself. Adding all the code above, we would do this:"
]
},
{
@@ -134,7 +134,7 @@
"As you see, where `self` would be used from within the class instance, its assigned name is used when outside the class. We do this to view and change the variables inside the class, and to access the functions that are there.\n",
"\n",
"We aren't limited to a single instance of a class - we could have as many instances as we like. I could do this:\n",
- "```Python\n",
+ "```python\n",
"longrectangle = Shape(120,10)\n",
"fatrectangle = Shape(130,120)\n",
"```\n",
@@ -149,7 +149,7 @@
"metadata": {},
"source": [
"## 7.4 Lingo\n",
- "Object-oriented-programming has a set of lingo that is associated with it. Its about time that we have this all cleared up:\n",
+ "Object-oriented-programming has a set of lingo that is associated with it. It's about time that we have this all cleared up:\n",
"* When we first describe a `class`, we are *defining* it (like with functions)\n",
"* The ability to group similar functions and variables together is called *encapsulation*\n",
"* The word `class` can be used when describing the code where the class is defined (like how a function is defined), and it can also refer to an instance of that `class` - this can get confusing, so make sure you know in which form we are talking about classes\n",
@@ -164,9 +164,9 @@
"metadata": {},
"source": [
"## 7.5 Inheritance\n",
- "Let's have a look back at the introduction. We know how classes group together variables and functions, known as attributes and methods, so that both the data and the code to process it is in the same spot. We can create any number of instances of that class, so that we don't have to write new code for every new object we create. But what about adding extra features to our golf club design? This is where *inheritance* comes into play.\n",
+ "Let's have a look back at the introduction. We know how classes group together variables and functions, known as attributes and methods, so that both the data and the code to process it are in the same spot. We can create any number of instances of that class, so that we don't have to write new code for every new object we create. But what about adding extra features to our golf club design? This is where *inheritance* comes into play.\n",
"\n",
- "Python makes inheritance really easily. We define a new class, based on another, 'parent' class. Our new class brings everything over from the parent, and we can also add other things to it. If any new attributes or methods have the same name as an attribute or method in our parent class, it is used instead of the parent one. Remember the `Shape` class?\n",
+ "Python makes inheritance really easy. We define a new class, based on another, 'parent' class. Our new class brings everything over from the parent, and we can also add other things to it. If any new attributes or methods have the same name as an attribute or method in our parent class, it is used instead of the parent one. Remember the `Shape` class?\n",
"\n",
"```Python\n",
"class Shape:\n",
@@ -197,7 +197,7 @@
"\t self.y = x\n",
"```\n",
"\n",
- "It is just like normally defining a class, but this time we put in brackets after the name, the parent class that we inherited from. As you see, we described a square really *quickly* because of this. That's because we inherited everything from the shape class, and changed only what needed to be changed. In this case we redefined the `__init__` function of Shape so that the X and Y values are the same. \n",
+ "It is just like normally defining a class, but this time we put in brackets after the name, the parent class that we inherited from. As you see, we described a square really *quickly* because of this. That's because we inherited everything from the shape class and changed only what needed to be changed. In this case, we redefined the `__init__` function of Shape so that the X and Y values are the same. \n",
"\n",
"Let's take from what we have learnt, and create another new class, this time inherited from `Square`. It will be two squares, one immediately left of the other:\n",
"```Python\n",
@@ -215,7 +215,7 @@
" return 2 * self.x + 3 * self.y\n",
"```\n",
"\n",
- "This time, we also had to redefine the `perimeter` function, as there is a line going down the middle of the shape. Try creating an instance of this class in the field below and play around with different values. Since the `class Shape` has already been run, you can simply add only the new classes here and add define the instances."
+ "This time, we also had to redefine the `perimeter` function, as there is a line going down the middle of the shape. Try creating an instance of this class in the field below and play around with different values. Since the `class Shape` has already been run, you can simply add only the new classes here and define the instances."
]
},
{
@@ -252,8 +252,8 @@
"## 7.6 Pointers and Dictionaries of Classes\n",
"Thinking back, when you say that one variable equals another, e.g. `variable2 = variable1`, the variable on the left-hand side of the equal-sign takes on the value of the variable on the right. With class instances, this happens a little differently - the name on the left becomes the class instance on the right. So in `instance2 = instance1`, `instance2` is 'pointing' to `instance1` - there are two names given to the one class instance, and you can access the class instance via either name. \n",
"\n",
- "In other languages, you do things like this using *pointers*, however in Python this all happens behind the scenes.\n",
- "The final thing that we will cover is dictionaries of classes. Keeping in mind what we have just learnt about pointers, we can assign an instance of a class to an entry in a list or dictionary. This allows for virtually any amount of class instances to exist when our program is run. Let's have a look at the example below, and see how it describes what I am talking about:"
+ "In other languages, you do things like this using *pointers*; however, in Python, this all happens behind the scenes.\n",
+ "The final thing that we will cover is dictionaries of classes. Keeping in mind what we have just learnt about pointers, we can assign an instance of a class to an entry in a list or dictionary. This allows for virtually any number of class instances to exist when our program is run. Let's have a look at the example below, and see how it describes what I am talking about:"
]
},
{
@@ -282,7 +282,7 @@
"cell_type": "markdown",
"metadata": {},
"source": [
- "As you see, we simply replaced our boring old name on the left-hand side with an exciting, new, dynamic, dictionary entry. Pretty cool, eh?\n",
+ "As you see, we simply replaced our boring old name on the left-hand side with an exciting, new, dynamic dictionary entry. Pretty cool, eh?\n",
"## 7.7 Conclusion\n",
"And that is the lesson on classes! You won't believe how long it took me to write this in a clear-cut manner, and I am still not completely satisfied! I have already gone through and rewritten half of this lesson once, and if you're still confused, I'll probably go through it again. I've probably confused some of you with my own confusion on this topic, but remember - it is not something's name that is important, but what it does (this doesn't work in a social setting, believe me... ;))."
]
diff --git a/PythonIntroCh8.ipynb b/PythonIntroCh8.ipynb
index 0291f4a..bcab4ae 100644
--- a/PythonIntroCh8.ipynb
+++ b/PythonIntroCh8.ipynb
@@ -13,7 +13,7 @@
"source": [
"# 8. Modules\n",
"## 8.1 Introduction\n",
- "Last lesson we covered the killer topic of Classes. As you can remember, classes are neat combinations of variables and functions in a nice, neat package. Programming lingo calls this feature encapsulation, but regardless of what it is called, it's a really cool feature for keeping things together so the code can be used in many instances in lots of places. Of course, you've got to ask, \"how do I get my classes to many places, in many programs?\". The answer is to put them into a module, to be imported into other programs."
+ "Last lesson we covered the killer topic of Classes. As you can remember, classes are neat combinations of variables and functions in a nice, neat package. Programming lingo calls this feature encapsulation, but regardless of what it is called, it's a really cool feature for keeping things together so the code can be used in many instances in lots of places. Of course, you've got to ask, \"How do I get my classes to many places, in many programs?\" The answer is to put them into a module, to be imported into other programs."
]
},
{
@@ -61,7 +61,7 @@
"import moduletest\n",
"```\n",
"\n",
- "This assumes that the module is in the same directory as `mainprogram.py`, or is a default module that comes with Python. You leave out the `.py` at the end of the file name - it is ignored. You normally put all `import` statements at the beginning of the Python file, but technically they can be anywhere. In order to use the items in the module in your main program, you use the following:\n",
+ "This assumes that the module is in the same directory as `mainprogram.py`, or is a default module that comes with Python. You leave out the `.py` at the end of the file name - it is ignored. You normally put all `import` statements at the beginning of the Python file, but technically, they can be anywhere. In order to use the items in the module in your main program, you use the following:\n",
"\n",
"```Python\n",
"### USING AN IMPORTED MODULE\n",
@@ -127,7 +127,7 @@
"\n",
"## 8.4 Conclusion\n",
"That's it! A very simple lesson, but now you can organise your programs very neatly. In fact, now it is incredibly easy to make programs that can grow in complexity without ending up with one cryptic file that is full of bugs.\n",
- "Modules are great for importing code. Next lesson, we learn about file input and output, and the saving of information inside classes, to be retrieved later. Will be great!"
+ "Modules are great for importing code. Next lesson, we will learn about file input and output, and the saving of information inside classes, to be retrieved later. Will be great!"
]
},
{
diff --git a/PythonIntroCh9.ipynb b/PythonIntroCh9.ipynb
index dc989c2..ae96b30 100644
--- a/PythonIntroCh9.ipynb
+++ b/PythonIntroCh9.ipynb
@@ -13,11 +13,11 @@
"source": [
"# 9. File I/O\n",
"## 9.1 Introduction\n",
- "Last lesson we learned how to load external code into our program. Without any introduction (like what I usually have), let's delve into file input and output with normal text files, and later the saving and restoring of instances of classes. (Wow, our lingo power has improved greatly!)\n",
+ "Last lesson, we learned how to load external code into our program. Without any introduction (like what I usually have), let's delve into file input and output with normal text files, and later, the saving and restoring of instances of classes. (Wow, our lingo power has improved greatly!)\n",
"## 9.2 Opening a file\n",
- "To open a text file you use, well, the `open()` function. Seems sensible. You pass certain parameters to `open()` to tell it in which way the file should be opened - `r` for read only, `w` for writing only (if there is an old file, it will be written over), `a` for appending (adding things on to the end of the file) and `r+` for both reading and writing. But less talk, let's open a file for reading (you can do this in Spyder later in the course). Open a normal text file. We will then print out what we read inside the file:\n",
+ "To open a text file, you use, well, the `open()` function. Seems sensible. You pass certain parameters to `open()` to tell it in which way the file should be opened - `r` for read only, `w` for writing only (if there is an old file, it will be written over), `a` for appending (adding things on to the end of the file) and `r+` for both reading and writing. But less talk, let's open a file for reading (you can do this in Spyder later in the course). Open a normal text file. We will then print out what we read inside the file:\n",
"```Python\n",
- "filename = 'C:\\\\temp\\\\readme.txt' # path to file.\\ is an escape character, so you need 2 or use / instead.\n",
+ "filename = 'C:\\\\temp\\\\readme.txt' # path to file.\\ is an escape character, so you need two i.e. \\\\ or use / instead.\n",
"fl = open(filename, 'r') # Open the file\n",
"for line in fl:\n",
" print(line)\n",
@@ -32,7 +32,7 @@
" print(line)\n",
"```\n",
"\n",
- "With the second method you don't have to add `fl.close`, it is automagically closed."
+ "With the second method, you don't have to add `fl.close`; it is automatically closed."
]
},
{
@@ -48,11 +48,11 @@
"print(fl.read())\n",
"```\n",
"\n",
- "Did you try to run `print(fl.read())` a second time? Did it fail? It likely did, and reason is because the 'cursor' has changed it's place. Cursor? What cursor? Well, a cursor that you really cannot see, but still a cursor. This invisible cursor tells the read function (and many other I/O functions) where to start from. To set where the cursor is, you use the `seek()` function. It is used in the form `seek(offset, whence)`.\n",
+ "Did you try to run `print(fl.read())` a second time? Did it fail? It likely did, and the reason is that the 'cursor' has changed its place. Cursor? What cursor? Well, a cursor that you really cannot see, but still a cursor. This invisible cursor tells the read function (and many other I/O functions) where to start from. To set where the cursor is, you use the `seek()` function. It is used in the form `seek(offset, whence)`.\n",
"\n",
"`whence` is optional, and determines where to seek from. If `whence` is 0, the bytes/letters are counted from the beginning. If it is 1, the bytes are counted from the current cursor position. If it is 2, then the bytes are counted from the end of the file. If nothing is put there, 0 is assumed.\n",
"\n",
- "`offset` decribes how far from `whence` that the cursor moves. for example:\n",
+ "`offset` describes how far from `whence` that the cursor moves. for example:\n",
"* `fl.seek(45,0)` would move the cursor to 45 bytes/letters after the beginning of the file.\n",
"* `fl.seek(10,1)` would move the cursor to 10 bytes/letters after the current cursor position.\n",
"* `fl.seek(-77,2)` would move the cursor to 77 bytes/letters before the end of the file (notice the - before the 77)\n"
@@ -65,13 +65,13 @@
"We can use `fl.seek()` to go to any spot in the file and then try typing `print(fl.read())`. It will print from the spot you seeked to. But realise that `fl.read()` moves the cursor to the end of the file - you will have to seek again.\n",
"\n",
"## 9.4 Other I/O Functions\n",
- "There are many other functions that help you with dealing with files. They have many uses that empower you to do more, and make the things you can do easier. Let's have a look at `tell()`, `readline()`, `readlines()`, `write()` and `close()`.\n",
+ "There are many other functions that help you with dealing with files. They have many uses that empower you to do more and make the things you can do easier. Let's have a look at `tell()`, `readline()`, `readlines()`, `write()` and `close()`.\n",
"\n",
- "`tell()` returns where the cursor is in the file. It has no parameters, just type it in (like what the example below will show). This is infinitely useful, for knowing what you are referring to, where it is, and simple control of the cursor. To use it, type `fileobjectname.tell()` - where fileobjectname is the name of the file object you created when you opened the file (in `openfile = open('pathtofile', 'r')` the file object name is `openfile`).\n",
+ "`tell()` returns where the cursor is in the file. It has no parameters, just type it in (like what the example below will show). This is infinitely useful for knowing what you are referring to, where it is, and simple control of the cursor. To use it, type `fileobjectname.tell()` - where fileobjectname is the name of the file object you created when you opened the file (in `openfile = open('pathtofile', 'r')`, the file object name is `openfile`).\n",
"\n",
- "`readline()` reads from where the cursor is till the end of the line. Remember that the end of the line isn't the edge of your screen - the line ends when you press enter to create a new line. This is useful for things like reading a log of events, or going through something progressively to process it. There are no parameters you have to pass to `readline()`, though you can optionally tell it the maximum number of bytes/letters to read by putting a number in the brackets. Use it with `fileobjectname.readline()`. \n",
+ "`readline()` reads from where the cursor is till the end of the line. Remember that the end of the line isn't the edge of your screen - the line ends when you press enter to create a new line. This is useful for things like reading a log of events or going through something progressively to process it. There are no parameters you have to pass to `readline()`, though you can optionally tell it the maximum number of bytes/letters to read by putting a number in the brackets. Use it with `fileobjectname.readline()`. \n",
"\n",
- "`readlines()` is much like `readline()`, however `readlines()` reads all the lines from the cursor onwards, and returns a list, with each list element holding a line of code. Use it with `fileobjectname.readlines()`. For example, if you had the text file:\n",
+ "`readlines()` is much like `readline()`, however, `readlines()` reads all the lines from the cursor onwards, and returns a list, with each list element holding a line of code. Use it with `fileobjectname.readlines()`. For example, if you had the text file:\n",
"```\n",
"Line 1\n",
"\n",
@@ -91,11 +91,11 @@
"| 4 | \" |\n",
"| 5 | 'Line 6' |\n",
"\n",
- "The `write()` function, writes to the file. How did you guess??? It writes from where the cursor is, and overwrites text in front of it - like in MS Word, where you press 'insert' and it writes over the top of old text. To utilise this most purposeful function, put a string between the brackets to write e.g. `fileobjectname.write('this is a string')`.\n",
+ "The `write()` function writes to the file. How did you guess??? It writes from where the cursor is, and overwrites text in front of it - like in MS Word, where you press 'insert' and it writes over the top of old text. To utilise this most purposeful function, put a string between the brackets to write e.g. `fileobjectname.write('this is a string')`.\n",
"\n",
- "`close`, you may figure, closes the file so that you can no longer read or write to it until you reopen in again. Simple enough. To use, you would write `fileobjectname.close()`. Simple!\n",
+ "`close`, you may figure, closes the file so that you can no longer read or write to it until you reopen it again. Simple enough. To use, you would write `fileobjectname.close()`. Simple!\n",
"\n",
- "Later in the course you can try this in the Python command line. Open up a test file (or create a new one...) and play around with these functions. You can do some simple (and very inconvenient) text editing."
+ "Later in the course, you can try this in the Python command line. Open up a test file (or create a new one...) and play around with these functions. You can do some simple (and very inconvenient) text editing."
]
},
{
@@ -105,9 +105,9 @@
"## 9.5 Mmm, Pickles\n",
"Pickles, in Python, are to be eaten. Their flavour is just too good to let programmers leave them in the fridge.\n",
"\n",
- "Ok, just joking there. Pickles, in Python, are objects saved to a file. An object in this case could be a variable, instance of a class, or a list, dictionary, or tuple. Other things can also be pickled, but with limits. The object can then be restored, or unpickled, later on. In other words, you are 'saving' your objects.\n",
+ "Ok, just joking there. Pickles, in Python, are objects saved to a file. An object in this case could be a variable, an instance of a class, or a list, dictionary, or tuple. Other things can also be pickled, but with limits. The object can then be restored, or unpickled, later on. In other words, you are 'saving' your objects.\n",
"\n",
- "So how do we pickle? With the `dump()` function, which is inside the pickle module - so at the beginning of your program you will have to write `import pickle`. Simple enough? Then open an empty file, and use `pickle.dump()` to drop the object into that file. Let's try that:\n",
+ "So how do we pickle? With the `dump()` function, which is inside the pickle module, so at the beginning of your program, you will have to write `import pickle`. Simple enough? Then open an empty file, and use `pickle.dump()` to drop the object into that file. Let's try that:\n",
"\n",
"```Python\n",
"### pickletest.py\n",
@@ -133,7 +133,7 @@
"```\n",
"\n",
"The code to do this is laid out like `pickle.dump(object_to_pickle, file_object)` where:\n",
- "* `object_to_pickle` is the object you want to pickle (i.e. save it to file)\n",
+ "* `object_to_pickle` is the object you want to pickle (i.e. save it to a file)\n",
"* `file_object` is the file object you want to write to (in this case, the file object is `file`)"
]
},
@@ -165,7 +165,7 @@
"```\n",
"Nifty, eh? \n",
"\n",
- "Of course, the limitation above is that we can only put in one object to a file. We could get around this by putting lots of picklable objects in a list or dictionary, and then pickling that list or dictionary. This is the quickest and easiest way, but you can do some pretty advanced stuff if you have advanced knowledge of pickle. \n",
+ "Of course, the limitation above is that we can only put in one object in a file. We could get around this by putting lots of picklable objects in a list or dictionary, and then pickling that list or dictionary. This is the quickest and easiest way, but you can do some pretty advanced stuff if you have advanced knowledge of pickle. \n",
" \n",
"Which we won't cover."
]