GeezerVison is showing github.com — Rest of chapters as markdown · python043/full-speed-python@27b1ed9
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: Makefile +12Lines changed: 12 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| 7 | 7 | chapters/installation.md \ | 8 | 8 | chapters/basic-datatypes.md \ | 9 | 9 | chapters/lists.md \ | | 10 | + chapters/functions.md \ | | 11 | + chapters/loops.md \ | | 12 | + chapters/dictionaries.md \ | | 13 | + chapters/classes.md \ | | 14 | + chapters/iterators.md \ | | 15 | + chapters/generators.md \ | 10 | 16 |
| 11 | 17 | pdf: | 12 | 18 | pandoc -o full-speed-python.pdf \ | | 16 | 22 | chapters/installation.md \ | 17 | 23 | chapters/basic-datatypes.md \ | 18 | 24 | chapters/lists.md \ | | 25 | + chapters/functions.md \ | | 26 | + chapters/loops.md \ | | 27 | + chapters/dictionaries.md \ | | 28 | + chapters/classes.md \ | | 29 | + chapters/iterators.md \ | | 30 | + chapters/generators.md \ | 19 | 31 |
| 20 | 32 | clean: | 21 | 33 | rm *.epub *.pdf |
Collapse file Copy file name to clipboard +73Lines changed: 73 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +# Classes | | 2 | + | | 3 | +In object oriented programming (OOP), a class is a structure that allows to group together a set of properties (called attributes) and functions (called methods) to manipulate those properties. Take the following class that defines a person with properties "name" and "age" and the "greet" method. | | 4 | + | | 5 | +```Python | | 6 | +class Person: | | 7 | + | | 8 | + def __init__(self, name, age): | | 9 | + self.name = name | | 10 | + self.age = age | | 11 | + | | 12 | + def greet(self): | | 13 | + print("Hello, my name is %s!" % self.name) | | 14 | +``` | | 15 | + | | 16 | +Most classes will need the constructor method ("\_\_init\_\_") to initialize the class’s attributes. In the previous case the constructor of the class receives the person’s name and age and stores that information in the class’s instance (referenced by the *self* keyword). Finally, "greet" method prints the name of the person as stored in a specific class instance (object). | | 17 | + | | 18 | +Class instances are used through the instantiation of objects. Here’s how we can instantiate two objects: | | 19 | + | | 20 | +```Python | | 21 | +>>> a = Person("Peter", 20) | | 22 | +>>> b = Person("Anna", 19) | | 23 | + | | 24 | +>>> a.greet() | | 25 | +Hello, my name is Peter! | | 26 | +>>> b.greet() | | 27 | +Hello, my name is Anna! | | 28 | + | | 29 | +>>> print(a.age) # We can also access the attributes of an object | | 30 | +20 | | 31 | +``` | | 32 | + | | 33 | +## Exercises with classes | | 34 | + | | 35 | +Use the Python documentation on classes at <https://docs.python.org/3/tutorial/classes.html> to solve the following exercises. | | 36 | + | | 37 | +1. Implement a class named "Rectangle" to store the coordinates of a rectangle given by (x1, y1) and (x2, y2). | | 38 | + | | 39 | +2. Implement the class constructor with the parameters (x1, y1, x2, y2) and store them in the class instances using the "self" keyword. | | 40 | + | | 41 | +3. Implement the "width()" and "height()" methods which return, respectively, the width and height of a rectangle. Create two objects, instances of "Rectangle" to test the calculations. | | 42 | + | | 43 | +4. Implement the method "area" to return the area of the rectangle (width\*height). | | 44 | + | | 45 | +5. Implement the method "circumference" to return the perimeter of the rectangle (2\*width + 2\*height). | | 46 | + | | 47 | +6. Do a print of one of the objects created to test the class. Implement the "\_\_str\_\_" method such that when you print one of the objects it print the coordinates as (x1, y1)(x2, y2). | | 48 | + | | 49 | +## Class inheritance | | 50 | + | | 51 | +In object oriented programming, inheritance is one of the forms in which a subclass can inherit the attributes and methods of another class, allowing it to rewrite some of the super class’s functionalities. For instance, from the "Person" class above we could create a subclass to keep people with 10 years of age: | | 52 | + | | 53 | +```Python | | 54 | +class TenYearOldPerson(Person): | | 55 | + | | 56 | + def __init__(self, name): | | 57 | + super().__init__(name, 10) | | 58 | + | | 59 | + def greet(self): | | 60 | + print("I don't talk to strangers!!") | | 61 | +``` | | 62 | + | | 63 | +The indication that the "TenYearOldPerson" class is a subclass of "Person" is given on the first line. Then, we rewrote the constructor of the subclass to only receive the name of the person, but we will eventually call the super class’s constructor with the name of the 10-year-old and the age hardcoded as 10. Finally we reimplemented the "greet" method. | | 64 | + | | 65 | +## Exercises with inheritance | | 66 | + | | 67 | +Use the "Rectangle" class as implemented above for the following exercises: | | 68 | + | | 69 | +1. Create a "Square" class as subclass of "Rectangle". | | 70 | + | | 71 | +2. Implement the "Square" constructor. The constructor should have only the x1, y1 coordinates and the size of the square. Notice which arguments you’ll have to use when you invoke the "Rectangle" constructor when you use "super". | | 72 | + | | 73 | +3. Instantiate two objects of "Square", invoke the area method and print the objects. Make sure that all calculations are returning correct numbers and that the coordinates of the squares are consistent with the size of the square used as argument. |
Collapse file Copy file name to clipboard +106Lines changed: 106 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +# Dictionaries | | 2 | + | | 3 | +In this chapter we will work with Python dictionaries. Dictionaries are data structures that indexes values by a given key (key-value pairs). The following example shows a dictionary that indexes students ages by name. | | 4 | + | | 5 | +```Python | | 6 | +ages = { | | 7 | + "Peter": 10, | | 8 | + "Isabel": 11, | | 9 | + "Anna": 9, | | 10 | + "Thomas": 10, | | 11 | + "Bob": 10, | | 12 | + "Joseph": 11, | | 13 | + "Maria": 12, | | 14 | + "Gabriel": 10, | | 15 | +} | | 16 | + | | 17 | +>>> print(ages["Peter"]) | | 18 | +10 | | 19 | +``` | | 20 | + | | 21 | +It is possible to iterate over the contents of a dictionary using "items", like this: | | 22 | + | | 23 | +```Python | | 24 | +>>> for name, age in ages.items(): | | 25 | +... print(name, age) | | 26 | +... | | 27 | +Peter 10 | | 28 | +Isabel 11 | | 29 | +Anna 9 | | 30 | +Thomas 10 | | 31 | +Bob 10 | | 32 | +Joseph 11 | | 33 | +Maria 12 | | 34 | +Gabriel 10 | | 35 | +``` | | 36 | + | | 37 | +However, dictionary keys don’t necessarily need to be strings but can be any [immutable](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) object: | | 38 | + | | 39 | +```Python | | 40 | +d = { | | 41 | + 0: [0, 0, 0], | | 42 | + 1: [1, 1, 1], | | 43 | + 2: [2, 2, 2], | | 44 | +} | | 45 | + | | 46 | +>>> d[2] | | 47 | +[2, 2, 2] | | 48 | +``` | | 49 | + | | 50 | +And you can also use other dictionaries as values: | | 51 | + | | 52 | +```Python | | 53 | +students = { | | 54 | + "Peter": {"age": 10, "address": "Lisbon"}, | | 55 | + "Isabel": {"age": 11, "address": "Sesimbra"}, | | 56 | + "Anna": {"age": 9, "address": "Lisbon"}, | | 57 | +} | | 58 | + | | 59 | +>>> students['Peter'] | | 60 | +{'age': 10, 'address': 'Lisbon'} | | 61 | +>>> students['Peter']['address'] | | 62 | +'Lisbon' | | 63 | +``` | | 64 | + | | 65 | +This is quite useful to structure hierarchical information. | | 66 | + | | 67 | +## Exercises with dictionaries | | 68 | + | | 69 | +Use the Python documentation at <https://docs.python.org/3/library/stdtypes.html#mapping-types-dict> to solve the following exercises. | | 70 | + | | 71 | +Take the following Python dictionary: | | 72 | + | | 73 | + ages = { | | 74 | + "Peter": 10, | | 75 | + "Isabel": 11, | | 76 | + "Anna": 9, | | 77 | + "Thomas": 10, | | 78 | + "Bob": 10, | | 79 | + "Joseph": 11, | | 80 | + "Maria": 12, | | 81 | + "Gabriel": 10, | | 82 | + } | | 83 | + | | 84 | +1. How many students are in the dictionary? Search for the "len" function. | | 85 | + | | 86 | +2. Implement a function that receives the "ages" dictionary as parameter and returns the average age of the students. Traverse all items on the dictionary using the "items" method as above. | | 87 | + | | 88 | +3. Implement a function that receives the "ages" dictionary as parameter and returns the name of the oldest student. | | 89 | + | | 90 | +4. Implement a function that receives the "ages" dictionary and a number "n" and returns a new dict where each student is \(n\) years older. For instance, *new_ages(ages, 10)* returns a copy of "ages" where each student is 10 years older. | | 91 | + | | 92 | +## Exercises with sub-dictionaries | | 93 | + | | 94 | +Take the following dictionary: | | 95 | + | | 96 | + students = { | | 97 | + "Peter": {"age": 10, "address": "Lisbon"}, | | 98 | + "Isabel": {"age": 11, "address": "Sesimbra"}, | | 99 | + "Anna": {"age": 9, "address": "Lisbon"}, | | 100 | + } | | 101 | + | | 102 | +1. How many students are in the "students" dict? Use the appropriate function. | | 103 | + | | 104 | +2. Implement a function that receives the students dict and returns the average age. | | 105 | + | | 106 | +3. Implement a function that receives the students dict and an address, and returns a list with names of all students whose address matches the address in the argument. For instance, invoking "find_students(students, ’Lisbon’)" should return Peter and Anna. |
Collapse file Copy file name to clipboard +113Lines changed: 113 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +# Modules and functions | | 2 | + | | 3 | +In this chapter we will talk about modules and functions. A function is a block of code that is used to perform a single action. A module is a Python file containing variables, functions and many more things. | | 4 | + | | 5 | +Start up your Python REPL and let’s use the "math" module which provides access to mathematical functions: | | 6 | + | | 7 | +```Python | | 8 | +>>> import math | | 9 | +>>> math.cos(0.0) | | 10 | +1.0 | | 11 | +>>> math.radians(275) | | 12 | +4.799655442984406 | | 13 | +``` | | 14 | + | | 15 | +Functions are sequences of instructions that are executed when the function is invoked. The following defines the "do\_hello" function that prints two messages when invoked: | | 16 | + | | 17 | +```Python | | 18 | +>>> def do_hello(): | | 19 | +... print("Hello") | | 20 | +... print("World") | | 21 | +... | | 22 | +>>> do_hello() | | 23 | +Hello | | 24 | +World | | 25 | +``` | | 26 | + | | 27 | +Make sure that you insert a tab before both print expressions in the previous function. Tabs and spaces in Python are relevant and define that a block of code is somewhat dependent on a previous instruction. For instance, the print expressions are "inside" the "do\_hello" function therefore must have a tab. | | 28 | + | | 29 | +Functions can also receive parameters a return values (using the "return" keyword): | | 30 | + | | 31 | +```Python | | 32 | +>>> def add_one(val): | | 33 | +... print("Function got value", val) | | 34 | +... return val + 1 | | 35 | +... | | 36 | +>>> value = add_one(1) | | 37 | +Function got value 1 | | 38 | +>>> value | | 39 | +2 | | 40 | +``` | | 41 | + | | 42 | +## Exercises with the math module | | 43 | + | | 44 | +Use the Python documentation about the math module (<https://docs.python.org/3/library/math.html>) to solve the following exercises: | | 45 | + | | 46 | +1. Find the greatest common divisor of the following pairs of numbers: (15, 21), (152, 200), (1988, 9765). | | 47 | + | | 48 | +2. Compute the base-2 logarithm of the following numbers: 0, 1, 2, 6, 9, 15. | | 49 | + | | 50 | +3. Use the "input" function to ask the user for a number and show the result of the sine, cosine and tangent of the number. Make sure that you convert the user input from string to a number (use the int() or the float() function). | | 51 | + | | 52 | +## Exercises with functions | | 53 | + | | 54 | +1. Implement the "add2" function that receives two numbers as arguments and returns the sum of the numbers. Then implement the "add3" function that receives and sums 3 parameters. | | 55 | + | | 56 | +2. Implement a function that returns the greatest of two numbers given as parameters. Use the "if" statement to compare both numbers: <https://docs.python.org/3/tutorial/controlflow.html#if-statements>. | | 57 | + | | 58 | +3. Implement a function named "is\_divisible" that receives two parameters (named "a" and "b") and returns true if "a" can be divided by "b" or false otherwise. A number is divisible by another when the remainder of the division is zero. Use the modulo operator ("%"). | | 59 | + | | 60 | +4. Create a function named "average" that computes the average value of a list passed as parameter to the function. Use the "sum" and "len" functions. | | 61 | + | | 62 | +## Recursive functions | | 63 | + | | 64 | +In computer programming, a recursive function is simply a function that calls itself. For instance take the factorial function. | | 65 | + | | 66 | +\begin{equation} | | 67 | +f(x)=\begin{cases} | | 68 | + 1, & \text{if $x=0$}.\\ | | 69 | + x \times f(x-1), & \text{otherwise}. | | 70 | +\end{cases} | | 71 | +\end{equation} | | 72 | + | | 73 | +As an example, take the factorial of 5: | | 74 | + | | 75 | +\begin{equation} | | 76 | +\begin{split} | | 77 | +5! &= 5 \times 4! \\ | | 78 | + &= 5 \times 4 \times 3! \\ | | 79 | + &= 5 \times 4 \times 3 \times 2! \\ | | 80 | + &= 5 \times 4 \times 3 \times 2 \times 1 \\ | | 81 | + &= 120 | | 82 | +\end{split} | | 83 | +\end{equation} | | 84 | + | | 85 | +Basically, the factorial of 5 is 5 times the factorial of 4, etc. Finally, the factorial of 1 (or of zero) is 1 which breaks the recursion. In Python we could write the following recursive function: | | 86 | + | | 87 | +```Python | | 88 | +def factorial(x): | | 89 | + if x == 0: | | 90 | + return 1 | | 91 | + else: | | 92 | + return x * factorial(x-1) | | 93 | +``` | | 94 | + | | 95 | +The trick with recursive functions is that there must be a "base" case where the recursion must end and a recursive case that iterates towards the base case. In the case of factorial we know that the factorial of zero is one, and the factorial of a number greater that zero will depend on the factorial of the previous number until it reaches zero. | | 96 | + | | 97 | +## Exercises with recursive functions | | 98 | + | | 99 | +1. Implement the factorial function and test it with several different values. Cross-check with a calculator. | | 100 | + | | 101 | +2. Implement a recursive function to compute the sum of the \(n\) first integer numbers (where \(n\) is a function parameter). Start by thinking about the base case (the sum of the first 0 integers is?) and then think about the recursive case. | | 102 | + | | 103 | +3. The Fibonnaci sequence is a sequence of numbers in which each number of the sequence matches the sum of the previous two terms. Given the following recursive definition implement \(fib(n)\). | | 104 | + | | 105 | + \begin{equation} | | 106 | + fib(n)=\begin{cases} | | 107 | + 0, & \text{if $x=0$}.\\ | | 108 | + 1, & \text{if $x=1$}.\\ | | 109 | + fib(n-1) + fib(n-2), & \text{otherwise}. | | 110 | + \end{cases} | | 111 | + \end{equation} | | 112 | + | | 113 | + Check your results for the first numbers of the sequence: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... |
Collapse file Copy file name to clipboard +59Lines changed: 59 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +# Generators | | 2 | + | | 3 | +If you read the previous chapter, you know that iterators are objects that are regularly used with "for" loops. In other others, iterators are objects that implement the iteration protocol. A Python generator is a convenient way to implement an iterator. Instead of a class, a generator is a function which returns a value each time the "yield" keyword is used. Here’s an example of a generator to count the values between two numbers: | | 4 | + | | 5 | +```Python | | 6 | +def myrange(a, b): | | 7 | + while a < b: | | 8 | + yield a | | 9 | + a += 1 | | 10 | +``` | | 11 | + | | 12 | +Like iterators, generators can be used with the "for" loop: | | 13 | + | | 14 | +```Python | | 15 | +>>> for value in myrange(1, 4): | | 16 | +... print(value) | | 17 | +... | | 18 | +1 | | 19 | +2 | | 20 | +3 | | 21 | +``` | | 22 | + | | 23 | +Under the hood, generators behave similarly to iterators: | | 24 | + | | 25 | +```Python | | 26 | +>>> seq = myrange(1,3) | | 27 | +>>> next(seq) | | 28 | +1 | | 29 | +>>> next(seq) | | 30 | +2 | | 31 | +>>> next(seq) | | 32 | +Traceback (most recent call last): | | 33 | + File "<stdin>", line 1, in <module> | | 34 | +StopIteration | | 35 | +``` | | 36 | + | | 37 | +The interesting thing about generators is the "yield" keyword. The "yield" keyword works much like the "return" keyword, but unlike "return", it allows the function to eventually resume its execution. In other words, each time the next value of a generator is needed, Python wakes up the function and resumes its execution from the "yield" line as if the function had never exited. | | 38 | + | | 39 | +Generator functions can use other functions inside. For instance, it is very common to use the "range" function to iterate over a sequence of numbers: | | 40 | + | | 41 | +```Python | | 42 | +def squares(n): | | 43 | + for value in range(n): | | 44 | + yield value * value | | 45 | +``` | | 46 | + | | 47 | +## Exercises with generators | | 48 | + | | 49 | +1. Implement a generator called "squares" to yield the square of all numbers from \(a\) to \(b\). Test it with a "for" loop and print each of the yielded values. | | 50 | + | | 51 | +2. Create a generator to yield all the even numbers from 1 to \(n\). | | 52 | + | | 53 | +3. Create another generator to yield all the odd numbers from 1 to \(n\). | | 54 | + | | 55 | +4. Implement a generator that returns all numbers from \(n\) down to 0. | | 56 | + | | 57 | +5. Create a generator to return the fibonnaci sequence starting from the first element up to \(n\). The first numbers of the sequence are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ... | | 58 | + | | 59 | +6. Implement a generator that returns all consecutive pairs of numbers from 0 to \(n\), such as (0, 1), (1, 2), (2, 3)... |
|