diff --git a/CHANGELOG.md b/CHANGELOG.md index 39cc6c7c9b..ae6b902e5d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -63,6 +63,27 @@ Types of change: - [Html - Link Relative Paths - Change part of PQ as it wasn't worder properly](https://github.com/enkidevs/curriculum/pull/2985) - [Python - Format Text Paragraphs With Textwrap - Make the fill method more clear](https://github.com/enkidevs/curriculum/pull/2981) - [Python - More On Lists - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3005) +- [Python - Classes I - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2992) +- [Python - Looping - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3000) +- [Python - Meet Python - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3003) +- [Python - Python Tips - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3010) +- [Python - Sequential Data Types II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3012) +- [Python - Decorators - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3023) +- [Python - Functional Programming II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3025) +- [Python - String Recipes - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3013) +- [Python - Syntax And Numerical Operators - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3014) +- [Python - Testing - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3015) +- [Python - Unordered Data Types - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3016) +- [Python - Utilities I - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3017) +- [Python - Utilities II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3018) +- [Python - Working With Strings - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3019) +- [Python - Arrays I - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3020) +- [Python - Arrays II - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3021) +- [Python - Comprehension - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3022) +- [Python - Functional Programming - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3024) +- [Python - Generators - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3026) +- [Python - Python Immutability - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3028) +- [Python - Iterators - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/3027) ## January 4th 2022 diff --git a/python/functional-programming/arrays-i/the-reversed-built-in-function.md b/python/functional-programming/arrays-i/the-reversed-built-in-function.md index 6072750eee..bf849dfe4b 100644 --- a/python/functional-programming/arrays-i/the-reversed-built-in-function.md +++ b/python/functional-programming/arrays-i/the-reversed-built-in-function.md @@ -31,7 +31,7 @@ The `reversed` built-in allows us to create an iterator for an iterable sequence reversed(seq) ``` -Where `seq` is an iterable sequence such as a tuple, list, string or range. This returns an iterator which accesses the elements in the sequence in the reverse order. For example, we may use `reversed` to reverse the order of characters in a string. +Where `seq` is an iterable sequence such as a tuple, list, string, or range. This returns an iterator, which accesses the elements in the sequence in the reverse order. For example, we may use `reversed` to reverse the order of characters in a string. ```python ourString = 'enki' @@ -39,7 +39,7 @@ print(list(reversed(ourString))) # Result: ['i', 'k', 'n', 'e'] ``` -Notice how we could create custom classes that implement the `__reversed__()` method and then use `reversed` on them to quickly and efficiently reverse their ordering. In this way we can begin to see how often the `reversed` function might be useful in day-to-day programming tasks. +Notice how we could create custom classes that implement the `__reversed__()` method and then use `reversed` on them to quickly and efficiently reverse their ordering. In this way, we can begin to see how often the `reversed` function might be useful in day-to-day programming tasks. --- diff --git a/python/functional-programming/arrays-i/the-slice-built-in-function.md b/python/functional-programming/arrays-i/the-slice-built-in-function.md index 7fef3fb0db..1dfc4bd811 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,8 +105,7 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', - '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 3c66abce92..7ff2fc725f 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,18 +105,9 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', - 'FR', - 'FR', - 'RU'] -fnames = ['italo', - 'jean', - 'emily', - 'katya'] -lnames = ['calvino', - 'micheal', - 'rambert', - 'sokolov'] +locations = ['IT', 'FR', 'FR', 'RU'] +fnames = ['italo', 'jean', 'emily', 'katya'] +lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index eb43dabe6c..24be068738 100644 --- a/python/functional-programming/arrays-ii/the-map-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-map-built-in-function.md @@ -29,7 +29,7 @@ revisionQuestion: ## Content -The `map` function is built in to the Python language. Together with the other built-in functions `filter` and `reduce`, `map` allows us to take a functional approach to programming in Python. +The `map` function is built into the Python language. Together with the other built-in functions `filter` and `reduce`, `map` allows us to take a functional approach to programming in Python. `map` applies a given function—`function_here` in the case below—iteratively to all items in a given `input_list`[1]. The basic syntax looks like this: @@ -68,8 +68,7 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js', - 'buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js', 'buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 8987a02dd7..86709fed22 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,8 +105,7 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, -'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index d3bb863eee..9ed597844c 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -34,11 +34,11 @@ cube_dict = {x: x ** 3 for x in num_list} ``` -Now if we print cube_dict, we get: +Now, if we print `cube_dict`, we get: ```python for k, v in cube_dict.items(): - print(k, v) + print(k, v) # output # 1 1 # 2 8 @@ -58,17 +58,18 @@ print(lcase_freqs) # partial output ... {'u': 0, 'q': 0, 'w': 0, 'o': 0, \ -'b': 0, 'c': 0, 't': 0, 'h': 0, \ + 'b': 0, 'c': 0, 't': 0, 'h': 0, \ ... -'g': 0, 'a': 0, 'n': 0} + 'g': 0, 'a': 0, 'n': 0} + # Check it is correct: lfk = list(lcase_freqs.keys()) lfk.sort() print(lfk) ['a', 'b', 'c', 'd', 'e', 'f', \ -'g', 'h', 'i', 'j', 'k', 'l', \ -'m', 'n', 'o', 'p','q', 'r', \ -'s', 't', 'u', 'v', 'w', 'x', \ -'y', 'z'] + 'g', 'h', 'i', 'j', 'k', 'l', \ + 'm', 'n', 'o', 'p','q', 'r', \ + 's', 't', 'u', 'v', 'w', 'x', \ + 'y', 'z'] ``` diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index a3689020f2..cfd08dff50 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,8 +97,7 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 \ - ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] ``` - if diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index 5d5e7f4a42..ddc22493c5 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,27 +27,23 @@ Since a list comprehension can take any **expression** as its initial expression These are often useful, but are often used to work with matrices. ```python -matrix = [[1, 2, 3], [4, 5, 6], \ -[7, 8, 9]] - +matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] ``` Say we want to create another matrix with values equal to the squares of each element in the original matrix: ```python -matrix2 = [[x**2 for x in row] for \ -row in matrix] -#matrix2 = [[1, 4, 9], [16, 25, 36],\ -# [49, 64, 81]] +matrix2 = [[x**2 for x in row] for row in matrix] +#matrix2 = [[1, 4, 9], [16, 25, 36], [49, 64, 81]] ``` A more advanced list comprehension with two for clauses and two if clauses: ```python lc = [ (x, y) for x in \ -range(10) if x % 2 == 0 \ -for y in range(20) if \ -y % 3 == 0 ] + range(10) if x % 2 == 0 \ + for y in range(20) if \ + y % 3 == 0 ] # lc # [(0, 0), (0, 3), (0, 6), \ # (0, 9), (0, 12), (0, 15), (0, 18),\ @@ -70,7 +66,6 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python - l = [??? for x in range(10)\ if ??? for y in ???] ``` diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index f9b40726e7..d9efade59d 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,14 +33,12 @@ Imagine we have the following list: ```python my_list = [1, 2, 3, 4, 5, 6, 7, 8] - ``` And we need a set containing only even numbers in the list. This can be easily achieved with **set comprehension**: ```python even_set = {x for x in my_list if x%2 == 0} - ``` We can now check the result: @@ -48,7 +46,6 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} - ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -67,10 +64,8 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python - l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else/ - ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else ??? for x ??? l} ``` - if @@ -88,7 +83,6 @@ new_set = {x ??? x % 2 == 0 else/ What will the `odd_set` look like after we run the following code snippet? ```python - l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index 105042a723..a188eea03f 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,8 +47,7 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() \ - for word in input_list] +lower_list = [word.lower() for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -63,8 +62,7 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? \ - for word in ???] +lower_list = [word.??? for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 972963269e..3c729410a0 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,8 +32,7 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F" - .format(method(self) * 1.8 + 32) + return "{0} F".format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -55,8 +54,7 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F" - .format(method(*args,**kwargs)*1.8+32) + return "{0} F".format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -65,10 +63,8 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, - extra3 = 0): - return self.degrees + extra1 + extra2 - + extra3 + def get_temp(self, extra1, extra2 = 0, extra3 = 0): + return self.degrees + extra1 + extra2 + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 4aaa726e7b..34c06eec99 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,8 +26,7 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

" - .format(string_function(name)) + return "

{0}

".format(string_function(name)) return func_wrapper hello_wrapper = h2_decorate(say_hello) ``` @@ -37,8 +36,7 @@ We can shorten the code and get rid of the variable assignment by introducing th ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

" - .format(string_function(name)) + return "

{0}

".format(string_function(name)) return func_wrapper @h2_decorate @@ -55,8 +53,7 @@ As you can see, the function is decorated, without the need of an explicit `h2_d # variable assignment def say_hello(name): return "Hello, {0}!".format(name) -long_wrap = - div_decorate(h2_decorate(say_hello)) +long_wrap = div_decorate(h2_decorate(say_hello)) print(long_wrap("Mike")) # @ notation @@ -83,8 +80,7 @@ However, this syntax requires an additional enclosing function, as the **decorat def tags_wrapper(tag): def func_decorator(string_function): def name_wrapper(name): - return "<{0}>{1}" - .format(tag, string_function(name)) + return "<{0}>{1}".format(tag, string_function(name)) return name_wrapper return func_decorator diff --git a/python/functional-programming/decorators/functools-wraps.md b/python/functional-programming/decorators/functools-wraps.md index f7bb9b8987..fa119aa85a 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,8 +26,7 @@ For example, for the code below: ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

" \ - .format(string_function(name)) + return "

{0}

".format(string_function(name)) return func_wrapper @h2_decorate @@ -53,8 +52,7 @@ from functools import wraps def h2_decorate(string_function): @wraps(string_function) def func_wrapper(name): - return "

{0}

" - .format(string_function(name)) + return "

{0}

".format(string_function(name)) return func_wrapper print(say_hello.__name__) diff --git a/python/functional-programming/decorators/what-are-decorators.md b/python/functional-programming/decorators/what-are-decorators.md index 2ee86503a0..4d96acdd4d 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,8 +43,7 @@ You could always define another function that makes use of `say_hello`: ```python def hello_heading(name): - return "

{0}

" - .format(say_hello(name)) + return "

{0}

".format(say_hello(name)) ``` Which is perfectly acceptable, but you'd be giving away the opportunity of making your code extensible. What if you are going to need a `say_goodbye` function, formatted in the same way? You'd have to create two more functions: @@ -53,8 +52,7 @@ Which is perfectly acceptable, but you'd be giving away the opportunity of makin def say_goodbye(name): return "Goodbye, {0}!".format(name) def goodbye_heading(name): - return "

{0}

" - .format(say_goodbye(name)) + return "

{0}

".format(say_goodbye(name)) ``` This is not ideal, since all you had done, for each function, was to **decorate** (enhance, manipulate or extend) their output. What if you could write a function that wraps any function's output in `

` tags? @@ -62,8 +60,7 @@ This is not ideal, since all you had done, for each function, was to **decorate* ```python def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

" - .format(string_function(name)) + return "

{0}

".format(string_function(name)) return func_wrapper ``` @@ -87,7 +84,7 @@ If you couldn't figure it out, consider that `h2_decorate`'s references to the ` ## Practice -The number of similar looking functions that can be decorated using the same decorator is +The number of similar-looking functions that can be decorated using the same decorator is ??? @@ -108,13 +105,11 @@ def say_hello(name): return "Hello, {0}!".format(name) # A def hello_heading(name): - return "

{0}

" - .format(say_hello(name)) + return "

{0}

".format(say_hello(name)) # B def hello_heading(func): def func_wrapper(name): - return "

{0}

" - .format(func(name)) + return "

{0}

".format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index c02d6ca751..99e8bf3e6a 100644 --- a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md +++ b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md @@ -35,7 +35,7 @@ Generators allow us to make functions which essentially keep these variables fro ```python def generate_ints(N): for i in range(N): - yield i + yield i ``` This is a simple generator, identified by the `yield` keyword. (Any function with a `yield` is a generator.) When it is called, instead of returning a value, a generator object is returned instead which supports the iterator protocol. Calling `next()` on the generator object will continually run and return the result, "pausing" the function every time after it reaches `yield`. @@ -47,17 +47,14 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and - condition2(element): + if condition1(element) and condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and - condition2(e) else - modify(e) for e in list] +collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index 322447e407..aa719b8053 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( - lambda x: x % 2 == 0,foo)) - ) +print(list(filter( \ + lambda x: x % 2 == 0,foo +))) # Output: [2, 4, 6] ``` @@ -108,10 +108,9 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list( - filter( - lambda x: x / 2 == 1 ,foo - )) +result = list(filter( \ + lambda x: x / 2 == 1 ,foo +)) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index aabb6f9c03..bcf09a4880 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```plain-text +```python def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```plain-text +```python # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,8 +99,7 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power( - power_of_two(), 4))) +print(list(n_power(power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ecd93de7f6..ea9b3d8141 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index d010cc6313..cb18f961a9 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index 74998ca833..a521d85162 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index 9e8f8cd2df..a70cd4d28b 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,9 +36,7 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print( - list( - itertools.chain(letters, numbers))) +print(list(itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -48,10 +46,7 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print( - list( - itertools.filterfalse( - lambda x: 2 < x < 7, numbers))) +print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -62,9 +57,7 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print( - list( - itertools.compress(numbers, boolean))) +print(list(itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -86,26 +79,18 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = -iter( - itertools.???( - discounts, isInSale)) +discountIterator = iter(itertools.???(discounts, isInSale)) -fullPricesInSale = -itertools.compress(prices, isInSale) +fullPricesInSale = itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print( - list( - itertools.???( - lambda x: f(x), fullPricesInSale))) +print(list(itertools.???(lambda x: f(x), fullPricesInSale))) -print( - list(salePrices)) +print(list(salePrices)) ``` - `compress` @@ -125,16 +110,10 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', - 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print( - list( - itertools.islice( - itertools.cycle( - itertools.compress( - names, boolean)), 0, 6))) +print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index 6cd8958632..f83c4d831e 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,8 +33,7 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have - less than zero items in the basket!""") + raise ValueError("""You can't have less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -44,8 +43,7 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + - str(self.itemcount) + " items.") + return("Shopping Basket with " + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -92,9 +90,7 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection( - http.client.HTTPConnection( - "httpbin.org", 80)) +conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 41028ca9e8..12ef6c24e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} + IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} practiceQuestion: formats: - fill-in-the-gap @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 5e91664bd1..10d592e97d 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,10 +41,8 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request( - self.method, "/") - self.result = - self.httpconnection.getresponse() + self.httpconnection.request(self.method, "/") + self.result = self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 7c118d4965..3d24ad72d8 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index c46e623a7e..b7eb62504a 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,8 +61,7 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}" - .format(self.name, self.idnum)) + print("{0} is employee no. {1}".format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index d82ec7a030..bdd02dd8b1 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 1bf0802c0f..20d39ce860 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,8 +30,7 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}" - .format(self.name, self.idnum)) + print("{0} is employee no. {1}".format(self.name, self.idnum)) ``` To create an instance of the class: @@ -67,8 +66,7 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}" - .format(self.name, self.idnum)) + print("{0} is employee no. {1}".format(self.name, self.idnum)) steve = ???('???') ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 0ecb749d1b..4559ef31be 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -29,12 +29,12 @@ For example: ```python x = 5 while (x > 0): - if (x == 2): - # exit the loop - # when x equals 2 - break - print(x) - x = x - 1 + if (x == 2): + # exit the loop + # when x equals 2 + break + print(x) + x = x - 1 print("Broken away!") ``` @@ -50,7 +50,7 @@ Broken away! Python's `continue` statement is used to skip only one iteration[1] of a loop. -The code execution will proceed to the beginning of next loop iteration. +The code execution will proceed to the beginning of the next loop iteration. For example, here's how we can print only odd numbers by skipping every even loop iteration: diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 8b6f66ad04..448d8d2e2c 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 2ef3a3fad2..7cca772a89 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 3764220c60..185ecf2c0f 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index fddf5854b2..50fca2d674 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 9e142357ba..4410bfd850 100644 --- a/python/python-core/meet-python/what-is-python.md +++ b/python/python-core/meet-python/what-is-python.md @@ -34,9 +34,9 @@ For example, here's how you might check whether a number is greater than another my_age = 23 legal_age = 21 if my_age >= legal_age: - print("You can have a beer!") + print("You can have a beer!") else: - print("Unlucky.") + print("Unlucky.") ``` @@ -44,7 +44,6 @@ Python is also a *general-purpose* programming language. That means it can be us You can use it to build websites, web apps and desktop apps. But it's also used in scientific computing, artificial intelligence, and data analysis! - > 💬 Why are you interested in Python? > > Leave a comment or view some of the other comments for inspiration before moving on. @@ -62,7 +61,7 @@ Let's write some Python code! Do you remember how to print a message? my_age = 20 legal_age = 18 if my_age >= legal_age: - ???("Enjoy the ride!") + ???("Enjoy the ride!") ``` - print diff --git a/python/python-core/playing-with-time/datetime-module.md b/python/python-core/playing-with-time/datetime-module.md index c2c43047c3..71d526775b 100644 --- a/python/python-core/playing-with-time/datetime-module.md +++ b/python/python-core/playing-with-time/datetime-module.md @@ -4,7 +4,7 @@ type: normal category: feature links: - >- - [docs.python.org](https://docs.python.org/3.5/library/datetime.html){website} + [docs.python.org](https://docs.python.org/3.10/library/datetime.html){website} practiceQuestion: formats: - fill-in-the-gap diff --git a/python/python-core/python-tips/dynamic-typing.md b/python/python-core/python-tips/dynamic-typing.md index c8aa72110e..54efba0cde 100644 --- a/python/python-core/python-tips/dynamic-typing.md +++ b/python/python-core/python-tips/dynamic-typing.md @@ -20,7 +20,7 @@ revisionQuestion: ## Content -Unlike in statically-typed programming language, Python variables are dynamically typed. That means that a variable (e.g. `x`) can take the value of a number, a string or even a function, but not at the same time. +Unlike in statically-typed programming language, Python variables are dynamically-typed. That means that a variable (e.g. `x`) can take the value of a number, a string, or even a function, but not simultaneously. Some people consider Python's dynamic typing a weakness as it can lead to hard to find bugs. @@ -33,7 +33,7 @@ def x(): pass ``` -In Python, variables do not represent a portion of computer's memory where their value is written, but *tags* pointing to objects. +In Python, variables do not represent a portion of a computer's memory where their value is written, but *tags* pointing to objects. Keep in mind that it is a **bad practice** to use the same variable name for different data types. Instead, use meaningful names for variables. diff --git a/python/python-core/python-tips/exiting-the-interpreter.md b/python/python-core/python-tips/exiting-the-interpreter.md index 43ae3c9f1f..d46c17c665 100644 --- a/python/python-core/python-tips/exiting-the-interpreter.md +++ b/python/python-core/python-tips/exiting-the-interpreter.md @@ -68,7 +68,7 @@ sys.??? ## Revision -What is the key stroke for exiting python interpreter (REPL)? +What is the keyboard shortcut for exiting python interpreter (REPL)? ??? diff --git a/python/python-core/python-tips/following-pep-8-styling-guideline.md b/python/python-core/python-tips/following-pep-8-styling-guideline.md index 828f5d33dc..554012c428 100644 --- a/python/python-core/python-tips/following-pep-8-styling-guideline.md +++ b/python/python-core/python-tips/following-pep-8-styling-guideline.md @@ -23,10 +23,10 @@ revisionQuestion: ## Content -The most common and standard styling guideline for Python is known as PEP 8. -It is designed to improve readability. +Python's most common and standard styling guideline is PEP 8, designed to improve readability. + +It can, however, be quite strict (e.g. in the case of whitespaces). -It can however be quite strict (e.g. in the case of whitespaces). For instance, this is OK in PEP 8: ```python @@ -47,8 +47,7 @@ Raymond Hettinger's word of wisdom: "Do not PEP 8 unto others; only PEP 8 thy self. Don't let PEP 8 make you insanely intolerant of other people's code." -To PEP 8 yourself, use a linter and an autoformatter. These -exist for all the popular editors. +To PEP 8 yourself, use a linter and an autoformatter. These exist for all the popular editors. --- diff --git a/python/python-core/python-tips/pretty-print-data-structures.md b/python/python-core/python-tips/pretty-print-data-structures.md index 5f43c11b21..034009fcd1 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -50,7 +50,7 @@ for x in range(4): print(pprint.pformat(data, width=19)) ``` -Instead of a single line our output will be: +Instead of a single line, our output will be: ```python [(0, {0: 0, 1: 1}), @@ -78,8 +78,7 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) - for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/sequential-data-types-ii/del-statement-for-lists.md b/python/python-core/sequential-data-types-ii/del-statement-for-lists.md index eb00b22f63..bbdb1b21f4 100644 --- a/python/python-core/sequential-data-types-ii/del-statement-for-lists.md +++ b/python/python-core/sequential-data-types-ii/del-statement-for-lists.md @@ -54,7 +54,7 @@ print(a) Note that `[0:2]` does not include the item at index `2`. -We can also use `del` to delete all of the items inside a `list`, or the whole object itself: +We can also use `del` to delete all of the items inside a `list` or the whole object itself: ```python # delete all the items diff --git a/python/python-core/sequential-data-types-ii/python-lists.md b/python/python-core/sequential-data-types-ii/python-lists.md index 4e6fbfc56a..b3effbf3ac 100644 --- a/python/python-core/sequential-data-types-ii/python-lists.md +++ b/python/python-core/sequential-data-types-ii/python-lists.md @@ -25,7 +25,7 @@ revisionQuestion: A list is a **sequential data type** that acts as a container for objects. -Lists are separated by commas and *must be wrapped in square brackets*, `[ ]`. +Lists are separated by commas, and *must be wrapped in square brackets*, `[ ]`. ```python my_first_list = ['apples', 'oranges'] diff --git a/python/python-core/sequential-data-types-ii/ranges.md b/python/python-core/sequential-data-types-ii/ranges.md index fde9ffa956..422cdd40fa 100644 --- a/python/python-core/sequential-data-types-ii/ranges.md +++ b/python/python-core/sequential-data-types-ii/ranges.md @@ -43,7 +43,7 @@ list(range(1, 10)) # [1, 2, 3, 4, 5, 6, 7, 8, 9] ``` -The first argument here is where the range starts, and second argument is where it ends. This second argument is *not inclusive*. +The first argument here is where the range starts, and the second argument is where it ends. This second argument is *not inclusive*. > Notice how the range function doesn't automatically generate the `list`. When using Python 3 we must always pass our range to the `list` method first. diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index 84efead07d..e5b3e7b395 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,9 +29,7 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize\ - ('NFKD', data).\ - encode('ASCII', 'ignore') +normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index eeca38504e..47b9648e51 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/string-recipes/stringprep-module.md b/python/python-core/string-recipes/stringprep-module.md index 831952f246..69bf36d48f 100644 --- a/python/python-core/string-recipes/stringprep-module.md +++ b/python/python-core/string-recipes/stringprep-module.md @@ -28,7 +28,7 @@ The **RFC 3454** international memo defines the procedure of *preparing* Unicode Often, it is necessary to compare identifications for things such as **host names** for **equality**. -The main purpose of **RFC 3454** is providing a framework for ensuring string input and comparison work for users throughout the world. +The main purpose of **RFC 3454** is to provide a framework for ensuring string input and comparison work for users throughout the world. Python provides the `stringprep` module filled with static methods used for checking if your input is in the specified **RFC 3454** table. diff --git a/python/python-core/syntax-and-numerical-operators/arithmetic-operators.md b/python/python-core/syntax-and-numerical-operators/arithmetic-operators.md index cc91b18343..d9ebc54ead 100644 --- a/python/python-core/syntax-and-numerical-operators/arithmetic-operators.md +++ b/python/python-core/syntax-and-numerical-operators/arithmetic-operators.md @@ -56,7 +56,7 @@ If you want to perform floor division to return an `int`, use the `//` operator: # 6 ``` -When using the `//` operator, you only return the whole number part of the division. Any digits after the decimal point will be removed. +When using the `//` operator, you only return the whole number part of the division. Digits after the decimal point are removed. --- diff --git a/python/python-core/syntax-and-numerical-operators/python-variables.md b/python/python-core/syntax-and-numerical-operators/python-variables.md index da1693076d..7079c658e8 100644 --- a/python/python-core/syntax-and-numerical-operators/python-variables.md +++ b/python/python-core/syntax-and-numerical-operators/python-variables.md @@ -34,7 +34,7 @@ number = 10 number = 100 ``` -Initially the value of `number` was `10`. Later it was changed to `100`. +Initially, the value of `number` was `10`. Later it was changed to `100`. ```python print(number) diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index 6b0d411dbb..ddcbb3e606 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index f1c178e5c8..f2b05b66e7 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,24 +36,23 @@ We will define a class that implements one method that returns the product of tw ```python class Calculator: - def multiply(self, a, b): - time.sleep(10) - return a * b + def multiply(self, a, b): + time.sleep(10) + return a * b ``` If we would run a basic **unittest** on this class, it'll take `10` seconds plus the actual testing time to finish the test. Let's define a **unittest** using a mock example: -```plain-text +```python from unittest import TestCase from unittest.mock import patch class TestCalculator(TestCase): - @patch('main.Calculator.multiply', - return_value=9) - def test_multiply(self, multiply): - self.assertEqual(multiply(2,3), 9) + @patch('main.Calculator.multiply', return_value=9) + def test_multiply(self, multiply): + self.assertEqual(multiply(2,3), 9) ``` We are importing the `patch` decorator[1] from `unittest.mock`. It replaces the actual `multiply` function with a **mock function** that behaves exactly how we want it to. In this case, our **mock function** always returns `9`. During the lifetime of our **test**, the `multiply` function is replaced with its **mocked version**. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index aae3d34d00..6b112f23c2 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example we'll **run** the test with `-v` (verbose) flag: +For this example, we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/testing/pytest.md b/python/python-core/testing/pytest.md index 53b14f0c13..3479c0e571 100644 --- a/python/python-core/testing/pytest.md +++ b/python/python-core/testing/pytest.md @@ -32,11 +32,11 @@ Note that for pytest to run the assertion function, it has to start with `test_` ```python # multiply_pytest.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` The test can be run issuing the following command[1]: @@ -75,7 +75,7 @@ The **output** is split into two main parts. The first half contains information - the number of **tests** collected from that file; - the label: `F` if tests fail, or `P` if they pass. -If any **test** fails, then pytest will generate the second part. This part shows the line that causes each **test case** to fail, marked by the `>` sign. Furthermore, it gives a detailed explanation of the **assertion** and finally it states what type of **error** was encountered. +If any **test** fails, then pytest will generate the second part. This part shows the line that causes each **test case** to fail, marked by the `>` sign. Furthermore, it gives a detailed explanation of the **assertion**, and finally, it states what type of **error** was encountered. --- diff --git a/python/python-core/testing/unit-testing.md b/python/python-core/testing/unit-testing.md index 07a00f9374..986c32bb00 100644 --- a/python/python-core/testing/unit-testing.md +++ b/python/python-core/testing/unit-testing.md @@ -33,7 +33,6 @@ Consider the following example: import unittest class SimplisticTest(unittest.TestCase): - def test_True(self): self.assertTrue(True) diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index 6afd2d6d44..b58d06a0a7 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -31,11 +31,9 @@ revisionQuestion: ```python square_numbers.keys() - # dict_keys([1, 2, 3, 4, 5]) square_numbers.values() - # dict_values([1, 4, 9, 16, 25]) ``` @@ -43,16 +41,15 @@ square_numbers.values() ```python square_numbers.pop(1) - # 1 print(square_numbers) # {2: 4, 3: 9, 4: 16, 5: 25} ``` -- `popitem()` removes the last item that was inserted in the dictionary, and returns it. +- `popitem()` removes the last item that was inserted in the dictionary and returns it. -> For versions prior to Python 3.7, `popitem()` removed an arbitrary item from the dictionary. For more information check out the links in the "Learn More" section. +> For versions prior to Python 3.7, `popitem()` removed an arbitrary item from the dictionary. For more information, check out the links in the "Learn More" section. ```python square_numbers.popitem() @@ -95,8 +92,7 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???( - [1, 2, 3, 4, 5], ???) +new_dictionary = ???.???([1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 57d4e2cec9..07273fb6c8 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,7 +95,6 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python - animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/unordered-data-types/set-methods.md b/python/python-core/unordered-data-types/set-methods.md index fcc30f99d5..8282db0168 100644 --- a/python/python-core/unordered-data-types/set-methods.md +++ b/python/python-core/unordered-data-types/set-methods.md @@ -48,13 +48,13 @@ print(my_set) # {'rabbit', 'parrot', 'cat', 'horse', 'dog'} ``` -As you can see, *duplicate* values aren't added to `my_set`. Also note how the *order of items doesn't matter*. +As you can see, *duplicate* values aren't added to `my_set`. Also, note how the *order of items doesn't matter*. To remove items, we can use: - `discard()` -> removes an item if it exists and does nothing if it does not -- `remove()` -> removes an item if it exists, but raises an error if it does not exist. +- `remove()` -> removes an item if it exists but raises an error if it does not exist. ```python my_set.remove('dog') diff --git a/python/python-core/utilities-i/check-available-python-modules.md b/python/python-core/utilities-i/check-available-python-modules.md index 5c3a6e78d1..1b94eb491d 100644 --- a/python/python-core/utilities-i/check-available-python-modules.md +++ b/python/python-core/utilities-i/check-available-python-modules.md @@ -28,13 +28,13 @@ revisionQuestion: ## Content -Find a list of all python modules installed on a machine by running the following command in a terminal. +Find a list of all Python modules installed on a machine by running the following command in a terminal. ```bash pydoc modules ``` -Or, inside of a python interactive shell: +Or, inside of a Python interactive shell: ```python >>> help('modules') @@ -45,7 +45,7 @@ Or, inside of a python interactive shell: ## Practice -Complete the following command such that when used in the Python interactive shell it will show all modules installed on the machine: +Complete the following command such that when used in the Python interactive shell, it will show all modules installed on the machine: ```py >>> ???('???') @@ -63,7 +63,7 @@ Complete the following command such that when used in the Python interactive she ## Revision -What command/s can be ran in **a terminal*** in order to see all Python modules installed on the machine? +What command can be used in **a terminal*** to see all Python modules installed on the machine? ??? diff --git a/python/python-core/utilities-i/schedule-events-with-sched.md b/python/python-core/utilities-i/schedule-events-with-sched.md index f2d04938e1..c61d691bf0 100644 --- a/python/python-core/utilities-i/schedule-events-with-sched.md +++ b/python/python-core/utilities-i/schedule-events-with-sched.md @@ -22,7 +22,7 @@ revisionQuestion: ## Content -Another useful **Python** module is `sched` and it's used for general purpose event scheduling. +Another useful **Python** module is `sched`, and it's used for general-purpose event scheduling. Import the module: @@ -31,7 +31,7 @@ import sched import time # we will use this ``` -Every operation is done with the help of a `scheduler` class that needs two time functions. The first one to determine the current time and the second to wait for a specific period of time. (e.g. `time.time` and `time.sleep`) +Every operation is done with the help of a `scheduler` class that needs two-time functions. The first one to determine the current time and the second to wait for a specific period of time. (e.g. `time.time` and `time.sleep`) ```python s = sched.scheduler(time.time, time.sleep) @@ -55,7 +55,7 @@ Then we run our scheduler: s.run() ``` -`first` is printed after 2 seconds while `second` is printed after 3 seconds. +`first` is printed after 2 seconds, and the `second` after 3 seconds. --- @@ -92,7 +92,7 @@ Given the scheduler code: ```python sched.enter(3,2,print,argument=('second',)) ``` -What is the priority and what the delay? +What is the priority, and what is the delay? ```python # Priority ??? # Delay ??? diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index e6dbc06ebc..58026056a2 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -54,13 +54,13 @@ print(cal) The output will look like this: ```plain-text - January 2016 - Mo Tu We Th Fr Sa Su - 1 2 3 - 4 5 6 7 8 9 10 - 11 12 13 14 15 16 17 - 18 19 20 21 22 23 24 - 25 26 27 28 29 30 31 + January 2016 +Mo Tu We Th Fr Sa Su + 1 2 3 + 4 5 6 7 8 9 10 +11 12 13 14 15 16 17 +18 19 20 21 22 23 24 +25 26 27 28 29 30 31 ``` @@ -77,9 +77,9 @@ To print a whole year's calendar: print(calendar.calendar(2016)) ``` -Output not shown since it is too large. +The output is not shown since it is too large. -This module provide other useful methods for working with dates, times and calendars such as `calendar.isleap` (checks if a year is a leap year). +This module provides other useful methods for working with dates, times, and calendars, such as `calendar.isleap` (checks if a year is a leap year). --- @@ -89,8 +89,7 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.??? \ - (calendar.MONDAY) +calendar.???(calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index fd20f3e393..18babf7bff 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/get-the-similarity-ratio-of-two-sequences.md b/python/python-core/utilities-ii/get-the-similarity-ratio-of-two-sequences.md index 4397eae47b..59b0de40fb 100644 --- a/python/python-core/utilities-ii/get-the-similarity-ratio-of-two-sequences.md +++ b/python/python-core/utilities-ii/get-the-similarity-ratio-of-two-sequences.md @@ -21,7 +21,7 @@ revisionQuestion: ## Content -`difflib`'s `SequenceMatcher` class and its ratio method makes it easy to compute the "similarity" of two sequences. +`difflib`'s `SequenceMatcher` class and its ratio method make it easy to compute the "similarity" of two sequences. ```python import difflib @@ -42,7 +42,7 @@ With the output: 40.0 ``` -*Junk* sequences (such as whitespace or blank lines) can be passed as the first argument of the function, for them not to be taken into account. The default value is `None`, when nothing is ignored. +*Junk* sequences (such as whitespace or blank lines) can be passed as the first argument of the function, for them not to be taken into account. The default value is `None` when nothing is ignored. It can be used to compare sequences of characters as well, i.e. strings. diff --git a/python/python-core/utilities-ii/use-struct-to-work-with-binary-data.md b/python/python-core/utilities-ii/use-struct-to-work-with-binary-data.md index 3a8260883c..2f1c0aee74 100644 --- a/python/python-core/utilities-ii/use-struct-to-work-with-binary-data.md +++ b/python/python-core/utilities-ii/use-struct-to-work-with-binary-data.md @@ -29,7 +29,7 @@ revisionQuestion: ## Content -Python's `struct` module has routines for converting between binary and text data, in both directions. +Python's `struct` module has routines for converting between binary and text data in both directions. Import the module: diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index c992d3fc8d..6b862df0d7 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,8 +29,7 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, \ - " abcd", "abcd abcd") +s = SequenceMatcher(None, " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -51,8 +50,7 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", - " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -65,8 +63,7 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, - “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index 83bb0b5be4..f09723f249 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,8 +57,7 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) \ - for elt in somelist] +slist = [some_function(elt) for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/string-formatting.md b/python/python-core/working-with-strings/string-formatting.md index 0ff0486dcd..889bb8dcfa 100644 --- a/python/python-core/working-with-strings/string-formatting.md +++ b/python/python-core/working-with-strings/string-formatting.md @@ -53,7 +53,7 @@ print(a_string) # Learning Python with Enki, workout number 3. ``` -As you can see, the `format` method takes in the replacements as arguments, and returns the formatted string. Another useful feature of this method is that you can decide which argument is replaced, by using indexes: +As you can see, the `format` method takes in the replacements as arguments and returns the formatted string. Another useful feature of this method is that you can decide which argument is replaced by using indexes: ```py app = 'Enki' diff --git a/python/python-core/working-with-strings/string-operations.md b/python/python-core/working-with-strings/string-operations.md index f8c3b722f0..f4e50558a5 100644 --- a/python/python-core/working-with-strings/string-operations.md +++ b/python/python-core/working-with-strings/string-operations.md @@ -23,7 +23,7 @@ revisionQuestion: Strings are bits of text either defined with 'single' or "double" quotations. Python has a number of built-in methods which perform a variety of operations on strings. -First we'll declare a string for method testing purposes: +First, we'll declare a string for method testing purposes: ```python testString = 'operations' diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 7554291e53..191401d6d7 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,10 +73,8 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string - .???("It's ???weather") -print(t - .???(weather="sunny")) +t = string.???("It's ???weather") +print(t.???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -105,8 +103,7 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string - .???(???="evening")) +print(my_string.???(???="evening")) ``` - `format`