diff --git a/learning_python3.md b/learning_python3.md index 9a4f894..b674a86 100644 --- a/learning_python3.md +++ b/learning_python3.md @@ -6,34 +6,30 @@ Keep this in mind, everybody has to go through this stage and the *click* comes The three new things you'll learn: 1. the **concepts** of programming, most notably Object Orientated Programming (OOP) -2. the **syntax** of one particular language, in our case Python3 +2. the **syntax** of one particular language, in our case python3 3. the **tools** needed to start programming in our language of choice -Within each of these topics there are *subtopics* but there are not bottomless! -Below is a small overview of how I would subdivide them. +Within each of these topics there are *subtopics* but these are not bottomless! +Below is a small overview of how *I* would subdivide them. ## Concepts The subtopics behind the concept of programming can be sliced (in no particular order) as follows: * objects or **OOP** (Object Orientated Programming) - * abstraction - * encapsulation - * inheritance - * polymorphism * variables (which are **not** *boxes* in python3) * conditional logic * functions * loops -The concept behind these topics are the same in most languages, it's just *how* you write them that is different. +The concepts behind these topics are the same in most modern languages, it's just *how* you write them that is different. This *how* is part of the **syntax** of the language. ## Syntax > In computer science, the syntax of a computer language is the set of rules that defines the combinations of symbols that are considered to be correctly structured statements or expressions in that language. > This applies both to programming languages, where the document represents source code, and to markup languages, where the document represents data. -> The syntax of a language defines its surface form.[1] Text-based computer languages are based on sequences of characters, +> The syntax of a language defines its surface form.[1] The quote above is taken shamelessly from [wikipedia](https://en.wikipedia.org/wiki/Syntax_(programming_languages)). @@ -41,20 +37,19 @@ The quote above is taken shamelessly from [wikipedia](https://en.wikipedia.org/w ### Writing code -Scripts are text files, plain and simple. So in order to **write** a Python3 script all we need is a text editor. +Scripts are text files, plain and simple. So in order to **write** a python3 script all we need is a text editor. Nano, vim, notepad++ all do a good job of editing plain text files but some make it *easier* than others. -You've noticed that vim colors the code of a shell script no? One of the many features of an [IDE](https://en.wikipedia.org/wiki/Integrated_development_environment) is *syntax highlighting*. It colors things such as [keywords](https://realpython.com/python-keywords/) which makes our life so much nicer when writing code. We'll come back to these features in a bit. ### Running code -In order to **run** Python3 code you need the Python3 interpreter. +In order to **run** python3 code you need the python3 interpreter. This is because when you **execute** your script, the interpreter will **read and execute** each line of the text file **line by line**. -Most people who want to write and run Python3 code, or any language for that matter, will install an Integrated Development Environment to do so. -There are no *rules* as to what has to be included for a program to qualify as an IDE but in my opinion they should include: +Most people who want to write and run python3 code, or any language for that matter, will install an Integrated Development Environment to do so. +There are no *rules* as to what has to be included for a program to qualify as an IDE but in my opinion it should include: * syntax highlighting * autocomplete @@ -68,7 +63,6 @@ There is a plethora of IDE's available and you can't really make a *wrong* choic TODO animated overview of the shell and the world of OOP - # Installing pycharm TODO @@ -144,7 +138,7 @@ print("I'm", 35, "years old") Try printing different lines and with combinations of different object types such as `int`, `float` and `str`. What happens if you *add* (`+`) values to one another? - +What about subtracting? We can also print the objects referenced by variables. A simple example: @@ -191,7 +185,7 @@ print("Hello, my name is {} and I'm {} years old.".format(name, age)) # Taking input -The first **builtin function** we saw is `print` which can be used to signal messages to the user. +The first **built-in function** we saw is `print` which can be used to signal messages to the user. But how can we **get** some information from the user? This is done with the `input` function. If we open up a python shell we can observe it's behaviour. @@ -240,13 +234,13 @@ Can you tell me why I did that?** --- Try playing around with the `input` function and incorporate the different ways to print with it. -Ask multiple questions and combine the answers to print on one line. +Ask multiple questions and combine the answers to print a sensible message on one line. ## Functions can take arguments Some, if not most, functions will take one or more arguments when calling them. This might sound complicated but you've already done this! -The `print` function takes *a-message-to-print* as an argument, or even multiple ones as you probably noticed when playing around. +The `print` function takes *a-message-to-print* as an argument, or even multiple ones as you probably noticed when playing around with `+` and `,`. The `input` function *can* take arguments but as we've seen does not *require* an argument. When looking at the documentation we can discover **what** the function does, how to **call** the function and what it **returns**. @@ -280,7 +274,8 @@ print("Well hello {}!".format(answer)) --- Modify the questions you asked before so they have a proper prompt via the `input` function. -Ask multiple questions and combine the answers to print on one line with different `print` formatting. +Ask multiple questions and combine the answers to print a message on one line. +Try it with different `print` formatting. # Taking input and evaluation @@ -290,7 +285,7 @@ This is a lot easier than you think. Imagine you ask me my age. When I respond with *35* you'll think to yourself *"that's old!"*. If I would be younger then *30* you would think I'm young. -We can implement this logic in python with easy to read syntax. +We can implement this logic in python with an easy to read syntax. First we'll take a python **shell** to experiment a bit. ```python3 @@ -356,7 +351,7 @@ An object of the type `str` has multiple **methods** that can be applied on itse It might not have been obvious but the *string formatting* via `"hello {}".format("world")` we did above is exactly this. We **call** the `.format` **method** on a `str` object. Strings have a handful of methods we can call. -Pycharm lists these methods when you type `.` after a string. +Pycharm lists these methods when you type `.` after a string object. In the **shell** we can visualize this as well. For those of you not familiar with shells have a look at [tab completion](https://en.wikipedia.org/wiki/Command-line_completion). @@ -456,6 +451,7 @@ How much EUR would you like to convert into DOLLAR? blablabla That's not a number I understand... ➜ python_course_doc git:(master) ✗ ``` +
Spoiler warning @@ -479,12 +475,12 @@ else: We can use conditional logic to create quite elaborate decision processes. Let's build a mini text based adventure game. -Granted it's not a *tripple A* game but it will train your `if` and `else` skills plus it will highlight some issues we'll overcome in the next section. +Granted it's not a *triple A* game but it will train your `if` and `else` skills plus it will highlight some issues we'll overcome in the next section. ![adventure game](./assets/text_based_adventure_game.png) Consider the diagram above we can imagine a program that functions nicely with the code below. -It is not very *readable* nor *scalable*. +It is however not very *readable* nor *scalable*. ```python3 answer = input("You're at a cross section. Do you go left or right?") @@ -542,13 +538,14 @@ We will not improve on this particular example but I do advise you to create a s One of the *issues* we have in the text based game example is duplicate code. At two spots we execute almost identical code and this is something that should be avoided at all costs! Why write the same thing over and over? +Each time you write it again you introduce a new window for errors! You're better off writing it **once** and use it **lots**. This is where **functions** come into play. Python ships with a lot of built-in functions but we can create our own very easily. -The keyword to define a function in python is `def`. +The [keyword](https://docs.python.org/3/reference/compound_stmts.html#function-definitions) to define a function in python is `def`. All the code that is *indented* will be executed when we **call** the function. -Here is a basic abstraction of correct syntax. +Here is a basic abstraction with a correct syntax. ```python3 def first_function(): @@ -621,9 +618,9 @@ bake_vanilla_cake() Voila, we can now make as many chocolate and vanilla cakes as we want! But what about *bananas*? Following our logic we can create a *third* function to bake a banana cake but you're probably seeing a *pattern* here. -Each `bake_FLAVOR_cake` function is almost identical, just for the flavoring. -We can create one generic `bake_cake` function and just add the custom flavor each time we actually *bake* a cake. -This is done with arguments. +Each `bake_FLAVOR_cake` function is almost identical, just the flavor changes. +We can create one generic `bake_cake` function and add the custom `flavor` each time we actually *bake* a cake. +This can be done with arguments. ```python3 def bake_cake(flavor): @@ -781,12 +778,13 @@ Over the course of you programming journey you'll discover that efficient progra Imagine we want to include a dice in our text based adventure game. How on earth do we program that? -We need some for of *randomness* in our code. +We need some form of *randomness* in our code. A [quick google](https://stackoverflow.com/questions/28705965/python-random-function-without-using-random-module) demonstrates this is quite difficult without the use of libraries. As randomness is both [extensively](https://www.random.org/randomness/) used in programming **and** it's quite [difficult](https://medium.com/swlh/random-functions-a4f36b1dfd8f) to do properly, you'll find a `random` library in most languages. The new **keyword** you'll learn here is `import`. -It allows you to add extra functionality to your program. +It allows you to *include* extra functionality to your program. +(Go look back at the `c` and `c++` helloworld code, what do you think the `#include` does?) Once *imported* we can **call** functions that exist from the library in question. So, our dice becomes as follows. @@ -1059,6 +1057,7 @@ A well written script or program is divided into **three** sections. A mock-up program that follows these rules could look like this. Notice how it's easy to read? +The `pass` is a new [keyword](https://docs.python.org/3/reference/simple_stmts.html#the-pass-statement) that does nothing but is often used to declare functions a placeholders. ```python3 import random @@ -1187,7 +1186,7 @@ While they might look scary, don't overthink it, you'll get used to them very qu 🏃 Try it --- -Go back to the Celsius to Farenheit converter and add a while loop to ensure the user put's in only numbers. +Go back to the Celsius to Farenheit converter and add a while loop to ensure the user puts in only numbers. # Coding challenge - Guess the number @@ -1504,7 +1503,7 @@ if __name__ == "__main__": To make things more interesting you can add a decode function. Plus you could add a prompt that asks how big the shift should be (ROT13, ROT16, ...). -You can make the cypher a **lot** harder to break if you use a word (or phrase as a key). +You can also make the cypher a **lot** harder to break if you use a word (or phrase as a key). For example, if the key is `abc` and the message is `hello world` the first letter will be offset by a ROT0 (will remain `h`). The second letter, `e` will be offset by a ROT1 so will become `f`. The third letter by ROT2 so will become `n`. @@ -1897,6 +1896,7 @@ bottle new beer,9,1 If we save this to a blank file we can us the built-in `open` function to read and interpret the data as a `list` of `dict`. The code below does exactly that, first without list comprehension, secondly with. +A CSV file is such a **standard** in programming that most languages come with a built-in [parser](https://en.wikipedia.org/wiki/Parsing), hence the `import csv`. ```python import csv @@ -1940,7 +1940,7 @@ We'll go over some abstract examples to showcase the syntax and usage, then do a A basic abstraction can be seen below. The main thing to take away from this code block is the new [keyword](https://docs.python.org/3/reference/compound_stmts.html#class-definitions) `class`. -Once the new `class` is defined, we can create an **instance** of this class. +Once the new `class` is defined (remember what `pass` does?), we can create an **instance** of this class. We can create as many instances as we want, just as with `str`! ```python @@ -2328,6 +2328,9 @@ for question in data["results"]: print(html.unescape("\t {} {}".format(*choice)))``` ``` +You can get some *inspiration* from a small project I did for an other course. +The code can be found [here](https://gitea.86thumbs.net/waldek/ccpq/src/branch/master). + ### Introduction to the `requests` library ## Threading