From 5784a814947f724eeaa2fb601135386edc01b5f9 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:37:56 +0100 Subject: [PATCH 01/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 79 files changed, 469 insertions(+), 362 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From d5a973ff646c3695f2225f04ff13fe67db103b06 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 16:38:31 +0100 Subject: [PATCH 02/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..e091b033db 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 9602d2bf187620638cfe3130b92d89fe97cb8c55 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:11:34 +0100 Subject: [PATCH 03/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 78 files changed, 448 insertions(+), 338 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From eee64e083c3e9a89c133a468ca2ffb00363d820c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:12:57 +0100 Subject: [PATCH 04/60] update gramar --- python/python-core/looping/break-and-continue-statements.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..4559ef31be 100644 --- a/python/python-core/looping/break-and-continue-statements.md +++ b/python/python-core/looping/break-and-continue-statements.md @@ -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: From a243c04ea04b6d17b6a9ad081b09c71959b52506 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:13:47 +0100 Subject: [PATCH 05/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..b13cdaf352 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From c8f33435e763802a1c7f4a12f48e9dc18034a0c5 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:32:56 +0100 Subject: [PATCH 06/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 83 files changed, 489 insertions(+), 379 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 7cb6a064759ca9c7c9f8e20a5854a1482f40b16c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:33:08 +0100 Subject: [PATCH 07/60] update indentation --- python/python-core/meet-python/what-is-python.md | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) 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 From d73be9e31b14e24837d6416572f4302922656d76 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 17:33:47 +0100 Subject: [PATCH 08/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..8b0066deea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From e4dd53fcec21dff5a70c10ae1ceebe3fc1e20729 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:26:48 +0100 Subject: [PATCH 09/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 487 insertions(+), 378 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From ff451a6ace71566fd0793688bff37f5a5ff5830e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:27:15 +0100 Subject: [PATCH 10/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..51d417ea8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 6633817e620807f10f54fe6dc9d2f71c142ad153 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:27:21 +0100 Subject: [PATCH 11/60] minor grammar improvements --- python/python-core/python-tips/dynamic-typing.md | 4 ++-- .../python-core/python-tips/exiting-the-interpreter.md | 2 +- .../python-tips/following-pep-8-styling-guideline.md | 9 ++++----- .../python-tips/pretty-print-data-structures.md | 2 +- 4 files changed, 8 insertions(+), 9 deletions(-) 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 143a3f7067..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}), From c83fdb45b2e01249c055a14df1d6835661b3a81b Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:32:54 +0100 Subject: [PATCH 12/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 83 files changed, 489 insertions(+), 379 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From cadaa160bdc2aeff4075817ea223afea94ab50b5 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:34:18 +0100 Subject: [PATCH 13/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..10fb71cf9d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 388e1e8e346f9d78238b48246a90d60282f66047 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:34:28 +0100 Subject: [PATCH 14/60] minor grammar improvements --- .../sequential-data-types-ii/del-statement-for-lists.md | 2 +- python/python-core/sequential-data-types-ii/python-lists.md | 2 +- python/python-core/sequential-data-types-ii/ranges.md | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) 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. From 6d48d05edbe8c21d3647a9305f5d4a5abb468e60 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:39:11 +0100 Subject: [PATCH 15/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 485 insertions(+), 377 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From a1e04b6e338caa2b4ef19a11e0bdf3266cb424ea Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:39:17 +0100 Subject: [PATCH 16/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..7bd5d2bfcb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 2f88e7a08280edf9a0d145a3984f7521ff97bcf8 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:40:34 +0100 Subject: [PATCH 17/60] minor grammar improvement --- python/python-core/string-recipes/stringprep-module.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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. From b45878aa71dbacc35f1822460abcfec304190641 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:42:31 +0100 Subject: [PATCH 18/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 83 files changed, 489 insertions(+), 379 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 73a93458d0815270f5bdaafb021ed26ce89aeb90 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:42:36 +0100 Subject: [PATCH 19/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..84b1c5fb5b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 806726e55b8de307cdf27218e8693b6af887183f Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:45:51 +0100 Subject: [PATCH 20/60] minor grammar improvements --- .../syntax-and-numerical-operators/arithmetic-operators.md | 2 +- .../syntax-and-numerical-operators/python-variables.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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) From f83dd62735c48b81b95c757726e231eb851f3982 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:48:50 +0100 Subject: [PATCH 21/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 +++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 +++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++++--- .../comprehension/set-comprehension.md | 8 +++- ...r-loop-using-map-or-list-comprehensions.md | 8 ++-- .../decorators/decorators-methods.md | 12 ++++-- .../decorators/decorators-syntax.md | 12 ++++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++++--- .../functional-particularities-of-python.md | 7 +++- .../what-is-functional-programming.md | 13 ++++--- .../generators/generator-of-generators.md | 7 ++-- .../generators/recursive-generator.md | 16 ++++---- .../generators/yield-and-next.md | 14 +++---- .../iterators/the-iteration-protocol.md | 28 ++++++------- .../iterators/the-itertools-module-ii.md | 39 ++++++++++++++----- .../atomicity-of-failure.md | 10 +++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++++------ .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 ++++---- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++--- .../python-core/classes-i/creating-classes.md | 5 ++- .../classes-i/method-overriding.md | 16 ++++---- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++--- .../classes-iii/dynamically-create-types.md | 11 ++++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 +++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++++------ .../control-flow-i/if-statements.md | 14 +++---- .../indentation-and-commenting.md | 14 +++---- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 ++-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 ++++----- .../the-from-import-statement.md | 14 ++++--- .../debugging-with-print.md | 34 ++++++++-------- .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 +++++----- .../looping/break-and-continue-statements.md | 12 +++--- python/python-core/looping/for-loops.md | 12 +++--- .../python-core/looping/looping-techniques.md | 12 +++--- .../looping/using-else-in-loops.md | 36 ++++++++--------- python/python-core/looping/while-loops.md | 10 ++--- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++++----- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 +++--- .../python-functions/defining-functions.md | 14 +++---- .../python-functions/nested-functions.md | 34 ++++++++-------- .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 +++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 +++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 +++-- 80 files changed, 455 insertions(+), 345 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 844415b384a263ddc7187516f52ecba6eee3dab3 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:49:07 +0100 Subject: [PATCH 22/60] minor grammar and indentation improvements --- python/python-core/testing/mocking-tests.md | 9 ++++----- python/python-core/testing/pytest.md | 8 ++++---- python/python-core/testing/unit-testing.md | 1 - 3 files changed, 8 insertions(+), 10 deletions(-) diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index fead0beeff..f2b05b66e7 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -45,15 +45,14 @@ If we would run a basic **unittest** on this class, it'll take `10` seconds plus 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/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) From 3a9c04e1ee8bd7d97eba58d64936cb2d8ca9cb7c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:50:00 +0100 Subject: [PATCH 23/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..34c58fe31b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From ba4d53f2b24e2ab86f9e7bc8e5f6ee7ce2b80104 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:53:15 +0100 Subject: [PATCH 24/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 486 insertions(+), 378 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 1d6b82800a2c41a5f2925fab7fbc1ec9e9cf5ba5 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:53:22 +0100 Subject: [PATCH 25/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..ccc2ae791e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From dea76ebeafd556653a202508198c355fa250406c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:53:31 +0100 Subject: [PATCH 26/60] minor improvements --- .../unordered-data-types/dictionary-methods-ii.md | 7 ++----- python/python-core/unordered-data-types/set-methods.md | 4 ++-- 2 files changed, 4 insertions(+), 7 deletions(-) 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 cc09ed173f..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() 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') From 6f454329b029e227a36ccc3fac45f28fd345c848 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:55:23 +0100 Subject: [PATCH 27/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 487 insertions(+), 378 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 2eedbbe65f270447cdf81241d3d4be2567417032 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 18:55:29 +0100 Subject: [PATCH 28/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..dc22bd1594 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 72d9d93f7112284683f6fe1ab915af2fbfc9cd94 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:01:06 +0100 Subject: [PATCH 29/60] minor grammar improvements --- .../check-available-python-modules.md | 8 ++++---- .../utilities-i/schedule-events-with-sched.md | 8 ++++---- .../utilities-i/your-own-python-calendar.md | 18 +++++++++--------- 3 files changed, 17 insertions(+), 17 deletions(-) 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 65cf9f6775..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). --- From 41dd34aa7e55c6e0e6acea264ba9e6182fb206a8 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:03:26 +0100 Subject: [PATCH 30/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 482 insertions(+), 375 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From bd0e11daa828abeda74e25f4d317b6348804cb5a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:04:31 +0100 Subject: [PATCH 31/60] minor grammar updates --- .../utilities-ii/get-the-similarity-ratio-of-two-sequences.md | 4 ++-- .../utilities-ii/use-struct-to-work-with-binary-data.md | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) 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: From 33397acb812a722eaaea1b3726b2eefd0e7e2609 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:04:37 +0100 Subject: [PATCH 32/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..ae94d870fb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 4ac0a159880f5643a78c5c65b3e367ae228c545e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:07:18 +0100 Subject: [PATCH 33/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- 81 files changed, 481 insertions(+), 375 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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` From 3d8621d91a4983252679fdc0ef18e7ff9e3e0b66 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:07:24 +0100 Subject: [PATCH 34/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..4ddbb65c07 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 5d773ba7adadecda8b319151886d3469d93d0189 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:07:31 +0100 Subject: [PATCH 35/60] minor grammar improvements --- python/python-core/working-with-strings/string-formatting.md | 2 +- python/python-core/working-with-strings/string-operations.md | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) 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' From 5b5484e8a0760464dfb31ef92b2d71cf0981087f Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:10:55 +0100 Subject: [PATCH 36/60] revert other folders --- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 475 insertions(+), 375 deletions(-) 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From a269899e05e980d8a3037df3c5fbcb684eea7e60 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:11:29 +0100 Subject: [PATCH 37/60] minor grammar improvements --- .../arrays-i/the-reversed-built-in-function.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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. --- From 4116e31f85d4b9f49f0f66a3a97b3a999fe96397 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:11:35 +0100 Subject: [PATCH 38/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..69ccdc00b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From ff4f11bbdb8e997fa1cffe89ba66a01ae9d50b0f Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:14:10 +0100 Subject: [PATCH 39/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 485 insertions(+), 377 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 2daad363cec2e12a90d4114b0a0fc9b56119c600 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:14:25 +0100 Subject: [PATCH 40/60] minor grammar improvements --- .../arrays-ii/the-map-built-in-function.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 9f60eb2eb9..a0f4c4fa55 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: From 75fed3c9cdcbd175242b995754a7ced90f4fbbe6 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:14:43 +0100 Subject: [PATCH 41/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..c3378a2ccb 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 3c107d8b36bf9ef02cc3807e59784eb9fd98e683 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:16:59 +0100 Subject: [PATCH 42/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 78 files changed, 458 insertions(+), 362 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From fbb73f7b7c71c530842a7403552881f5af7f3281 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:17:11 +0100 Subject: [PATCH 43/60] add space for consistency --- .../comprehension/dictionary-comprehension.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index 83839cd5a1..9ed597844c 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -34,7 +34,7 @@ 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(): @@ -60,7 +60,8 @@ print(lcase_freqs) {'u': 0, 'q': 0, 'w': 0, 'o': 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() From 2a1df8d3fe8dba92819abc7548a2cf3a6d003a4c Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:17:43 +0100 Subject: [PATCH 44/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..9f1e2edca9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From efd963eb6a43bde33e14011533a0f81c4f498e6a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:20:20 +0100 Subject: [PATCH 45/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 79 files changed, 458 insertions(+), 363 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 3627d41878b214e3166e72de765af0a2dafda17e Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:20:42 +0100 Subject: [PATCH 46/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..d2dc3ece53 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 57e5e6ff9da7654d5721f98e7724808fd708a221 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:22:49 +0100 Subject: [PATCH 47/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 482 insertions(+), 373 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 66944196ab8f55a6d7aeb42cd4843182cc3f4575 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:22:58 +0100 Subject: [PATCH 48/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..2e96531945 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From cd3a69079ed0e745eba5d1327b48f60462c78a0d Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:24:54 +0100 Subject: [PATCH 49/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 82 files changed, 484 insertions(+), 377 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From ec6801e721e7163dccdaf6c0c82f1dbbc0956afb Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:25:54 +0100 Subject: [PATCH 50/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..54eb1712af 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 735b24ec962ff35fade8ba223bd36acd05e1b2c6 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:26:05 +0100 Subject: [PATCH 51/60] remove extra spacing --- .../functional-particularities-of-python.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 1d6a67ebb4..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`. From 111d2f7d6f905535c36db8164032b31471e8ccca Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:30:34 +0100 Subject: [PATCH 52/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../iterators/the-iteration-protocol.md | 28 +++++----- .../iterators/the-itertools-module-ii.md | 39 ++++++++++---- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 80 files changed, 470 insertions(+), 361 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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 f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From 6a422887ebb36827e1b2c99a5ad6e108caa75215 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:30:40 +0100 Subject: [PATCH 53/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..f361cc1883 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From 8f0a8be16118dfbcd1836aa7a31a11c7edc35135 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:32:28 +0100 Subject: [PATCH 54/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 ++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 ++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++--- .../comprehension/set-comprehension.md | 8 ++- ...r-loop-using-map-or-list-comprehensions.md | 8 +-- .../decorators/decorators-methods.md | 12 +++-- .../decorators/decorators-syntax.md | 12 +++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++--- .../functional-particularities-of-python.md | 7 ++- .../what-is-functional-programming.md | 13 ++--- .../generators/generator-of-generators.md | 7 +-- .../generators/recursive-generator.md | 16 +++--- .../generators/yield-and-next.md | 14 ++--- .../atomicity-of-failure.md | 10 ++-- ...tinguish-the-mutability-of-common-types.md | 6 +-- .../why-types-have-immutability-ii.md | 6 ++- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 81 files changed, 445 insertions(+), 356 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index f83c4d831e..6cd8958632 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,7 +33,8 @@ 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): @@ -43,7 +44,8 @@ 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: @@ -90,7 +92,9 @@ 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 12ef6c24e8..41028ca9e8 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://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} + IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){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 10d592e97d..5e91664bd1 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,8 +41,10 @@ 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/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From cc392d9aacbc0ba44e4b7e7b5d05653fc63f18a2 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:32:38 +0100 Subject: [PATCH 55/60] open changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..9c3f501df8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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 From 0760130659e4d00a2bed28faee3ad7ca54c25d16 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:34:11 +0100 Subject: [PATCH 56/60] revert other folders --- .../advanced-queues/prioritize-your-queue.md | 24 ++++----- .../advanced-queues/queue-s-and-threads.md | 3 +- .../context-manager-types-with.md | 17 +++--- .../advanced-referencing/weakref-proxies.md | 4 +- .../how-to-open-a-file-object.md | 3 +- .../basic-file-manipulation/writing-files.md | 3 +- .../bytearray-objects.md | 3 +- .../python-core/classes-i/class-keywords.md | 10 ++-- .../python-core/classes-i/creating-classes.md | 5 +- .../classes-i/method-overriding.md | 16 +++--- python/python-core/classes-i/using-classes.md | 6 ++- .../classes-ii/classes-ii-discussion.md | 6 ++- .../python-core/classes-ii/method-objects.md | 4 +- .../classes-ii/private-variables.md | 10 ++-- .../classes-iii/dynamically-create-types.md | 11 ++-- ...ecial-attributes-of-objects-and-classes.md | 2 +- .../control-flow-i/boolean-operators.md | 12 ++--- .../control-flow-i/if-elif-else-statements.md | 24 ++++----- .../control-flow-i/if-statements.md | 14 ++--- .../indentation-and-commenting.md | 14 ++--- .../control-flow-i/intro-to-booleans.md | 4 +- .../control-flow-ii/the-in-operator.md | 8 +-- .../control-flow-ii/the-not-operator.md | 2 +- .../best-way-to-implement-a-simple-queue.md | 3 +- .../double-ended-queues-with-deque.md | 4 +- .../enhance-your-tuple-s.md | 3 +- .../intro-to-modules/namespace-and-scoping.md | 18 +++---- .../the-from-import-statement.md | 14 ++--- .../debugging-with-print.md | 34 ++++++------ .../errors-and-execeptions.md | 4 +- .../python-debugger-ii.md | 21 ++++---- .../looping/break-and-continue-statements.md | 12 ++--- python/python-core/looping/for-loops.md | 12 ++--- .../python-core/looping/looping-techniques.md | 12 ++--- .../looping/using-else-in-loops.md | 36 ++++++------- python/python-core/looping/while-loops.md | 10 ++-- .../python-core/meet-python/what-is-python.md | 6 +-- .../dictionaries-from-lists.md | 3 +- .../keep-things-in-order-with-ordereddict.md | 2 +- .../more-on-lists/using-lists-as-queues.md | 20 +++---- .../playing-with-time/playing-with-time.md | 3 +- .../playing-with-time/time-object.md | 3 +- .../python-functions/calling-functions.md | 12 ++--- .../python-functions/defining-functions.md | 14 ++--- .../python-functions/nested-functions.md | 34 ++++++------ .../python-functions/the-return-statement.md | 4 +- ...om-item-from-a-list-tuple-data-stucture.md | 7 ++- .../pretty-print-data-structures.md | 3 +- .../recipe-to-normalize-text.md | 4 +- .../string-recipes/regular-expressions.md | 2 +- python/python-core/testing/doctests.md | 54 +++++++++---------- python/python-core/testing/mocking-tests.md | 6 +-- python/python-core/testing/nose-testing.md | 8 +-- .../dictionary-methods-ii.md | 3 +- .../dictionary-standard-mapping-type.md | 1 + .../utilities-i/your-own-python-calendar.md | 3 +- .../coroutine-utility-function.md | 2 +- .../utilities-ii/working-with-junk-data.md | 9 ++-- .../efficient-concatenation-with-join.md | 3 +- ...s-to-substitute-a-substring-of-a-string.md | 9 ++-- 60 files changed, 320 insertions(+), 283 deletions(-) diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index 99ace65af3..b1e82b6f0b 100644 --- a/python/python-core/advanced-queues/prioritize-your-queue.md +++ b/python/python-core/advanced-queues/prioritize-your-queue.md @@ -31,18 +31,18 @@ It uses the sort method `sort` in order to decide what to retrieve from it first import queue class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority < other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority < other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 3 / 55 / 100 ``` @@ -52,18 +52,18 @@ If we want to reverse the sorting order (greatest priority first), we would have ```python class Enki(object): - def __init__(self, priority): - self.priority = priority - return - def __lt__(self, other): - return self.priority > other.priority + def __init__(self, priority): + self.priority = priority + return + def __lt__(self, other): + return self.priority > other.priority q = queue.PriorityQueue() q.put(Enki(55)) q.put(Enki(3)) q.put(Enki(100)) while not q.empty(): - print(q.get().priority) + print(q.get().priority) # output is 100 / 55 / 3 ``` diff --git a/python/python-core/advanced-queues/queue-s-and-threads.md b/python/python-core/advanced-queues/queue-s-and-threads.md index 6f6c45bc8b..19798a81b6 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,7 +80,8 @@ Complete the code snippet: q = Queue() ??? = 3 # declare 3 threads for i in range(num_threads): - worker = ???(target=enki, args=(q,)) + worker = ??? \ + (target=enki, args=(q,)) worker.setDaemon(True) worker.start() ``` diff --git a/python/python-core/advanced-referencing/context-manager-types-with.md b/python/python-core/advanced-referencing/context-manager-types-with.md index 0388fa6d5f..f6692adf6c 100644 --- a/python/python-core/advanced-referencing/context-manager-types-with.md +++ b/python/python-core/advanced-referencing/context-manager-types-with.md @@ -56,13 +56,13 @@ To implement a custom **context manager**, two methods must be implemented: ```python class my_context_manager: def __enter__(self): - # set up things - return thing + # set up things + return thing def __exit__(self,type,value,traceback): - # deal with unmanaged resources + # deal with unmanaged resources #.... with my_context_manager as custom_name - # work with resources + # work with resources ``` @@ -80,10 +80,11 @@ Complete the code snippet to implement a context manager: ```python class new_context_manager: def ???(self): - # set up things - return thing - def ???(self, type, value, traceback): - # deal with unmanaged resources + # set up things + return thing + def ???(self, type, + value, traceback): + # deal with unmanaged resources with new_context_manager as custom_name # work with resources diff --git a/python/python-core/advanced-referencing/weakref-proxies.md b/python/python-core/advanced-referencing/weakref-proxies.md index 4e04c6d1c3..7c3e2b0a97 100644 --- a/python/python-core/advanced-referencing/weakref-proxies.md +++ b/python/python-core/advanced-referencing/weakref-proxies.md @@ -29,8 +29,8 @@ The difference is that proxies can be used without calling the `ref` first to ac import weakref class Enki(object): - def __init__(self, arg): - self.arg = arg + def __init__(self, arg): + self.arg = arg enki = Enki('arg') r = weakref.ref(enki) diff --git a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md index 73cb44b3a5..b51e4f6225 100644 --- a/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md +++ b/python/python-core/basic-file-manipulation/how-to-open-a-file-object.md @@ -30,7 +30,8 @@ revisionQuestion: Consider the following syntax: ```python -obj = open(f_name, [access_mode], [buffering]) +obj = open(f_name, [access_mode], + [buffering]) ``` Here's the disambiguation of its arguments: diff --git a/python/python-core/basic-file-manipulation/writing-files.md b/python/python-core/basic-file-manipulation/writing-files.md index 2c37539a54..19da4a6441 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,7 +39,8 @@ text = open(path, 'w+') Writing to the **file** can be done via the `write()` function. A single **string** may be passed as as **argument**, which will be written to the **file**. You can **split** the **string** into multiple lines by adding `\n` character where necessary. ```python -in = 'This is one line\n This is the second one.' +in = 'This is one line\n + This is the second one.' text.write(in) text.seek(0) print(text.read()) diff --git a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md index 272e72cc48..8ecbfb8cce 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,7 +80,8 @@ bytearray(b'.\xf0\xf1\xf2') Convert the bytearray object into a hexadecimal string: ```python ->>> ???(b'\xf0\xf1\xf2').???() +>>> ???(b'\xf0\xf1\xf2') \ + .???() 'f0f1f2' ``` diff --git a/python/python-core/classes-i/class-keywords.md b/python/python-core/classes-i/class-keywords.md index 3d24ad72d8..7c118d4965 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 b7eb62504a..c46e623a7e 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,7 +61,8 @@ 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 bdd02dd8b1..d82ec7a030 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 20d39ce860..1bf0802c0f 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,7 +30,8 @@ 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: @@ -66,7 +67,8 @@ 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/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index f4c3b37f47..da0dd34314 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,10 +65,12 @@ Then, add the two methods: ```python # Example 1 def perimeter(self): - return print("The perimeter of the given rectangle is", self.length * 2 + self.width * 2) + return print("The perimeter of the given rectangle is",\ + self.length * 2 + self.width * 2) def area(self): - return print("The area of the given rectangle is", self.length * self.width) + return print("The area of the given rectangle is",\ + self.length * self.width) # Example 2 diff --git a/python/python-core/classes-ii/method-objects.md b/python/python-core/classes-ii/method-objects.md index 7c70b63e0c..fda41bb480 100644 --- a/python/python-core/classes-ii/method-objects.md +++ b/python/python-core/classes-ii/method-objects.md @@ -52,8 +52,8 @@ Considering the following class and its instantiation: ```python class Enki: - def f(self): - return "Python" + def f(self): + return "Python" enki = Enki() diff --git a/python/python-core/classes-ii/private-variables.md b/python/python-core/classes-ii/private-variables.md index c44ac05871..663e5674df 100644 --- a/python/python-core/classes-ii/private-variables.md +++ b/python/python-core/classes-ii/private-variables.md @@ -31,9 +31,9 @@ Consider the `Enki` class: ```python class Enki: - def __init__(self): - self.__private = 3.14 - print(self.__private) + def __init__(self): + self.__private = 3.14 + print(self.__private) enki = Enki() # prints 3.14 @@ -63,8 +63,8 @@ What is the output of the following snippet? ```python class Test: - def __init__(self): - self.__x = "hey there" + def __init__(self): + self.__x = "hey there" t = Test() print(t.__x) ??? diff --git a/python/python-core/classes-iii/dynamically-create-types.md b/python/python-core/classes-iii/dynamically-create-types.md index c2a25bb467..537bbda277 100644 --- a/python/python-core/classes-iii/dynamically-create-types.md +++ b/python/python-core/classes-iii/dynamically-create-types.md @@ -40,7 +40,7 @@ This `type` function takes three arguments: - `bases` - list of superclasses - `dict` - dictionary of attributes -These two classes implement the same functionality although syntactically different: +These two classes implement the same functionality although syntacticly different ```python # The name is set to "BigCar" @@ -55,9 +55,12 @@ def Car_init(self, name): self.name = name # We can choose the name of a class -SmallCar = type("BigCar", (), \ -{"counter": 0, "__init__": Car_init, \ -"beep": lambda self: "Beep " + self.name}) +SmallCar = type("BigCar", + (), + {"counter": 0, + "__init__": Car_init, + "beep": lambda self: "Beep " + + self.name}) ``` So now these two classes are practically identical (`__name__` property is also equal), the only difference can be seen in types, which does not affect the functionality: diff --git a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md index 498a74b85d..7158dae9d7 100644 --- a/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md +++ b/python/python-core/classes-iii/special-attributes-of-objects-and-classes.md @@ -34,7 +34,7 @@ Suppose we have the class: ```python class Enki: - pi = 3.14 + pi = 3.14 ``` Get all **writable** attributes of your `class object`: diff --git a/python/python-core/control-flow-i/boolean-operators.md b/python/python-core/control-flow-i/boolean-operators.md index 47fb50ac2c..75ca7b1ec3 100644 --- a/python/python-core/control-flow-i/boolean-operators.md +++ b/python/python-core/control-flow-i/boolean-operators.md @@ -32,7 +32,7 @@ num = 1 a_string = 'foobar' if a_string == 'foobar' and num == 1: - print('Success!') + print('Success!') # Success! ``` @@ -42,7 +42,7 @@ When using the `and` operator, *all conditions* must evaluate to `True` for the ```python if a_string == 'foobar' or num > 2: - print('Success!') + print('Success!') # Success! ``` @@ -69,9 +69,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'python': - print ('yes') + print ('yes') else: - print('no') + print('no') # 'yes' ``` @@ -92,9 +92,9 @@ x = 6 a_string = 'python' if x == 6 ??? a_string == 'java': - print ('yes') + print ('yes') else: - print('no') + print('no') ``` - `or` diff --git a/python/python-core/control-flow-i/if-elif-else-statements.md b/python/python-core/control-flow-i/if-elif-else-statements.md index 22b0c84ff1..1a31d5823f 100644 --- a/python/python-core/control-flow-i/if-elif-else-statements.md +++ b/python/python-core/control-flow-i/if-elif-else-statements.md @@ -29,11 +29,11 @@ In terms of syntax, this is written as `elif`. It's shorthand for `else if`. ```python if condition: - print('do something') + print('do something') elif condition: - print('do something else') + print('do something else') else: - print('do some other thing') + print('do some other thing') ``` If the condition for `if` has not been met, the program will check the `elif`. If it meets this condition it will execute the `elif` body of code. @@ -43,11 +43,11 @@ The `else` code is only executed if none of the other conditions have been met. ```python num = 0 if num > 0: - print('Positive number') + print('Positive number') elif num == 0: - print('Zero') + print('Zero') else: - print('Negative number') + print('Negative number') ``` If we assign the value 0 to `num`, our program above will print `'Zero'`. @@ -65,11 +65,11 @@ Complete the following `if` statement to return `'You're at the start of a great days_coding = 2 if days_coding == 7: - print("You've been coding for a week!") + print("You've been coding for a week!") ??? days_coding ??? 7: - print("More than a week - keep it up!") + print("More than a week - keep it up!") ???: - print("You're at the start of a great journey!") + print("You're at the start of a great journey!") ``` - `elif` @@ -90,11 +90,11 @@ What does the following code snippet print? name = 'George' if name == 'Stefan': - print("Hey Stefan") + print("Hey Stefan") elif name == 'Andrei': - print('Hey Andrei') + print('Hey Andrei') else: - print("Hey, what's your name?") + print("Hey, what's your name?") ``` ??? diff --git a/python/python-core/control-flow-i/if-statements.md b/python/python-core/control-flow-i/if-statements.md index 119cab5fcc..fc8ca7852b 100644 --- a/python/python-core/control-flow-i/if-statements.md +++ b/python/python-core/control-flow-i/if-statements.md @@ -34,7 +34,7 @@ The program will only execute the code *if the condition has been met*. ```python num = 3 if num > 0: - print(num, " is a positive number") + print(num, " is a positive number") ``` The code above will print `'3 is a positive number'`. @@ -44,9 +44,9 @@ The `if` statement can be extended to include a *catch-all*, `else`, that will b ```python num = 1 if num == 0: - print("Zero") + print("Zero") else: - print("Positive number") + print("Positive number") ``` The code above will print `'Positive number'`. @@ -74,9 +74,9 @@ What does the following code snippet print? ```python x = 3 if x < 3: - print ('small') + print ('small') else: - print ('big') + print ('big') ``` ??? @@ -95,9 +95,9 @@ What does the following code snippet print? ```python x = 8 if (x == 8): - print ('true') + print ('true') else: - print ('false') + print ('false') ``` ??? diff --git a/python/python-core/control-flow-i/indentation-and-commenting.md b/python/python-core/control-flow-i/indentation-and-commenting.md index a4e9d23261..55a062c193 100644 --- a/python/python-core/control-flow-i/indentation-and-commenting.md +++ b/python/python-core/control-flow-i/indentation-and-commenting.md @@ -31,9 +31,9 @@ For example: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') + print('This will not be printed.') print('What about this one?') ``` @@ -48,10 +48,10 @@ If we were to rewrite the above snippet as: ```python if True: - print('Will print this.') + print('Will print this.') else: - print('This will not be printed.') - print('What about this one?') + print('This will not be printed.') + print('What about this one?') ``` The output will be: @@ -78,9 +78,9 @@ What will this code print? ```python if True: - print('this is true') + print('this is true') else: - print('this is false') + print('this is false') ``` ```plain-text diff --git a/python/python-core/control-flow-i/intro-to-booleans.md b/python/python-core/control-flow-i/intro-to-booleans.md index 10094cb93e..62fbe19bac 100644 --- a/python/python-core/control-flow-i/intro-to-booleans.md +++ b/python/python-core/control-flow-i/intro-to-booleans.md @@ -42,9 +42,9 @@ This means that once an `if` statement condition evaluates to `True`, the indent hungry = 'very' if hungry == 'very': - print('Get some food!') + print('Get some food!') else: - print("I bet you're hungry now!") + print("I bet you're hungry now!") ``` Here, `'Get some food!'` is printed because the condition above evaluates to `True`. diff --git a/python/python-core/control-flow-ii/the-in-operator.md b/python/python-core/control-flow-ii/the-in-operator.md index f011837d28..b9d67ec901 100644 --- a/python/python-core/control-flow-ii/the-in-operator.md +++ b/python/python-core/control-flow-ii/the-in-operator.md @@ -42,9 +42,9 @@ string = 'Python' sentence = "Python's the best language to learn!" if string in sentence: - print('I agree!') + print('I agree!') else: - print('Hmm, not sure I agree.') + print('Hmm, not sure I agree.') # I agree! ``` @@ -63,9 +63,9 @@ letter = 'p' my_string = 'stop, collaborate and listen' if letter ??? my_string: - print('???') + print('???') else: - print('???') + print('???') ``` - `in` diff --git a/python/python-core/control-flow-ii/the-not-operator.md b/python/python-core/control-flow-ii/the-not-operator.md index 2a5d0bdd5d..aa5e7bee1f 100644 --- a/python/python-core/control-flow-ii/the-not-operator.md +++ b/python/python-core/control-flow-ii/the-not-operator.md @@ -60,7 +60,7 @@ word = 'list' sentence = 'we know about numbers, strings and booleans' ??? word ??? in sentence: - print("Let's learn some more data types!") + print("Let's learn some more data types!") ``` - `if` diff --git a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md index 5144ebdaf7..a6ec81ba89 100644 --- a/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md +++ b/python/python-core/deep-into-collections/best-way-to-implement-a-simple-queue.md @@ -67,7 +67,8 @@ Complete the code snippet so that the queue reads Enki: ```python from collections import deque -queue = deque(["i", "n", "k", "i"]) +queue = deque(["i", "n", \ + "k", "i"]) queue.??? queue.??? diff --git a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md index 7830513e69..929beac058 100644 --- a/python/python-core/deep-into-collections/double-ended-queues-with-deque.md +++ b/python/python-core/deep-into-collections/double-ended-queues-with-deque.md @@ -64,8 +64,8 @@ Starting from Python `3.1` you can limit the maximum numbers of elements in a `d d = deque(maxlen=3) deque([], maxlen=3) for i in range(4): - d.append(i) - print(d) + d.append(i) + print(d) ... # Output: deque([0], maxlen=3) diff --git a/python/python-core/deep-into-collections/enhance-your-tuple-s.md b/python/python-core/deep-into-collections/enhance-your-tuple-s.md index 0b7e4179dd..4910c6608c 100644 --- a/python/python-core/deep-into-collections/enhance-your-tuple-s.md +++ b/python/python-core/deep-into-collections/enhance-your-tuple-s.md @@ -112,7 +112,8 @@ print(A._asdict()) Convert the `namedtuple` into an `OrderedDict` : ```python -question = ???('Practice', 'a b c') +question = ???('Practice', \ + 'a b c') p = question(a = 10, b = 5, c = 2) print(p.???()) # OrderedDict([('a', 10), \ diff --git a/python/python-core/intro-to-modules/namespace-and-scoping.md b/python/python-core/intro-to-modules/namespace-and-scoping.md index f70d9d75c7..166717de16 100644 --- a/python/python-core/intro-to-modules/namespace-and-scoping.md +++ b/python/python-core/intro-to-modules/namespace-and-scoping.md @@ -63,12 +63,12 @@ To make this easier to understand consider the following example: ```python def f(): - s = 'A local variable' - print(s) # print() is built-in - def g(): - x = 'An enclosed variable' - print(x) # print() is built-in - g() + s = 'A local variable' + print(s) # print() is built-in + def g(): + x = 'An enclosed variable' + print(x) # print() is built-in + g() r = 'A global variable' @@ -93,7 +93,7 @@ Consider the following snippet. In what scope do you think `z` is in? ```python def foo(x): - return x*x + return x*x z = foo(4) ``` @@ -114,8 +114,8 @@ Is the variable `a` still in scope when it is printed? ```python def foo(): - a = "Hello World" - return a + a = "Hello World" + return a b = foo() print(a) diff --git a/python/python-core/intro-to-modules/the-from-import-statement.md b/python/python-core/intro-to-modules/the-from-import-statement.md index 14a4735835..006f65124d 100644 --- a/python/python-core/intro-to-modules/the-from-import-statement.md +++ b/python/python-core/intro-to-modules/the-from-import-statement.md @@ -34,12 +34,12 @@ Consider the following module: # my_functions.py def hello(what): - text = "Hello, " + what - print(text) + text = "Hello, " + what + print(text) def cube(x): - print(x ** 3) + print(x ** 3) def quad(x): - print(x ** 4) + print(x ** 4) ``` To access exposed methods of it we could do the following: @@ -96,7 +96,8 @@ def ??? ```python # main.py -??? ??? ??? subtract ??? ??? +??? ??? ??? subtract + ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -124,7 +125,8 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? ??? +??? ??? ??? + ??? radius = 10 height = 30 diff --git a/python/python-core/is-your-python-healthy/debugging-with-print.md b/python/python-core/is-your-python-healthy/debugging-with-print.md index 0571ceed30..8ab6215644 100644 --- a/python/python-core/is-your-python-healthy/debugging-with-print.md +++ b/python/python-core/is-your-python-healthy/debugging-with-print.md @@ -33,13 +33,13 @@ Usually, developers start by printing everything for a better understanding: **w Consider the following example: ```python -def foo(): - return 6 -x = foo() -while(True): - x += 1 -if x > 19: - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 while(True): +5 x += 1 +6 if x > 19: +7 print("Welcome!") ``` Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have only an `if` statement to check. @@ -47,16 +47,16 @@ Let's suppose we wanted `"Welcome!"` to be printed. In this simple case, we have A **useful trick** for debugging is printing the value of `x` and following the execution of the code: ```python -def foo(): - return 6 -x = foo() -print("Line 4, x= ", x) -while(True): - x += 1 -print("Line 7, x=", x) -if x > 19: - print("Line 9, x=", x) - print("Welcome!") +1 def foo(): +2 return 6 +3 x = foo() +4 print("Line 4, x= ", x) +5 while(True): +6 x += 1 +7 print("Line 7, x=", x) +8 if x > 19: +9 print("Line 9, x=", x) +10 print("Welcome!") # Line 4, x=6 ``` diff --git a/python/python-core/is-your-python-healthy/errors-and-execeptions.md b/python/python-core/is-your-python-healthy/errors-and-execeptions.md index c86389266b..ee12d62a2b 100644 --- a/python/python-core/is-your-python-healthy/errors-and-execeptions.md +++ b/python/python-core/is-your-python-healthy/errors-and-execeptions.md @@ -43,8 +43,8 @@ Indentation in Python is very important. We want the **variable** to be assigned ```python def func(): - value = 5 - return value + value = 5 + return value ``` However, even if the code is *syntactically correct*, we can still encounter errors when executing the program. Errors detected while executing the program are called **exceptions**. There are types of exceptions which cause the program to stop executing and types of exceptions which can be handled. diff --git a/python/python-core/is-your-python-healthy/python-debugger-ii.md b/python/python-core/is-your-python-healthy/python-debugger-ii.md index 21e11dba4a..62bbe43866 100644 --- a/python/python-core/is-your-python-healthy/python-debugger-ii.md +++ b/python/python-core/is-your-python-healthy/python-debugger-ii.md @@ -29,16 +29,17 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list --> num_list = [1, 2] - chars = ['a', 'b'] - - def nested_loop(): - for nr in num_list: - print(nr) - for char in chars: - print(char) - - if __name__ == '__main__': +1 -> num_list = [1, 2] +2 chars = ['a', 'b'] +3 +4 +5 def nested_loop(): +6 for nr in num_list: +7 print(nr) +8 for char in chars: +9 print(char) +10 +11 if __name__ == '__main__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 311ffd3036..0ecb749d1b 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!") ``` diff --git a/python/python-core/looping/for-loops.md b/python/python-core/looping/for-loops.md index 448d8d2e2c..8b6f66ad04 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 7cca772a89..2ef3a3fad2 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 185ecf2c0f..3764220c60 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 50fca2d674..fddf5854b2 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 5da6e32326..9e142357ba 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.") ``` @@ -62,7 +62,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/more-on-dictionaries/dictionaries-from-lists.md b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md index 4d0e9d86f0..e30123c761 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,7 +87,8 @@ Suppose we have the following lists. We want to know the temperature in UK. Fill countries = ['USA','UK','SP'] temp = ['28','29','30'] -new = ???(???(countries,temp)) +new = ???(???( + countries,temp)) new.???('USA') new.pop('SP') diff --git a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md index 6e74742786..fd25872cb6 100644 --- a/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md +++ b/python/python-core/more-on-dictionaries/keep-things-in-order-with-ordereddict.md @@ -100,7 +100,7 @@ e['n'] = 'N' e['k'] = 'K' e['i'] = 'I' for k, v in e.???(): - print(k, v) + print(k, v) # e E / n N / k K / i I ``` diff --git a/python/python-core/more-on-lists/using-lists-as-queues.md b/python/python-core/more-on-lists/using-lists-as-queues.md index 6f36cb8534..32cb9768e0 100644 --- a/python/python-core/more-on-lists/using-lists-as-queues.md +++ b/python/python-core/more-on-lists/using-lists-as-queues.md @@ -37,20 +37,20 @@ Let's define a **queue** class now: ```py class Queue: - def __init__(self): - self.items = [] + def __init__(self): + self.items = [] - def isEmpty(self): - return self.items == [] + def isEmpty(self): + return self.items == [] - def enqueue(self, item): - self.items.insert(0,item) + def enqueue(self, item): + self.items.insert(0,item) - def dequeue(self): - return self.items.pop() + def dequeue(self): + return self.items.pop() - def size(self): - return len(self.items) + def size(self): + return len(self.items) ``` > 💡 Instead of `size` you can use `__len__`. It will allow you to use `len(myQueue)` instead of `myQueue.size()`. Check the *Learn More* section for a playground link. We've prepared both queue classes in there so you can test them out and decide which one you want to use. diff --git a/python/python-core/playing-with-time/playing-with-time.md b/python/python-core/playing-with-time/playing-with-time.md index fbabccd549..1edc2f9d16 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,7 +38,8 @@ The `time.time()` function returns the **current time** in **seconds** since "th ```python cur_time = time.time() -print("Seconds since Unix Epoch: ", cur_time) +print("Seconds since Unix Epoch: ", + cur_time) # ('Seconds since Unix Epoch: ', # 1498231656.509076) diff --git a/python/python-core/playing-with-time/time-object.md b/python/python-core/playing-with-time/time-object.md index ce03c40ee0..5ba58d6bc7 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,7 +112,8 @@ from ??? import date, time t = time() print(t == time.???) # True -print(t.???(23,59,59,999999) == time.???) # True +print(t.???(23,59,59,999999) + == time.???) # True d = ???(1991, 12, 25) print(d.???) # 12 diff --git a/python/python-core/python-functions/calling-functions.md b/python/python-core/python-functions/calling-functions.md index 1d36d14164..f3e51fe3f7 100644 --- a/python/python-core/python-functions/calling-functions.md +++ b/python/python-core/python-functions/calling-functions.md @@ -27,7 +27,7 @@ For example: ```python # To define def new_func(): - print ('Function time!') + print ('Function time!') # To call new_func() @@ -46,8 +46,8 @@ In this example, variable `x` is defined in the function as a parameter: ```python def func(x): - ans = x * x - print(ans) + ans = x * x + print(ans) ``` To call this function, you must pass a value (i.e. an argument) into it, which will put that value into the `x` variable (i.e. parameter) inside the function. @@ -80,7 +80,7 @@ Complete the code to define and call the `mean` function to get the arithmetic m x = 4 y = 2 ??? mean(a, b): - print((a + b) / 2) + print((a + b) / 2) ???(???) ``` @@ -99,8 +99,8 @@ Complete the code snippet to define and call the function with the correct param ```python ??? cube(x): - res = x * x * x - print (res) + res = x * x * x + print (res) num = 5 ???(???) diff --git a/python/python-core/python-functions/defining-functions.md b/python/python-core/python-functions/defining-functions.md index e2ed7fd9a0..743f22b19d 100644 --- a/python/python-core/python-functions/defining-functions.md +++ b/python/python-core/python-functions/defining-functions.md @@ -29,15 +29,15 @@ Functions in Python use Python's standard block syntax: ```python block-head: - block line 1 - block line 2 + block line 1 + block line 2 ``` Functions in Python are defined using the `def` keyword, and as explained above follow Python's block syntax. In the example below a function called `new_function` is defined with a simple print method inside: ```python def new_function(): - print('Function defined!') + print('Function defined!') ``` @@ -50,21 +50,21 @@ Which of the following syntaxes is correct for defining Python functions: ```python # 1 def function1(): - # function code… + # function code… # 2 def function2() { - # function code… + # function code… } # 3 def function 3( - # function code… + # function code… } # 4 def function 4() - # function code… + # function code… # ??? diff --git a/python/python-core/python-functions/nested-functions.md b/python/python-core/python-functions/nested-functions.md index 74aaa932f5..71fd62c058 100644 --- a/python/python-core/python-functions/nested-functions.md +++ b/python/python-core/python-functions/nested-functions.md @@ -27,10 +27,10 @@ For example: ```python def out_func(num): - def in_func(num): - return num + 1 - num_1 = in_func(num) - print(num, num_1) + def in_func(num): + return num + 1 + num_1 = in_func(num) + print(num, num_1) ``` The `in_func` function is nested within the `out_func` function and is inaccessible from outside of the `out_func` functions scope. @@ -59,10 +59,10 @@ What’s the output to the following function call: ```python def outer(num): - def inner(num): - return num - 2 - nums = inner(num) - print(num, nums) + def inner(num): + return num - 2 + nums = inner(num) + print(num, nums) outer(3) ``` @@ -97,17 +97,17 @@ We've defined a nested function here. What will the following code output? ```python def some_function(num): - def nested_func(num): - return num + 1 - num_1 = nested_func(num) - print(num, num_1) + def nested_func(num): + return num + 1 + num_1 = nested_func(num) + print(num, num_1) def some_new_function(num): - def nested_func_new(num): - return num*2 - num_1 = nested_func(num) - num_2 = nested_func_new(num) - print(num, num_1, num_2) + def nested_func_new(num): + return num*2 + num_1 = nested_func(num) + num_2 = nested_func_new(num) + print(num, num_1, num_2) some_new_function(1) ``` diff --git a/python/python-core/python-functions/the-return-statement.md b/python/python-core/python-functions/the-return-statement.md index c2aec940fc..c7422125ea 100644 --- a/python/python-core/python-functions/the-return-statement.md +++ b/python/python-core/python-functions/the-return-statement.md @@ -29,8 +29,8 @@ Here is an example using a return statement: ```python def return_func(): - print ('Print!') - return 'Return!' + print ('Print!') + return 'Return!' print(return_func()) ``` diff --git a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md index 505c9d3f67..7bec37881d 100644 --- a/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md +++ b/python/python-core/python-recipes/a-simple-way-to-select-a-random-item-from-a-list-tuple-data-stucture.md @@ -28,7 +28,8 @@ If you need to randomly select an item from a list: ```python import random items = ['here', 'to', 'one', 'strings'] -rand_item = items[random.randrange(len(items))] +rand_item = +items[random.randrange(len(items))] ``` Use `randrange` (or `randint`) to generate a pseudo-random integer from the range indicated by it's arguments. @@ -36,7 +37,9 @@ Use `randrange` (or `randint`) to generate a pseudo-random integer from the rang 2) Naive approach 2: ```python -rand_items = [items[random.randrange(len(items))] for item in range(4)] +rand_items = +[items[random.randrange(len(items))] + for item in range(4)] ``` Use `random.randrange` to generate indexes inside a list comprehension. 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 143a3f7067..5f43c11b21 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,7 +78,8 @@ 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/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index e5b3e7b395..84efead07d 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,7 +29,9 @@ 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 47b9648e51..eeca38504e 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/testing/doctests.md b/python/python-core/testing/doctests.md index ddcbb3e606..6b0d411dbb 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 fead0beeff..f1c178e5c8 100644 --- a/python/python-core/testing/mocking-tests.md +++ b/python/python-core/testing/mocking-tests.md @@ -36,9 +36,9 @@ 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. diff --git a/python/python-core/testing/nose-testing.md b/python/python-core/testing/nose-testing.md index 6b112f23c2..aae3d34d00 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/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index cc09ed173f..6afd2d6d44 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,7 +95,8 @@ 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 07273fb6c8..57d4e2cec9 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,6 +95,7 @@ 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/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index 65cf9f6775..e6dbc06ebc 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,7 +89,8 @@ 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 18babf7bff..fd20f3e393 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/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index 6b862df0d7..c992d3fc8d 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,7 +29,8 @@ 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) @@ -50,7 +51,8 @@ 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) ``` @@ -63,7 +65,8 @@ 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 f09723f249..83bb0b5be4 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,7 +57,8 @@ 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/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 191401d6d7..7554291e53 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,8 +73,10 @@ 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?": @@ -103,7 +105,8 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string.???(???="evening")) +print(my_string + .???(???="evening")) ``` - `format` From eff426abfd76827082b84852f8fbef588bb32157 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:34:18 +0100 Subject: [PATCH 57/60] update changelog --- CHANGELOG.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 2461deccbe..91e56b3a00 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -57,7 +57,7 @@ Types of change: ### Changed - [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 - All Applicable Insights - Move single-line commands to a single line, update indentation in codeblocks from 4 to 2 spaces](https://github.com/enkidevs/curriculum/pull/2979) +- [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) ## January 4th 2022 From b8b67f474cc23972413e356d0a5fe3f8421a73b3 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 23:21:10 +0100 Subject: [PATCH 58/60] revert other folders --- .../arrays-i/the-slice-built-in-function.md | 3 +- .../arrays-i/the-zip-built-in-function.md | 15 +++++-- .../arrays-ii/the-map-built-in-function.md | 3 +- .../arrays-ii/the-sorted-built-in-function.md | 3 +- .../comprehension/dictionary-comprehension.md | 12 +++--- .../comprehension/list-comprehension.md | 3 +- .../nested-lists-comprehension.md | 17 +++++--- .../comprehension/set-comprehension.md | 8 +++- ...r-loop-using-map-or-list-comprehensions.md | 8 ++-- .../decorators/decorators-methods.md | 12 ++++-- .../decorators/decorators-syntax.md | 12 ++++-- .../decorators/functools-wraps.md | 6 ++- .../decorators/what-are-decorators.md | 17 +++++--- .../functional-particularities-of-python.md | 7 +++- .../what-is-functional-programming.md | 13 ++++--- .../generators/generator-of-generators.md | 7 ++-- .../generators/recursive-generator.md | 16 ++++---- .../generators/yield-and-next.md | 14 +++---- .../iterators/the-iteration-protocol.md | 28 ++++++------- .../iterators/the-itertools-module-ii.md | 39 ++++++++++++++----- 20 files changed, 155 insertions(+), 88 deletions(-) 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 1dfc4bd811..7fef3fb0db 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,7 +105,8 @@ 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 7ff2fc725f..3c66abce92 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,9 +105,18 @@ 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 9f60eb2eb9..eb43dabe6c 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 @@ -68,7 +68,8 @@ 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 86709fed22..8987a02dd7 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,7 +105,8 @@ 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 83839cd5a1..d3bb863eee 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -38,7 +38,7 @@ 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,7 +58,7 @@ 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} # Check it is correct: @@ -66,9 +66,9 @@ 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 cfd08dff50..a3689020f2 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,7 +97,8 @@ 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 ddc22493c5..5d5e7f4a42 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,23 +27,27 @@ 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),\ @@ -66,6 +70,7 @@ 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 d9efade59d..f9b40726e7 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,12 +33,14 @@ 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: @@ -46,6 +48,7 @@ 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: @@ -64,8 +67,10 @@ 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 @@ -83,6 +88,7 @@ new_set = {x ??? x % 2 == 0 else ??? for x ??? l} 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 a188eea03f..105042a723 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,7 +47,8 @@ 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. @@ -62,7 +63,8 @@ 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 3c729410a0..972963269e 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,7 +32,8 @@ 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): @@ -54,7 +55,8 @@ 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): @@ -63,8 +65,10 @@ 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 34c06eec99..4aaa726e7b 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,7 +26,8 @@ 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) ``` @@ -36,7 +37,8 @@ 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 @@ -53,7 +55,8 @@ 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 @@ -80,7 +83,8 @@ 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 fa119aa85a..f7bb9b8987 100644 --- a/python/functional-programming/decorators/functools-wraps.md +++ b/python/functional-programming/decorators/functools-wraps.md @@ -26,7 +26,8 @@ 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 @@ -52,7 +53,8 @@ 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 4d96acdd4d..2ee86503a0 100644 --- a/python/functional-programming/decorators/what-are-decorators.md +++ b/python/functional-programming/decorators/what-are-decorators.md @@ -43,7 +43,8 @@ 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: @@ -52,7 +53,8 @@ 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? @@ -60,7 +62,8 @@ 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 ``` @@ -84,7 +87,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 ??? @@ -105,11 +108,13 @@ 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 1d6a67ebb4..c02d6ca751 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 @@ -47,14 +47,17 @@ 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 aa719b8053..322447e407 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,9 +108,10 @@ 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 bcf09a4880..aabb6f9c03 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: -```python +```plain-text 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*: -```python +```plain-text # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,7 +99,8 @@ 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 ea9b3d8141..ecd93de7f6 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 cb18f961a9..d010cc6313 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 a521d85162..74998ca833 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 a70cd4d28b..9e8f8cd2df 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,7 +36,9 @@ 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] ``` @@ -46,7 +48,10 @@ 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] ``` @@ -57,7 +62,9 @@ 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] ``` @@ -79,18 +86,26 @@ 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` @@ -110,10 +125,16 @@ 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))) ``` ??? From 49fee7ede016358761882df3273d3899c50b3734 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Mon, 10 Jan 2022 14:23:06 -0800 Subject: [PATCH 59/60] Update python/functional-programming/arrays-ii/the-map-built-in-function.md Co-authored-by: Nemanja Stojanovic --- .../arrays-ii/the-map-built-in-function.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 a0f4c4fa55..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 @@ -68,7 +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 = ???(???, ???) ``` From d4d53693e8121b8c82843a7c8cf8809689cf68e2 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Thu, 13 Jan 2022 11:06:53 +0100 Subject: [PATCH 60/60] Update datetime-module.md replace the link for an older version with the current stable version one --- python/python-core/playing-with-time/datetime-module.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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