From 34fe0ffacf9b55c5101933539031f52ec185d061 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 4 Jan 2022 14:25:50 +0100 Subject: [PATCH 01/11] Update the-from-import-statement.md Move single-line commands from multiple lines back to a single line as we now wrap code blocks --- .../intro-to-modules/the-from-import-statement.md | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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 006f65124d..31bdc5a820 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 @@ -96,8 +96,7 @@ def ??? ```python # main.py -??? ??? ??? subtract - ??? ??? +??? ??? ??? subtract ??? ??? sub(20, 3) # 20 - 3 is: 17 @@ -125,8 +124,7 @@ sub(20, 3) How can you specifically import the `calculate_volume` method of `cylinder` module? ```python -??? ??? ??? - ??? +??? ??? ??? ??? radius = 10 height = 30 From 82c47e9db17cb70b3f1751cc1259ab73b5b8bbf9 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Tue, 4 Jan 2022 16:33:27 +0100 Subject: [PATCH 02/11] update code block spacing in functional programming --- .../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 +++--- .../nested-lists-comprehension.md | 12 +++--- .../comprehension/set-comprehension.md | 1 - ...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 | 4 +- .../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 +-- 33 files changed, 135 insertions(+), 207 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 7fef3fb0db..1dfc4bd811 100644 --- a/python/functional-programming/arrays-i/the-slice-built-in-function.md +++ b/python/functional-programming/arrays-i/the-slice-built-in-function.md @@ -105,8 +105,7 @@ print(ourString[sObject]) Use `slice` to remove every second number in the list of numbers. ```python -nList = ['1', '2', '3', '4', '5', - '6', '7', '8'] +nList = ['1', '2', '3', '4', '5', '6', '7', '8'] sObject = ???(???, ???, ???) print(nList[sObject]) diff --git a/python/functional-programming/arrays-i/the-zip-built-in-function.md b/python/functional-programming/arrays-i/the-zip-built-in-function.md index 3c66abce92..7ff2fc725f 100644 --- a/python/functional-programming/arrays-i/the-zip-built-in-function.md +++ b/python/functional-programming/arrays-i/the-zip-built-in-function.md @@ -105,18 +105,9 @@ We have three lists, `fnames`, `lnames`, `locations`, which are ordered so that Fill in the gaps in the code below to achieve this. ```python -locations = ['IT', - 'FR', - 'FR', - 'RU'] -fnames = ['italo', - 'jean', - 'emily', - 'katya'] -lnames = ['calvino', - 'micheal', - 'rambert', - 'sokolov'] +locations = ['IT', 'FR', 'FR', 'RU'] +fnames = ['italo', 'jean', 'emily', 'katya'] +lnames = ['calvino', 'micheal', 'rambert', 'sokolov'] result = zip(???, ???) result2 = zip(???, ???) diff --git a/python/functional-programming/arrays-ii/the-map-built-in-function.md b/python/functional-programming/arrays-ii/the-map-built-in-function.md index eb43dabe6c..9f60eb2eb9 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,8 +68,7 @@ Finally, it's good to know that we can pass more than one iterable `input_list` Let's say we have a list, called `promises`. We want to `make_good` on all our promises, where `make_good` is a previously-defined function that takes a string. Fill in the blanks in the code below to apply `make_good` to all elements in `promises`. ```python -promises = ['learn css', 'learn js', - 'buy milk', 'be excellent to each other'] +promises = ['learn css', 'learn js','buy milk', 'be excellent to each other'] promises = ???(???, ???) ``` diff --git a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md index 8987a02dd7..86709fed22 100644 --- a/python/functional-programming/arrays-ii/the-sorted-built-in-function.md +++ b/python/functional-programming/arrays-ii/the-sorted-built-in-function.md @@ -105,8 +105,7 @@ print(sorted([4, 0, 2, 3, 1, 5])) What is the result of the execution of the following code snippet? ```python -print(sorted([0, 2, 3, 1, -'a', 'b', 'A', 'B'])) +print(sorted([0, 2, 3, 1, 'a', 'b', 'A', 'B'])) ``` ??? diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index d3bb863eee..bce7ed783d 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/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index 5d5e7f4a42..bebf08f154 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -27,16 +27,14 @@ 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] + row in matrix] #matrix2 = [[1, 4, 9], [16, 25, 36],\ # [49, 64, 81]] ``` @@ -45,9 +43,9 @@ 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),\ diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index f9b40726e7..8ae40ad31e 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -40,7 +40,6 @@ And we need a set containing only even numbers in the list. This can be easily a ```python even_set = {x for x in my_list if x%2 == 0} - ``` We can now check the result: diff --git a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md index 105042a723..a188eea03f 100644 --- a/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md +++ b/python/functional-programming/comprehension/speed-up-your-for-loop-using-map-or-list-comprehensions.md @@ -35,7 +35,7 @@ If you need to lowercase all the input strings: ```python lower_list = [] for word in input_list: - lower_list.append(word.lower()) + lower_list.append(word.lower()) ``` Instead, you can use `map()` to push the loop into compiled C code: @@ -47,8 +47,7 @@ lower_list = map(str.lower, input_list) Also, in Python 2.0 or above, there are list comprehensions. List comprehension are the "pythonic" way to approach this situation. `map()` is more often used in JavaScript. We recommend usage of list comprehension: ```python -lower_list = [word.lower() \ - for word in input_list] +lower_list = [word.lower() for word in input_list] ``` They are both more efficient than simple `for` loop statement. @@ -63,8 +62,7 @@ Use list comprehension to modify a list of characters such that all its elements ```python strings = ['a', 'e', 'i', 'o', 'u'] -lower_list = [word.??? \ - for word in ???] +lower_list = [word.??? for word in ???] ``` - upper() diff --git a/python/functional-programming/decorators/decorators-methods.md b/python/functional-programming/decorators/decorators-methods.md index 972963269e..3c729410a0 100644 --- a/python/functional-programming/decorators/decorators-methods.md +++ b/python/functional-programming/decorators/decorators-methods.md @@ -32,8 +32,7 @@ def get_fahrenheit(method): # methods, pass self as a parameter def wrapper(self): # "self" argument is passed - return "{0} F" - .format(method(self) * 1.8 + 32) + return "{0} F".format(method(self) * 1.8 + 32) return wrapper class Temperature(object): @@ -55,8 +54,7 @@ We got it now working for methods. But what if we are looking to decorate method def get_fahrenheit(method): # exepect any number of args/named args def wrapper(*args, **kwargs): - return "{0} F" - .format(method(*args,**kwargs)*1.8+32) + return "{0} F".format(method(*args,**kwargs)*1.8+32) return wrapper class Temperature(object): @@ -65,10 +63,8 @@ class Temperature(object): @get_fahrenheit #two extra arguments expected here - def get_temp(self, extra1, extra2 = 0, - extra3 = 0): - return self.degrees + extra1 + extra2 - + extra3 + def get_temp(self, extra1, extra2 = 0, extra3 = 0): + return self.degrees + extra1 + extra2 + extra3 temp = Temperature(15) # self is passed by default print(temp.get_temp(3, extra2 = 1)) diff --git a/python/functional-programming/decorators/decorators-syntax.md b/python/functional-programming/decorators/decorators-syntax.md index 4aaa726e7b..34c06eec99 100644 --- a/python/functional-programming/decorators/decorators-syntax.md +++ b/python/functional-programming/decorators/decorators-syntax.md @@ -26,8 +26,7 @@ def say_hello(name): return "Hello, {0}!".format(name) def h2_decorate(string_function): def func_wrapper(name): - return "

{0}

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

{0}

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

{0}

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

{0}

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

{0}

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

{0}

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

{0}

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

{0}

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

{0}

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

{0}

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

{0}

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

{0}

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

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

{0}

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

{0}

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

{0}

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

{0}

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

{0}

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

{0}

".format(func(name)) return func_wrapper ``` diff --git a/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md b/python/functional-programming/functional-programming-ii/functional-particularities-of-python.md index c02d6ca751..1d6a67ebb4 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,17 +47,14 @@ A comprehension is an expression where the same flow control keywords used in lo ```python # without comprehension for element in list: - if condition1(element) and - condition2(element): + if condition1(element) and condition2(element): collection.append(element) else: new = mutate(element) collection.append(element) # with comprehension -collection = [e if condition1(e) and - condition2(e) else - modify(e) for e in list] +collection = [e if condition1(e) and condition2(e) else modify(e) for e in list] ``` As you can clearly see, our code instantly becomes much more legible and comprehensible. diff --git a/python/functional-programming/functional-programming/what-is-functional-programming.md b/python/functional-programming/functional-programming/what-is-functional-programming.md index 322447e407..aa719b8053 100644 --- a/python/functional-programming/functional-programming/what-is-functional-programming.md +++ b/python/functional-programming/functional-programming/what-is-functional-programming.md @@ -40,9 +40,9 @@ This is a way to define functions in a one-line fashion. Functions defined with ```py foo = [1, 2, 3, 4, 5, 6] -print(list(filter( - lambda x: x % 2 == 0,foo)) - ) +print(list(filter( \ + lambda x: x % 2 == 0,foo +))) # Output: [2, 4, 6] ``` @@ -108,10 +108,9 @@ Can you predict what the output will be? ```py foo = list(range(1,10)) -result = list( - filter( - lambda x: x / 2 == 1 ,foo - )) +result = list(filter( \ + lambda x: x / 2 == 1 ,foo +)) print(result) diff --git a/python/functional-programming/generators/generator-of-generators.md b/python/functional-programming/generators/generator-of-generators.md index aabb6f9c03..bcf09a4880 100644 --- a/python/functional-programming/generators/generator-of-generators.md +++ b/python/functional-programming/generators/generator-of-generators.md @@ -27,7 +27,7 @@ Last insight, we've seen how **recursion** and **generators** can work together. Consider the following example: -```plain-text +```python def fibonacci(): #Generating fibonacci sequence a, b = 0, 1 @@ -51,7 +51,7 @@ This is why we define the second **generator** called `firstn` which accepts two Finally, we print a list containing the first 10 *elements* of the *Fibonacci sequence*: -```plain-text +```python # Output: # [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` @@ -99,8 +99,7 @@ def n_power(g,n): for i in range(n): yield next(g) -print(list(n_power( - power_of_two(), 4))) +print(list(n_power(power_of_two(), 4))) ``` ??? diff --git a/python/functional-programming/generators/recursive-generator.md b/python/functional-programming/generators/recursive-generator.md index ecd93de7f6..ea9b3d8141 100644 --- a/python/functional-programming/generators/recursive-generator.md +++ b/python/functional-programming/generators/recursive-generator.md @@ -30,9 +30,9 @@ Consider the following example: ```python def infinity(start): - yield start - for x in infinity(start + 1) - yield x + yield start + for x in infinity(start + 1) + yield x ``` We defined a **generator** that counts up to infinity. During the first evaluation, the starting value will be **returned**. Then we loop on the new **generators** created in the `for`'s body. @@ -43,8 +43,8 @@ Let's check out the example above implemented using `yield from`: ```python def infinity(start): - yield start - yield from infinity(start + 1) + yield start + yield from infinity(start + 1) gen = infinity(20) print(next(gen)) # 20 @@ -64,9 +64,9 @@ Can you spot which of the following generators are recursive? ```python def list_gen(l): - if l: - yield l[0] - yield from list_gen(l[1:]) + if l: + yield l[0] + yield from list_gen(l[1:]) def cubic_generator(n): for i in range(n): diff --git a/python/functional-programming/generators/yield-and-next.md b/python/functional-programming/generators/yield-and-next.md index d010cc6313..cb18f961a9 100644 --- a/python/functional-programming/generators/yield-and-next.md +++ b/python/functional-programming/generators/yield-and-next.md @@ -42,10 +42,10 @@ Consider the following generator: ```py def range_gen(n): - i = 0 - while i < n: - yield i - i += 1 + i = 0 + while i < n: + yield i + i += 1 ``` This **function** generates all natural numbers up to `n`. Let's use the `next()` method now: @@ -73,9 +73,9 @@ What is the output of the following snippet? ```py def countdown(num): - while num > 0: - yield num - num -= 1 + while num > 0: + yield num + num -= 1 >>> gen = countdown(5) >>> print(next(gen)) diff --git a/python/functional-programming/iterators/the-iteration-protocol.md b/python/functional-programming/iterators/the-iteration-protocol.md index 74998ca833..a521d85162 100644 --- a/python/functional-programming/iterators/the-iteration-protocol.md +++ b/python/functional-programming/iterators/the-iteration-protocol.md @@ -34,22 +34,22 @@ Iterators are always implemented as classes. Let's examine an iterator's code fo ```python class Counter(object): - def __init__(self, start, finish): - self.current = start - self.finish = finish - - def __iter__(self): - return self - - def __next__(self): - if self.current > self.finish: - raise StopIteration - else: - self.current += 1 - return self.current - 1 + def __init__(self, start, finish): + self.current = start + self.finish = finish + + def __iter__(self): + return self + + def __next__(self): + if self.current > self.finish: + raise StopIteration + else: + self.current += 1 + return self.current - 1 ``` -We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created, however, it is not a constructor since, the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. +We're already familiar with the `iter` and `next` methods. The `init` method is what is called when the iterator is first created. However, it is not a constructor since the object is already created when the code within `init` is executed. Instead, this is referred to as an initializer. In this `Counter` example, we can see that `init` takes the values defined by the creator of the iterator (the start and finish values) and keeps track of them. The `next` method checks to see if the iterator has gone beyond the defined `finish` value, and if not, increases the current value and returns the value before that. If the value has exceeded the `finish` value, a StopIteration exception is raised. Simple! diff --git a/python/functional-programming/iterators/the-itertools-module-ii.md b/python/functional-programming/iterators/the-itertools-module-ii.md index 9e8f8cd2df..a70cd4d28b 100644 --- a/python/functional-programming/iterators/the-itertools-module-ii.md +++ b/python/functional-programming/iterators/the-itertools-module-ii.md @@ -36,9 +36,7 @@ import itertools; letters = ['a', 'b', 'c', 'd'] numbers = [1, 2, 3, 4] -print( - list( - itertools.chain(letters, numbers))) +print(list(itertools.chain(letters, numbers))) # Result = ['a', 'b', 'c', 'd', 1, 2, 3, 4] ``` @@ -48,10 +46,7 @@ Next, `filterfalse` iterates through a collection of elements, and, given a bool ```python numbers = [1, 2, 3, 4, 5, 6, 7, 8] -print( - list( - itertools.filterfalse( - lambda x: 2 < x < 7, numbers))) +print(list(itertools.filterfalse(lambda x: 2 < x < 7, numbers))) # Result = [1, 2, 7, 8] ``` @@ -62,9 +57,7 @@ Finally, `compress()`, which takes two collections, a and b, and returns only th numbers = [1, 2, 3, 4, 5, 6, 7, 8] boolean = [1, 0, 1, 0, 1, 0, 1, 0] -print( - list( - itertools.compress(numbers, boolean))) +print(list(itertools.compress(numbers, boolean))) # Result: [1, 3, 5, 7] ``` @@ -86,26 +79,18 @@ discounts = [-30, -100, -35, -85, -15] isInSale = [1, 0, 1, 1, 1] salePrices = [] -discountIterator = -iter( - itertools.???( - discounts, isInSale)) +discountIterator = iter(itertools.???(discounts, isInSale)) -fullPricesInSale = -itertools.compress(prices, isInSale) +fullPricesInSale = itertools.compress(prices, isInSale) def f(x): price = x + next(discountIterator) salePrices.append(price) return(price <= 0) -print( - list( - itertools.???( - lambda x: f(x), fullPricesInSale))) +print(list(itertools.???(lambda x: f(x), fullPricesInSale))) -print( - list(salePrices)) +print(list(salePrices)) ``` - `compress` @@ -125,16 +110,10 @@ What is the result of the following code execution? ```python import itertools; -names = ['Tom', 'Sadiq', 'Lars', - 'Lee', 'Jean'] +names = ['Tom', 'Sadiq', 'Lars', 'Lee', 'Jean'] boolean = [1, 0, 1, 1, 0] -print( - list( - itertools.islice( - itertools.cycle( - itertools.compress( - names, boolean)), 0, 6))) +print(list(itertools.islice(itertools.cycle(itertools.compress(names, boolean)), 0, 6))) ``` ??? diff --git a/python/functional-programming/python-immutability/atomicity-of-failure.md b/python/functional-programming/python-immutability/atomicity-of-failure.md index 6cd8958632..f83c4d831e 100644 --- a/python/functional-programming/python-immutability/atomicity-of-failure.md +++ b/python/functional-programming/python-immutability/atomicity-of-failure.md @@ -33,8 +33,7 @@ Take a look at this simple class, `MutableShoppingBasket`, representing a user's class MutableShoppingBasket: def __init__(self, itemcount): if itemcount < 0: - raise ValueError("""You can't have - less than zero items in the basket!""") + raise ValueError("""You can't have less than zero items in the basket!""") self.itemcount = itemcount def increment_items(self): @@ -44,8 +43,7 @@ class MutableShoppingBasket: self.itemcount -=1 def __repr__(self): - return("Shopping Basket with " + - str(self.itemcount) + " items.") + return("Shopping Basket with " + str(self.itemcount) + " items.") ``` Can you see how this constraint could be broken? Let's do it: @@ -92,9 +90,7 @@ What is the code snippet below an example of? (Remember that the `Connection` class defaults to the last HTTP method used if one is not specified in `request()`. See the footnotes in the insight for more information.) ```python -conn = Connection( - http.client.HTTPConnection( - "httpbin.org", 80)) +conn = Connection(http.client.HTTPConnection("httpbin.org", 80)) r1 = conn.request("POST") r2 = conn.request("", "text=hello") ``` diff --git a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md index 41028ca9e8..065c140c09 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 @@ -63,7 +63,7 @@ For example, consider the following code snippet: ```python string = "" for line in file: - string += str(line) + string += str(line) ``` In this case, while the code will execute and perform the functionality correctly, as we increase the size of the string it will become increasingly more inefficient. This is because of the immutability of the `string` type, which causes the concatenation operation performed at each iteration to create a whole new copy of the string. As we reach the end of a large file, every iteration of the loop will be creating and discarding a very large string, which could potentially be needlessly I/O intensive and a waste of memory. @@ -73,7 +73,7 @@ With the knowledge of which data types are mutable, you can choose a better data ```python list = [] # List is mutable! for line in file: - list.append(str(line)) + list.append(str(line)) "".join(list) ``` diff --git a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md index 5e91664bd1..10d592e97d 100644 --- a/python/functional-programming/python-immutability/why-types-have-immutability-ii.md +++ b/python/functional-programming/python-immutability/why-types-have-immutability-ii.md @@ -41,10 +41,8 @@ class Connection(object): def post(self): self.method = "POST" # ^ mutates the Connection object - self.httpconnection.request( - self.method, "/") - self.result = - self.httpconnection.getresponse() + self.httpconnection.request(self.method, "/") + self.result = self.httpconnection.getresponse() conn.result.read() return self.result ``` diff --git a/python/python-core/advanced-queues/prioritize-your-queue.md b/python/python-core/advanced-queues/prioritize-your-queue.md index b1e82b6f0b..99ace65af3 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 19798a81b6..6f6c45bc8b 100644 --- a/python/python-core/advanced-queues/queue-s-and-threads.md +++ b/python/python-core/advanced-queues/queue-s-and-threads.md @@ -80,8 +80,7 @@ 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 f6692adf6c..0388fa6d5f 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,11 +80,10 @@ 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 7c3e2b0a97..4e04c6d1c3 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 b51e4f6225..73cb44b3a5 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,8 +30,7 @@ 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 19da4a6441..2c37539a54 100644 --- a/python/python-core/basic-file-manipulation/writing-files.md +++ b/python/python-core/basic-file-manipulation/writing-files.md @@ -39,8 +39,7 @@ 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 8ecbfb8cce..272e72cc48 100644 --- a/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md +++ b/python/python-core/bits-bytes-hexadecimals/bytearray-objects.md @@ -80,8 +80,7 @@ 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 7c118d4965..3d24ad72d8 100644 --- a/python/python-core/classes-i/class-keywords.md +++ b/python/python-core/classes-i/class-keywords.md @@ -35,11 +35,11 @@ Functions inside any object type are known as *methods* (the case for class func ```python # a data structure class Employee: - # an attribute - count = 5 - # a method - def print_idnum(self): - ... + # an attribute + count = 5 + # a method + def print_idnum(self): + ... ``` diff --git a/python/python-core/classes-i/creating-classes.md b/python/python-core/classes-i/creating-classes.md index c46e623a7e..b7eb62504a 100644 --- a/python/python-core/classes-i/creating-classes.md +++ b/python/python-core/classes-i/creating-classes.md @@ -25,7 +25,7 @@ Classes are defined with the `class` keyword and use Python's block structure[2] ```python class Employee: - count = 0 + count = 0 ``` To create an instance of a class (also called to "instantiate") is done like so: @@ -61,8 +61,7 @@ Once the `__init__` method has been taken care of, other methods can be defined class Employee: # the code above def print_idnum(self): - print("{0} is employee no. {1}" - .format(self.name, self.idnum)) + print("{0} is employee no. {1}".format(self.name, self.idnum)) ``` > 💡 On the other hand, when calling methods, you do not need to pass `self` as a parameter, Python does that for you automatically. diff --git a/python/python-core/classes-i/method-overriding.md b/python/python-core/classes-i/method-overriding.md index d82ec7a030..bdd02dd8b1 100644 --- a/python/python-core/classes-i/method-overriding.md +++ b/python/python-core/classes-i/method-overriding.md @@ -39,12 +39,12 @@ To *override* a parent method, the child class should define a method with the * ```python class Animal: - def identify(self): - print("I am an animal") + def identify(self): + print("I am an animal") class Bird(Animal): - def identify(self): - print("I am a bird") + def identify(self): + print("I am a bird") bird = Bird() bird.identify() @@ -58,10 +58,10 @@ To add some behavior to a method but also use the parent method behavior, use `s # No changes made to the class Animal # Change class Bird to: class Bird(Animal): - def identify(self): - # added line, calls parent method - super().identify() - print("I am a bird") + def identify(self): + # added line, calls parent method + super().identify() + print("I am a bird") bird = Bird() bird.identify() diff --git a/python/python-core/classes-i/using-classes.md b/python/python-core/classes-i/using-classes.md index 1bf0802c0f..20d39ce860 100644 --- a/python/python-core/classes-i/using-classes.md +++ b/python/python-core/classes-i/using-classes.md @@ -30,8 +30,7 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}" - .format(self.name, self.idnum)) + print("{0} is employee no. {1}".format(self.name, self.idnum)) ``` To create an instance of the class: @@ -67,8 +66,7 @@ class Employee: self.name = name self.idnum = Employee.count def print_idnum(self): - print("{0} is employee no. {1}" - .format(self.name, self.idnum)) + print("{0} is employee no. {1}".format(self.name, self.idnum)) steve = ???('???') ``` From 9cee153e23823889324c89ea27e2e33db7dfa595 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Tue, 4 Jan 2022 16:40:27 +0100 Subject: [PATCH 03/11] Update dictionary-comprehension.md --- .../comprehension/dictionary-comprehension.md | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/python/functional-programming/comprehension/dictionary-comprehension.md b/python/functional-programming/comprehension/dictionary-comprehension.md index bce7ed783d..83839cd5a1 100644 --- a/python/functional-programming/comprehension/dictionary-comprehension.md +++ b/python/functional-programming/comprehension/dictionary-comprehension.md @@ -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'] ``` From dba96fc6077fd83ccfcd3685ab1787ba9b8be08a Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Wed, 5 Jan 2022 12:55:05 +0100 Subject: [PATCH 04/11] Fix inconsistent indentation in code blocks --- .../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 | 8 +-- .../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 ++-- 49 files changed, 238 insertions(+), 265 deletions(-) diff --git a/python/python-core/classes-ii/classes-ii-discussion.md b/python/python-core/classes-ii/classes-ii-discussion.md index da0dd34314..f4c3b37f47 100644 --- a/python/python-core/classes-ii/classes-ii-discussion.md +++ b/python/python-core/classes-ii/classes-ii-discussion.md @@ -65,12 +65,10 @@ 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 fda41bb480..7c70b63e0c 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 663e5674df..c44ac05871 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 537bbda277..c2a25bb467 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 syntacticly different +These two classes implement the same functionality although syntactically different: ```python # The name is set to "BigCar" @@ -55,12 +55,9 @@ 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 7158dae9d7..498a74b85d 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 75ca7b1ec3..47fb50ac2c 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 1a31d5823f..22b0c84ff1 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 fc8ca7852b..119cab5fcc 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 55a062c193..a4e9d23261 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 62fbe19bac..10094cb93e 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 b9d67ec901..f011837d28 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 aa5e7bee1f..2a5d0bdd5d 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 a6ec81ba89..5144ebdaf7 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,8 +67,7 @@ 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 929beac058..7830513e69 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 4910c6608c..0b7e4179dd 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,8 +112,7 @@ 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 166717de16..f70d9d75c7 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 31bdc5a820..14a4735835 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: 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 8ab6215644..0571ceed30 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 -1 def foo(): -2 return 6 -3 x = foo() -4 while(True): -5 x += 1 -6 if x > 19: -7 print("Welcome!") +def foo(): + return 6 +x = foo() +while(True): + x += 1 +if x > 19: + 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 -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!") +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!") # 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 ee12d62a2b..c86389266b 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 62bbe43866..21e11dba4a 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,17 +29,16 @@ Considering the **source code** exemplified in the previous insight[1], lets see ```python (Pdb) list -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__': +-> 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__': (Pdb) ``` diff --git a/python/python-core/looping/break-and-continue-statements.md b/python/python-core/looping/break-and-continue-statements.md index 0ecb749d1b..311ffd3036 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 8b6f66ad04..448d8d2e2c 100644 --- a/python/python-core/looping/for-loops.md +++ b/python/python-core/looping/for-loops.md @@ -29,14 +29,14 @@ The standard Python `for` loop syntax is: ```python for iterating_num in sequence: - doSomething() + doSomething() ``` An example `for` loop: ```python for letter in 'Enki': - print('Letter: ', letter) + print('Letter: ', letter) ``` Gives this output: @@ -54,7 +54,7 @@ When writing a loop, Python will assign each value of the list to `x`, one by on nums = [1, 2, 3] for x in nums: - print(x) + print(x) ``` Gives this output: @@ -74,8 +74,8 @@ What’s the output of the following code snippet: ```py for x in [0, 1, 2, 3, 4, 5]: - if (x % 2 == 0): - print(x) + if (x % 2 == 0): + print(x) ``` ??? @@ -94,7 +94,7 @@ What’s the output of the following code snippet: ```py for letter in 'Python': - print(letter) + print(letter) ``` ??? diff --git a/python/python-core/looping/looping-techniques.md b/python/python-core/looping/looping-techniques.md index 2ef3a3fad2..7cca772a89 100644 --- a/python/python-core/looping/looping-techniques.md +++ b/python/python-core/looping/looping-techniques.md @@ -47,7 +47,7 @@ Python has multiple techniques for looping over data structures. ```python my_dict = {'first': 'a', 'second': 'b'} for k, v in my_dict.items(): - print(k, v) + print(k, v) #first a #second b ``` @@ -57,7 +57,7 @@ The `enumerate()` function allows looping with both `index` and `value` through ```python my_list = ['a', 'b'] for i, v in enumerate(my_list): - print(i, v) + print(i, v) # 0 a # 1 b ``` @@ -68,7 +68,7 @@ for i, v in enumerate(my_list): first_list = ['a', 'b'] second_list = ['one', 'two'] for f, s in zip(first_list, second_list): - print(f, s) + print(f, s) # a one # b two ``` @@ -78,7 +78,7 @@ To loop in a sorted order, use the `sorted()` function: ```python my_list = ['b', 'c', 'a'] for f in sorted(my_list): - print(f) + print(f) # a # b # c @@ -105,7 +105,7 @@ Complete the code snippet to pair the sequences in order and loop over them both list_a = ['a', 'b', 'c'] list_one = ['one', 'two', 'three'] for k, v in ???(list_a, list_one): - print(???) + print(???) //Expected output: // a one @@ -130,7 +130,7 @@ Complete the code snippet to loop through the list in reverse and then print it ```python enki_list = ['i', 'k', 'n', 'e'] for w in ???(???): - ???(w) + ???(w) ``` diff --git a/python/python-core/looping/using-else-in-loops.md b/python/python-core/looping/using-else-in-loops.md index 3764220c60..185ecf2c0f 100644 --- a/python/python-core/looping/using-else-in-loops.md +++ b/python/python-core/looping/using-else-in-loops.md @@ -29,10 +29,10 @@ For example, an `else` statement integrated into a `while` loop: ```python x = 0 while (x < 3): - print(x) - x = x + 1 + print(x) + x = x + 1 else: - print(x, "is too big!") + print(x, "is too big!") ``` Gives the following output: @@ -48,9 +48,9 @@ Also, an `else` statement integrated into a `for` loop in a similar example: ```python for x in range(0, 5): - print(x) + print(x) else: - print(x, "is range's upper limit") + print(x, "is range's upper limit") ``` Gives the following output: @@ -68,12 +68,12 @@ If a loop exits because of a `break` clause, the `else` clause will be skipped: ```python for i in range(0, 2): - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` With the output: @@ -93,10 +93,10 @@ Fill in the following snippet such that it will print `"Computation Done"` when ```python x = 0 while x ??? 3: - print("running") - x = x + 1 + print("running") + x = x + 1 ???: - ???("Computation Done") + ???("Computation Done") ``` - `<` @@ -130,12 +130,12 @@ An `else` statement is used in loops when the loop's ??? is evaluated to ???. ```python for i in [1, 2]: - if i == 1: - print("a") - break - print("b") + if i == 1: + print("a") + break + print("b") else: - print("c") + print("c") ``` ??? diff --git a/python/python-core/looping/while-loops.md b/python/python-core/looping/while-loops.md index fddf5854b2..50fca2d674 100644 --- a/python/python-core/looping/while-loops.md +++ b/python/python-core/looping/while-loops.md @@ -25,7 +25,7 @@ The standard `while` loop syntax is: ```python while condition: - doSomething() + doSomething() ``` While the condition evaluates to *true*, the code inside the loop is executed. As soon as the condition evaluates to *false*, the loop is exited and the code immediately following the loop is executed. @@ -35,8 +35,8 @@ For example: ```python counter = 0 while counter < 5: - print(counter) - counter = counter + 1 + print(counter) + counter = counter + 1 ``` Gives the following output: @@ -80,8 +80,8 @@ What’s the output of the following code snippet: ```python x = 0 while x < 5: - x = x + 1 - print(x) + x = x + 1 + print(x) ``` ??? diff --git a/python/python-core/meet-python/what-is-python.md b/python/python-core/meet-python/what-is-python.md index 9e142357ba..5da6e32326 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 e30123c761..4d0e9d86f0 100644 --- a/python/python-core/more-on-dictionaries/dictionaries-from-lists.md +++ b/python/python-core/more-on-dictionaries/dictionaries-from-lists.md @@ -87,8 +87,7 @@ 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 fd25872cb6..6e74742786 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 32cb9768e0..6f36cb8534 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 1edc2f9d16..fbabccd549 100644 --- a/python/python-core/playing-with-time/playing-with-time.md +++ b/python/python-core/playing-with-time/playing-with-time.md @@ -38,8 +38,7 @@ 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 5ba58d6bc7..ce03c40ee0 100644 --- a/python/python-core/playing-with-time/time-object.md +++ b/python/python-core/playing-with-time/time-object.md @@ -112,8 +112,7 @@ 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 f3e51fe3f7..1d36d14164 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 743f22b19d..e2ed7fd9a0 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 71fd62c058..74aaa932f5 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 c7422125ea..c2aec940fc 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 7bec37881d..505c9d3f67 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,8 +28,7 @@ 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. @@ -37,9 +36,7 @@ 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 5f43c11b21..143a3f7067 100644 --- a/python/python-core/python-tips/pretty-print-data-structures.md +++ b/python/python-core/python-tips/pretty-print-data-structures.md @@ -78,8 +78,7 @@ Pretty `print` the following 2D array: ```python import ??? -array = [(x, {y: y * y for y in range(4)}) - for x in range(8)] +array = [(x, {y: y * y for y in range(4)}) for x in range(8)] print(pprint.???(???, width=19)) ``` diff --git a/python/python-core/string-recipes/recipe-to-normalize-text.md b/python/python-core/string-recipes/recipe-to-normalize-text.md index 84efead07d..e5b3e7b395 100644 --- a/python/python-core/string-recipes/recipe-to-normalize-text.md +++ b/python/python-core/string-recipes/recipe-to-normalize-text.md @@ -29,9 +29,7 @@ Using the `unicodedata` Python module it's easy to normalize any **unicode** dat import unicodedata data = u'ïnvéntìvé' -normal = unicodedata.normalize\ - ('NFKD', data).\ - encode('ASCII', 'ignore') +normal = unicodedata.normalize('NFKD', data).encode('ASCII', 'ignore') print(normal) ``` diff --git a/python/python-core/string-recipes/regular-expressions.md b/python/python-core/string-recipes/regular-expressions.md index eeca38504e..47b9648e51 100644 --- a/python/python-core/string-recipes/regular-expressions.md +++ b/python/python-core/string-recipes/regular-expressions.md @@ -42,7 +42,7 @@ The most common use of the `re` module is to search texts for specified patterns ```python text = 'Enki is cool' if re.search('Enki', text): - print("Found it!") + print("Found it!") # output: Found it! ``` diff --git a/python/python-core/testing/doctests.md b/python/python-core/testing/doctests.md index 6b0d411dbb..ddcbb3e606 100644 --- a/python/python-core/testing/doctests.md +++ b/python/python-core/testing/doctests.md @@ -30,7 +30,7 @@ We begin by importing the *doctest* module and defining a function: import doctest def multiply(a, b): - return a * b + return a * b ``` Then, define the tests inside the function's docstring[1]: @@ -40,24 +40,24 @@ Then, define the tests inside the function's docstring[1]: import doctest def multiply(a, b): - """ - Test for numbers: + """ + Test for numbers: - >>> multiply(3,3) - 9 + >>> multiply(3,3) + 9 - Test for chars: + Test for chars: - >>> multiply('a',3) - 'aaa' - >>> multiply('a',0) - '' - """ + >>> multiply('a',3) + 'aaa' + >>> multiply('a',0) + '' + """ - return a * b + return a * b if __name__ == '__main__': - doctest.testmod() + doctest.testmod() ``` @@ -73,24 +73,24 @@ The output: ```python Trying: - multiply(3, 3) + multiply(3, 3) Expecting: - 9 + 9 ok Trying: - multiply('a', 3) + multiply('a', 3) Expecting: - 'aaa' + 'aaa' ok Trying: - multiply('a', 0) + multiply('a', 0) Expecting: - '' + '' ok 1 items had no tests: - __main__ + __main__ 1 items passed all tests: - 3 tests in __main__.multiply + 3 tests in __main__.multiply 3 tests in 2 items. 3 passed and 0 failed. Test passed. @@ -105,12 +105,12 @@ Create a `doctest` for the following methods: ```python def sum(a, b): - # Test: - """ - >>> ??? ??? - 2 - """ - return ??? + # Test: + """ + >>> ??? ??? + 2 + """ + return ??? ``` - sum diff --git a/python/python-core/testing/mocking-tests.md b/python/python-core/testing/mocking-tests.md index f1c178e5c8..fead0beeff 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 aae3d34d00..6b112f23c2 100644 --- a/python/python-core/testing/nose-testing.md +++ b/python/python-core/testing/nose-testing.md @@ -31,16 +31,16 @@ revisionQuestion: # multiply_nose.py def multiply(a, b): - return a * b + return a * b def test_one(): - assert multiply(2, 3) == 6 + assert multiply(2, 3) == 6 def test_two(): - assert multiply(3, 2) == 5 + assert multiply(3, 2) == 5 ``` -For this example we'll **run** the test with `-v` (verbose) flag: +For this example, we'll **run** the test with `-v` (verbose) flag: ```bash nosetests -v multiply.py diff --git a/python/python-core/unordered-data-types/dictionary-methods-ii.md b/python/python-core/unordered-data-types/dictionary-methods-ii.md index 6afd2d6d44..cc09ed173f 100644 --- a/python/python-core/unordered-data-types/dictionary-methods-ii.md +++ b/python/python-core/unordered-data-types/dictionary-methods-ii.md @@ -95,8 +95,7 @@ print(famous_siblings) Suppose we want to create a dictionary using the `fromkeys` method. Fill in the gaps accordingly: ```python -new_dictionary = ???.???( - [1, 2, 3, 4, 5], ???) +new_dictionary = ???.???([1, 2, 3, 4, 5], ???) print(new_dictionary) # {1: 0, 2: 0, 3: 0, 4: 0, 5: 0} diff --git a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md index 57d4e2cec9..07273fb6c8 100644 --- a/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md +++ b/python/python-core/unordered-data-types/dictionary-standard-mapping-type.md @@ -95,7 +95,6 @@ print(preferences) Fill in the following snippet so that it will return the value of `dog`: ```python - animals = { 'cat': 'persian', 'dog': 'pug' diff --git a/python/python-core/utilities-i/your-own-python-calendar.md b/python/python-core/utilities-i/your-own-python-calendar.md index e6dbc06ebc..65cf9f6775 100644 --- a/python/python-core/utilities-i/your-own-python-calendar.md +++ b/python/python-core/utilities-i/your-own-python-calendar.md @@ -89,8 +89,7 @@ This module provide other useful methods for working with dates, times and calen Set the first day of the week of your `calendar` to be Monday: ```python -calendar.??? \ - (calendar.MONDAY) +calendar.???(calendar.MONDAY) ``` - `setfirstweekday` diff --git a/python/python-core/utilities-ii/coroutine-utility-function.md b/python/python-core/utilities-ii/coroutine-utility-function.md index fd20f3e393..18babf7bff 100644 --- a/python/python-core/utilities-ii/coroutine-utility-function.md +++ b/python/python-core/utilities-ii/coroutine-utility-function.md @@ -63,7 +63,7 @@ Convert `my_generator` to a coroutine function: import types def my_generator(): - yield 1 + yield 1 my_coroutine = ???.???(my_generator) ``` diff --git a/python/python-core/utilities-ii/working-with-junk-data.md b/python/python-core/utilities-ii/working-with-junk-data.md index c992d3fc8d..6b862df0d7 100644 --- a/python/python-core/utilities-ii/working-with-junk-data.md +++ b/python/python-core/utilities-ii/working-with-junk-data.md @@ -29,8 +29,7 @@ For the sake of the argument we will work with this class' function called `find ```python from difflib import SequenceMatcher -s = SequenceMatcher(None, \ - " abcd", "abcd abcd") +s = SequenceMatcher(None, " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=0, b=4, size=5) @@ -51,8 +50,7 @@ See how in the first scenario we searched for the longest match between the two But if we treat white spaces as **Junk** the output will be different: ```python -s = SequenceMatcher(lambda x: x == " ", - " abcd", "abcd abcd") +s = SequenceMatcher(lambda x: x == " ", " abcd", "abcd abcd") print(s.find_longest_match(0, 5, 0, 9)) # prints Match(a=1, b=0, size=4) ``` @@ -65,8 +63,7 @@ print(s.find_longest_match(0, 5, 0, 9)) Complete the `SequenceMatcher` constructor such that empty spaces are treated as junk: ```python -s = SequenceMatcher(??? x: x == ???, - “ abcd”, “abcd abcd”) +s = SequenceMatcher(??? x: x == ???, “ abcd”, “abcd abcd”) ``` - `lambda` diff --git a/python/python-core/working-with-strings/efficient-concatenation-with-join.md b/python/python-core/working-with-strings/efficient-concatenation-with-join.md index 83bb0b5be4..f09723f249 100644 --- a/python/python-core/working-with-strings/efficient-concatenation-with-join.md +++ b/python/python-core/working-with-strings/efficient-concatenation-with-join.md @@ -57,8 +57,7 @@ for x in list: A better and faster way is: ```python -slist = [some_function(elt) \ - for elt in somelist] +slist = [some_function(elt) for elt in somelist] s = "".join(slist) ``` diff --git a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md index 7554291e53..191401d6d7 100644 --- a/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md +++ b/python/python-core/working-with-strings/three-ways-to-substitute-a-substring-of-a-string.md @@ -73,10 +73,8 @@ Using `string.Template` , substitute the following substring: ```python import string -t = string - .???("It's ???weather") -print(t - .???(weather="sunny")) +t = string.???("It's ???weather") +print(t.???(weather="sunny")) ``` Using `f-strings`, print "Hey Enki, how are you?": @@ -105,8 +103,7 @@ Substitute the substring using curly brackets: ```python my_string = "Good {time}" -print(my_string - .???(???="evening")) +print(my_string.???(???="evening")) ``` - `format` From a346846276cef908b8b6b45633451fcd12ac3691 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 5 Jan 2022 14:43:00 +0100 Subject: [PATCH 05/11] replace 404 link --- .../distinguish-the-mutability-of-common-types.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 065c140c09..12ef6c24e8 100644 --- a/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md +++ b/python/functional-programming/python-immutability/distinguish-the-mutability-of-common-types.md @@ -5,7 +5,7 @@ category: must-know links: - >- [PYTHON OBJECTS: MUTABLE VS. - IMMUTABLE](https://codehabitude.com/2013/12/24/python-objects-mutable-vs-immutable/){website} + IMMUTABLE](https://www.geeksforgeeks.org/mutable-vs-immutable-objects-in-python/){website} practiceQuestion: formats: - fill-in-the-gap From 05fbb6dfd366aa70e6a01a521606b8c5e12fb0f3 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 5 Jan 2022 14:51:16 +0100 Subject: [PATCH 06/11] Update CHANGELOG.md --- CHANGELOG.md | 1 + 1 file changed, 1 insertion(+) diff --git a/CHANGELOG.md b/CHANGELOG.md index fd904b105c..abef2ab3da 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -52,6 +52,7 @@ Types of change: ### Changed - [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) ## January 4th 2022 From 63168da9e8a325a43f30965f71ac26d8969b00ad Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 5 Jan 2022 14:57:41 +0100 Subject: [PATCH 07/11] Update list-comprehension.md --- .../functional-programming/comprehension/list-comprehension.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/python/functional-programming/comprehension/list-comprehension.md b/python/functional-programming/comprehension/list-comprehension.md index a3689020f2..cfd08dff50 100644 --- a/python/functional-programming/comprehension/list-comprehension.md +++ b/python/functional-programming/comprehension/list-comprehension.md @@ -97,8 +97,7 @@ Use list comprehension to add one and divide by two [(x + 1) / 2] for all elemen ```python l = [1,2,3,4,5] -x = [((x+1)/2) ??? x % 2 \ - ??? x ??? x in ???] +x = [((x+1)/2) ??? x % 2 ??? x ??? x in ???] ``` - if From 675b9f40675434ae33580b5c39547a99dae5d580 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 5 Jan 2022 15:00:24 +0100 Subject: [PATCH 08/11] Update nested-lists-comprehension.md --- .../comprehension/nested-lists-comprehension.md | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/python/functional-programming/comprehension/nested-lists-comprehension.md b/python/functional-programming/comprehension/nested-lists-comprehension.md index bebf08f154..ddc22493c5 100644 --- a/python/functional-programming/comprehension/nested-lists-comprehension.md +++ b/python/functional-programming/comprehension/nested-lists-comprehension.md @@ -33,10 +33,8 @@ 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: @@ -68,7 +66,6 @@ Use nested list comprehension to generate a list of tuples, where the first elem Ex: (1,1),(1,2),(1,3),...(9,7),(9,8),(9,9). ```python - l = [??? for x in range(10)\ if ??? for y in ???] ``` From 72006d656b811c34b1459ac3f1f6111e12b7f057 Mon Sep 17 00:00:00 2001 From: Stefan Stojanovic Date: Wed, 5 Jan 2022 15:02:04 +0100 Subject: [PATCH 09/11] Update set-comprehension.md --- .../comprehension/set-comprehension.md | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/python/functional-programming/comprehension/set-comprehension.md b/python/functional-programming/comprehension/set-comprehension.md index 8ae40ad31e..d9efade59d 100644 --- a/python/functional-programming/comprehension/set-comprehension.md +++ b/python/functional-programming/comprehension/set-comprehension.md @@ -33,7 +33,6 @@ 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**: @@ -47,7 +46,6 @@ We can now check the result: ```python print(even_set) # {8, 2, 4, 6} - ``` Note that the above operation would work even if my_list contained some duplicate values, e.g: @@ -66,10 +64,8 @@ since sets by definition do not allow duplicates. Fill in the following code snippet. It creates a new set that contains elements of list `l` that are even and adds one and divides by two the odd numbers: ```python - l = [10, 11, 13, 14, 18, 19] -new_set = {x ??? x % 2 == 0 else/ - ??? for x ??? l} +new_set = {x ??? x % 2 == 0 else ??? for x ??? l} ``` - if @@ -87,7 +83,6 @@ new_set = {x ??? x % 2 == 0 else/ What will the `odd_set` look like after we run the following code snippet? ```python - l = [1,3,3,2,4,5,5,8,9] odd_set = {x for x in l if x % 2} ``` From 8f0a8be16118dfbcd1836aa7a31a11c7edc35135 Mon Sep 17 00:00:00 2001 From: Stefan-Stojanovic Date: Mon, 10 Jan 2022 19:32:28 +0100 Subject: [PATCH 10/11] 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 11/11] 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