From adc474c4c95ea18f12cab5e7d5c7d57598f0f18e Mon Sep 17 00:00:00 2001 From: Stephan Spindler <25225092+s-spindler@users.noreply.github.com> Date: Wed, 27 Jul 2022 21:38:53 +0200 Subject: Add sets to empty things that are false --- python.html.markdown | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 0bd16a80..e8c7110a 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -153,13 +153,14 @@ None # => None "etc" is None # => False None is None # => True -# None, 0, and empty strings/lists/dicts/tuples all evaluate to False. +# None, 0, and empty strings/lists/dicts/tuples/sets all evaluate to False. # All other values are True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False +bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False +bool(set()) # => False #################################################### ## 2. Variables and Collections -- cgit v1.2.3 From 6c2c6b10760ae786621438cfd60dfd326d48be41 Mon Sep 17 00:00:00 2001 From: "Stanislav (Stanley) Modrak" <44023416+smith558@users.noreply.github.com> Date: Sun, 28 Aug 2022 18:45:40 +0100 Subject: Clarify casting and move bool() method section --- python.html.markdown | 16 ++++++++++++++-- 1 file changed, 14 insertions(+), 2 deletions(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index e8c7110a..0b115c4e 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -85,12 +85,24 @@ False - 5 # => -5 2 == True # => False -5 != False # => True -# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned -# Don't mix up with bool(ints) and bitwise and/or (&,|) +# None, 0, and empty strings/lists/dicts/tuples/sets all evaluate to False. +# All other values are True bool(0) # => False +bool("") # => False +bool([]) # => False +bool({}) # => False +bool(()) # => False +bool(set()) # => False bool(4) # => True bool(-6) # => True + +# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned +# Don't mix up with bool(ints) and bitwise and/or (&,|) +bool(0) # => False +bool(2) # => True 0 and 2 # => 0 +bool(-5) # => True +bool(2) # => True -5 or 0 # => -5 # Equality is == -- cgit v1.2.3 From 52617d5c82c0f5a8c50e9c75dde3918a3b81a869 Mon Sep 17 00:00:00 2001 From: Gregory Inouye <48232124+gregoryinouye@users.noreply.github.com> Date: Thu, 20 Oct 2022 11:56:59 -0700 Subject: remove duplicate truthy falsy explanation --- python.html.markdown | 9 --------- 1 file changed, 9 deletions(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 0b115c4e..4aeb93f4 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -165,15 +165,6 @@ None # => None "etc" is None # => False None is None # => True -# None, 0, and empty strings/lists/dicts/tuples/sets all evaluate to False. -# All other values are True -bool(0) # => False -bool("") # => False -bool([]) # => False -bool({}) # => False -bool(()) # => False -bool(set()) # => False - #################################################### ## 2. Variables and Collections #################################################### -- cgit v1.2.3 From e3ee5b81faad348586ff50dda2100046bd17591f Mon Sep 17 00:00:00 2001 From: "Stanislav (Stanley) Modrak" <44023416+smith558@users.noreply.github.com> Date: Wed, 26 Oct 2022 18:07:08 +0100 Subject: Update python.html.markdown --- python.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 4aeb93f4..4382181f 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Rommel Martinez", "https://ebzzry.io"] - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] - ["caminsha", "https://github.com/caminsha"] + - ["Stanislav Modrak", "https://stanislav.gq"] filename: learnpython.py --- @@ -81,7 +82,7 @@ False - 5 # => -5 # Comparison operators look at the numerical value of True and False 0 == False # => True -1 == True # => True +2 > True # => True 2 == True # => False -5 != False # => True -- cgit v1.2.3 From c86c82f4b5081f542ea580088b53574c09b6688c Mon Sep 17 00:00:00 2001 From: "Stanislav (Stanley) Modrak" <44023416+smith558@users.noreply.github.com> Date: Wed, 26 Oct 2022 18:36:17 +0100 Subject: Update python.html.markdown --- python.html.markdown | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 4aeb93f4..2f91d452 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -419,7 +419,7 @@ for animal in ["dog", "cat", "mouse"]: """ "range(number)" returns an iterable of numbers -from zero to the given number +from zero up to (but excluding) the given number prints: 0 1 @@ -628,6 +628,12 @@ def set_global_x(num): set_x(43) set_global_x(6) +""" +prints: + 43 + 5 + 6 +""" # Python has first class functions -- cgit v1.2.3 From 610676c76efa7532975cfcc8dc5b8b69cdce1a84 Mon Sep 17 00:00:00 2001 From: "Stanislav (Stanley) Modrak" <44023416+smith558@users.noreply.github.com> Date: Wed, 26 Oct 2022 18:37:42 +0100 Subject: Update python.html.markdown --- python.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 2f91d452..22827963 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -9,6 +9,7 @@ contributors: - ["Rommel Martinez", "https://ebzzry.io"] - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] - ["caminsha", "https://github.com/caminsha"] + - ["Stanislav Modrak", "https://stanislav.gq"] filename: learnpython.py --- -- cgit v1.2.3 From 25e194aa0fe8cb82ca8f68c14993d31bf55bf034 Mon Sep 17 00:00:00 2001 From: "Stanislav (Stanley) Modrak" <44023416+smith558@users.noreply.github.com> Date: Wed, 26 Oct 2022 19:30:44 +0100 Subject: Update python.html.markdown --- python.html.markdown | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 22827963..687529b5 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -613,15 +613,17 @@ y = 2 x, y = swap(x, y) # => x = 2, y = 1 # (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. -# Function Scope +# global scope x = 5 def set_x(num): - # Local var x not the same as global variable x + # local scope begins here + # local var x not the same as global var x x = num # => 43 print(x) # => 43 def set_global_x(num): + # global indicates that particular var lives in the global scope global x print(x) # => 5 x = num # global var x is now set to 6 -- cgit v1.2.3 From 0dcfdfb4b4fe27dce599b10f915a55d162e6496c Mon Sep 17 00:00:00 2001 From: Norwid Behrnd Date: Tue, 8 Nov 2022 12:50:57 +0100 Subject: remove overly long lines by additional line breaks The threshold of a line considered as too long is 80 characters per line. Changes introduced only alter the use of line breaks. --- python.html.markdown | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 687529b5..72dd45a6 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -13,11 +13,13 @@ contributors: filename: learnpython.py --- -Python was created by Guido van Rossum in the early 90s. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. It's basically -executable pseudocode. +Python was created by Guido van Rossum in the early 90s. It is now one of the +most popular languages in existence. I fell in love with Python for its +syntactic clarity. It's basically executable pseudocode. -Note: This article applies to Python 3 specifically. Check out [here](http://learnxinyminutes.com/docs/pythonlegacy/) if you want to learn the old Python 2.7 +Note: This article applies to Python 3 specifically. Check out +[here](http://learnxinyminutes.com/docs/pythonlegacy/) if you want to learn the +old Python 2.7 ```python @@ -97,8 +99,9 @@ bool(set()) # => False bool(4) # => True bool(-6) # => True -# Using boolean logical operators on ints casts them to booleans for evaluation, but their non-cast value is returned -# Don't mix up with bool(ints) and bitwise and/or (&,|) +# Using boolean logical operators on ints casts them to booleans for evaluation, +# but their non-cast value is returned. Don't mix up with bool(ints) and bitwise +# and/or (&,|) bool(0) # => False bool(2) # => True 0 and 2 # => 0 @@ -348,7 +351,7 @@ del filled_dict["one"] # Removes the key "one" from filled dict # Sets store ... well sets empty_set = set() -# Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. +# Initialize a set with a bunch of values. some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} # Similar to keys of a dictionary, elements of a set have to be immutable. @@ -533,8 +536,8 @@ our_iterable[1] # Raises a TypeError # An iterable is an object that knows how to create an iterator. our_iterator = iter(our_iterable) -# Our iterator is an object that can remember the state as we traverse through it. -# We get the next object with "next()". +# Our iterator is an object that can remember the state as we traverse through +# it. We get the next object with "next()". next(our_iterator) # => "one" # It maintains state as we iterate. @@ -719,8 +722,8 @@ class Human: # Note that the double leading and trailing underscores denote objects # or attributes that are used by Python but that live in user-controlled # namespaces. Methods(or objects or attributes) like: __init__, __str__, - # __repr__ etc. are called special methods (or sometimes called dunder methods) - # You should not invent such names on your own. + # __repr__ etc. are called special methods (or sometimes called dunder + # methods). You should not invent such names on your own. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name @@ -811,8 +814,8 @@ if __name__ == '__main__': # "species", "name", and "age", as well as methods, like "sing" and "grunt" # from the Human class, but can also have its own unique properties. -# To take advantage of modularization by file you could place the classes above in their own files, -# say, human.py +# To take advantage of modularization by file you could place the classes above +# in their own files, say, human.py # To import functions from other files use the following format # from "filename-without-extension" import "function-or-class" -- cgit v1.2.3 From 3d0ea351cb733f081d63aff337544cd1bcba41e4 Mon Sep 17 00:00:00 2001 From: Norwid Behrnd Date: Tue, 8 Nov 2022 13:33:15 +0100 Subject: remove overly long lines by edit of content Light rephrasing to stay within the constraint of 80 chars/line. The cross links at the end of the document are not affected. --- python.html.markdown | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 72dd45a6..2247f263 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -155,10 +155,10 @@ b == a # => True, a's and b's objects are equal # You can find the length of a string len("This is a string") # => 16 -# You can also format using f-strings or formatted string literals (in Python 3.6+) +# Since Python 3.6, you can use f-strings or formatted string literals. name = "Reiko" f"She said her name is {name}." # => "She said her name is Reiko" -# You can basically put any Python expression inside the braces and it will be output in the string. +# Any valid Python expression inside these braces is returned to the string. f"{name} is {len(name)} characters long." # => "Reiko is 5 characters long." # None is an object @@ -297,7 +297,7 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Note keys for dictionaries have to be immutable types. This is to ensure that # the key can be converted to a constant hash value for quick look-ups. # Immutable types include ints, floats, strings, tuples. -invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' +invalid_dict = {[1,2,3]: "123"} # => Yield a TypeError: unhashable type: 'list' valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. # Look up values with [] @@ -457,8 +457,7 @@ for i in range(4, 8, 2): print(i) """ -To loop over a list, and retrieve both the index and the value of each item in the list -prints: +Loop over a list to retrieve both the index and the value of each list item: 0 dog 1 cat 2 mouse @@ -485,10 +484,11 @@ try: # Use "raise" to raise an error raise IndexError("This is an index error") except IndexError as e: - pass # Pass is just a no-op. Usually you would do recovery here. + pass # Refrain from this, provide a recovery (next example). except (TypeError, NameError): - pass # Multiple exceptions can be handled together, if required. -else: # Optional clause to the try/except block. Must follow all except blocks + pass # Multiple exceptions can be processed jointly. +else: # Optional clause to the try/except block. Must follow + # all except blocks. print("All good!") # Runs only if the code in try raises no exceptions finally: # Execute under all circumstances print("We can clean up resources here") @@ -524,7 +524,8 @@ print(contents) filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() -print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object that implements our Iterable interface. +print(our_iterable) # => dict_keys(['one', 'two', 'three']). This is an object + # that implements our Iterable interface. # We can loop over it. for i in our_iterable: @@ -544,7 +545,8 @@ next(our_iterator) # => "one" next(our_iterator) # => "two" next(our_iterator) # => "three" -# After the iterator has returned all of its data, it raises a StopIteration exception +# After the iterator has returned all of its data, it raises a +# StopIteration exception next(our_iterator) # Raises StopIteration # We can also loop over it, in fact, "for" does this implicitly! @@ -552,7 +554,7 @@ our_iterator = iter(our_iterable) for i in our_iterator: print(i) # Prints one, two, three -# You can grab all the elements of an iterable or iterator by calling list() on it. +# You can grab all the elements of an iterable or iterator by call of list(). list(our_iterable) # => Returns ["one", "two", "three"] list(our_iterator) # => Returns [] because state is saved @@ -602,9 +604,9 @@ all_the_args(1, 2, a=3, b=4) prints: # Use * to expand tuples and use ** to expand kwargs. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -all_the_args(*args) # equivalent to all_the_args(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to all_the_args(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to all_the_args(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # equivalent: all_the_args(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent: all_the_args(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent: all_the_args(1, 2, 3, 4, a=3, b=4) # Returning multiple values (with tuple assignments) def swap(x, y): @@ -614,7 +616,7 @@ def swap(x, y): x = 1 y = 2 x, y = swap(x, y) # => x = 2, y = 1 -# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. +# (x, y) = swap(x,y) # Again the use of parenthesis is optional. # global scope x = 5 @@ -662,7 +664,7 @@ list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] # We can use list comprehensions for nice maps and filters -# List comprehension stores the output as a list which can itself be a nested list +# List comprehension stores the output as a list (which itself may be nested). [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] @@ -777,7 +779,7 @@ if __name__ == '__main__': i.say("hi") # "Ian: hi" j = Human("Joel") j.say("hello") # "Joel: hello" - # i and j are instances of type Human, or in other words: they are Human objects + # i and j are instances of type Human; i.e., they are Human objects. # Call our class method i.say(i.get_species()) # "Ian: H. sapiens" @@ -939,8 +941,8 @@ class Batman(Superhero, Bat): # However we are dealing with multiple inheritance here, and super() # only works with the next base class in the MRO list. # So instead we explicitly call __init__ for all ancestors. - # The use of *args and **kwargs allows for a clean way to pass arguments, - # with each parent "peeling a layer of the onion". + # The use of *args and **kwargs allows for a clean way to pass + # arguments, with each parent "peeling a layer of the onion". Superhero.__init__(self, 'anonymous', movie=True, superpowers=['Wealthy'], *args, **kwargs) Bat.__init__(self, *args, can_fly=False, **kwargs) @@ -1039,8 +1041,6 @@ print(say()) # Can you buy me a beer? print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ``` -## Ready For More? - ### Free Online * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -- cgit v1.2.3 From 4d6309b2bde3c927691b15d049ef7a31c678e1f1 Mon Sep 17 00:00:00 2001 From: Marcel Ribeiro Dantas Date: Thu, 1 Dec 2022 19:29:50 -0300 Subject: Add missing json import --- python.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 2247f263..175f17ec 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -503,6 +503,7 @@ contents = {"aa": 12, "bb": 21} with open("myfile1.txt", "w+") as file: file.write(str(contents)) # writes a string to a file +import json with open("myfile2.txt", "w+") as file: file.write(json.dumps(contents)) # writes an object to a file -- cgit v1.2.3 From 97806f674f78b9adffb51127039d98b02a666e60 Mon Sep 17 00:00:00 2001 From: John Paul Wohlscheid Date: Wed, 15 Feb 2023 13:26:47 -0500 Subject: removed tutorial that no longer exists --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 175f17ec..c157750f 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -10,6 +10,7 @@ contributors: - ["Roberto Fernandez Diaz", "https://github.com/robertofd1995"] - ["caminsha", "https://github.com/caminsha"] - ["Stanislav Modrak", "https://stanislav.gq"] + - ["John Paul Wohlscheid", "https://gitpi.us"] filename: learnpython.py --- @@ -1045,7 +1046,6 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Free Online * [Automate the Boring Stuff with Python](https://automatetheboringstuff.com) -* [Ideas for Python Projects](http://pythonpracticeprojects.com) * [The Official Docs](https://docs.python.org/3/) * [Hitchhiker's Guide to Python](https://docs.python-guide.org/en/latest/) * [Python Course](https://www.python-course.eu) -- cgit v1.2.3 From 73584a2e276cd52214f73443eda689c773973691 Mon Sep 17 00:00:00 2001 From: "Stanislav (Stanley) Modrak" <44023416+smith558@users.noreply.github.com> Date: Fri, 25 Aug 2023 04:52:13 +0100 Subject: Clarify "Method Resolution Order" (#4687) --- python.html.markdown | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index d9eda60c..d9261ff2 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -876,7 +876,8 @@ if __name__ == '__main__': if type(sup) is Superhero: print('I am a superhero') - # Get the Method Resolution search Order used by both getattr() and super() + # Get the "Method Resolution Order" used by both getattr() and super() + # (the order in which classes are searched for an attribute or method) # This attribute is dynamic and can be updated print(Superhero.__mro__) # => (, # => , ) @@ -958,8 +959,7 @@ class Batman(Superhero, Bat): if __name__ == '__main__': sup = Batman() - # Get the Method Resolution search Order used by both getattr() and super(). - # This attribute is dynamic and can be updated + # The Method Resolution Order print(Batman.__mro__) # => (, # => , # => , -- cgit v1.2.3 From 7b2491ecd5b3370b7cc712fced32b948440ecb40 Mon Sep 17 00:00:00 2001 From: triumphantomato <91909240+triumphantomato@users.noreply.github.com> Date: Thu, 7 Sep 2023 22:29:58 -0700 Subject: [python/en] Updated Decorator and wrapping explanation (#4749) Now it includes motivation, an explanation of functools.wraps, and demonstrates the utility of wrapping. --- python.html.markdown | 70 +++++++++++++++++++++++++++++++++++++++------------- 1 file changed, 53 insertions(+), 17 deletions(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index d9261ff2..91a53360 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -1016,31 +1016,67 @@ gen_to_list = list(values) print(gen_to_list) # => [-1, -2, -3, -4, -5] -# Decorators -# In this example `beg` wraps `say`. If say_please is True then it -# will change the returned message. -from functools import wraps +# Decorators are a form of syntactic sugar. +# They make code easier to read while accomplishing clunky syntax. +# Wrappers are one type of decorator. +# They're really useful for adding logging to existing functions without needing to modify them. -def beg(target_function): - @wraps(target_function) +def log_function(func): def wrapper(*args, **kwargs): - msg, say_please = target_function(*args, **kwargs) - if say_please: - return "{} {}".format(msg, "Please! I am poor :(") - return msg - + print("Entering function", func.__name__) + result = func(*args, **kwargs) + print("Exiting function", func.__name__) + return result return wrapper +@log_function # equivalent: +def my_function(x,y): # def my_function(x,y): + return x+y # return x+y + # my_function = log_function(my_function) +# The decorator @log_function tells us as we begin reading the function definition +# for my_function that this function will be wrapped with log_function. +# When function definitions are long, it can be hard to parse the non-decorated +# assignment at the end of the definition. + +my_function(1,2) # => "Entering function my_function" + # => "3" + # => "Exiting function my_function" + +# But there's a problem. +# What happens if we try to get some information about my_function? + +print(my_function.__name__) # => 'wrapper' +print(my_function.__code__.co_argcount) # => 0. The argcount is 0 because both arguments in wrapper()'s signature are optional. + +# Because our decorator is equivalent to my_function = log_function(my_function) +# we've replaced information about my_function with information from wrapper + +# Fix this using functools + +from functools import wraps + +def log_function(func): + @wraps(func) # this ensures docstring, function name, arguments list, etc. are all copied + # to the wrapped function - instead of being replaced with wrapper's info + def wrapper(*args, **kwargs): + print("Entering function", func.__name__) + result = func(*args, **kwargs) + print("Exiting function", func.__name__) + return result + return wrapper -@beg -def say(say_please=False): - msg = "Can you buy me a beer?" - return msg, say_please +@log_function +def my_function(x,y): + return x+y + +my_function(1,2) # => "Entering function my_function" + # => "3" + # => "Exiting function my_function" +print(my_function.__name__) # => 'my_function' +print(my_function.__code__.co_argcount) # => 2 -print(say()) # Can you buy me a beer? -print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ``` ### Free Online -- cgit v1.2.3 From e9f263a75f0ec9c2984307d0fd4503f8476c02fa Mon Sep 17 00:00:00 2001 From: triumphantomato <91909240+triumphantomato@users.noreply.github.com> Date: Thu, 7 Sep 2023 22:30:31 -0700 Subject: [python/en] add hint about leading underscore indicating internal use (#4748) --- python.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 91a53360..efeb0e86 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -733,7 +733,9 @@ class Human: self.name = name # Initialize property - self._age = 0 + self._age = 0 # the leading underscore indicates the "age" property is + # intended to be used internally + # do not rely on this to be enforced: it's a hint to other devs # An instance method. All methods take "self" as the first argument def say(self, msg): -- cgit v1.2.3 From 4c6be14b8acf5f0f3495d06249406edc5dde72f2 Mon Sep 17 00:00:00 2001 From: triumphantomato <91909240+triumphantomato@users.noreply.github.com> Date: Thu, 7 Sep 2023 22:31:15 -0700 Subject: Update expected results for ceil and floor (#4747) ceil and floor return ints not floats - check in repl or the python3 docs here: https://docs.python.org/3/library/math.html --- python.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index efeb0e86..326ddb95 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -685,8 +685,8 @@ print(math.sqrt(16)) # => 4.0 # You can get specific functions from a module from math import ceil, floor -print(ceil(3.7)) # => 4.0 -print(floor(3.7)) # => 3.0 +print(ceil(3.7)) # => 4 +print(floor(3.7)) # => 3 # You can import all functions from a module. # Warning: this is not recommended -- cgit v1.2.3 From 38bf258ad82363e8a8eb06064b223aa2354b0186 Mon Sep 17 00:00:00 2001 From: "Stanislav (Stanley) Modrak" <44023416+smith558@users.noreply.github.com> Date: Wed, 20 Sep 2023 12:51:11 +0100 Subject: Fix incorrect expression description --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 326ddb95..c9eac8ae 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -226,7 +226,7 @@ li[4] # Raises an IndexError li[1:3] # Return list from index 1 to 3 => [2, 4] li[2:] # Return list starting from index 2 => [4, 3] li[:3] # Return list from beginning until index 3 => [1, 2, 4] -li[::2] # Return list selecting every second entry => [1, 4] +li[::2] # Return list selecting elements with a step size of 2 => [1, 4] li[::-1] # Return list in reverse order => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] -- cgit v1.2.3 From 0a0b3555d5e9923907bb2b8e953a11c5b94a1464 Mon Sep 17 00:00:00 2001 From: "Stanislav (Stanley) Modrak" <44023416+smith558@users.noreply.github.com> Date: Thu, 21 Sep 2023 17:26:42 +0100 Subject: Clarify args and kwargs --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index c9eac8ae..75b1ec85 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -603,7 +603,7 @@ all_the_args(1, 2, a=3, b=4) prints: """ # When calling functions, you can do the opposite of args/kwargs! -# Use * to expand tuples and use ** to expand kwargs. +# Use * to expand args (tuples) and use ** to expand kwargs (dictionaries). args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} all_the_args(*args) # equivalent: all_the_args(1, 2, 3, 4) -- cgit v1.2.3 From 9e87e133a35ba1033e2627ff0e2ad3f0f482ca0f Mon Sep 17 00:00:00 2001 From: Carlos Tafur Date: Thu, 14 Dec 2023 16:23:10 +0100 Subject: Update python.html.markdown (#4228) I read somewhere that conventions in naming variables are snake_case and camelCase. --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 75b1ec85..49b46711 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -185,7 +185,7 @@ print("Hello, World", end="!") # => Hello, World! input_string_var = input("Enter some data: ") # Returns the data as a string # There are no declarations, only assignments. -# Convention is to use lower_case_with_underscores +# Convention in naming variables is snake_case style some_var = 5 some_var # => 5 -- cgit v1.2.3 From 05aa44a0419b735dcb6d5e63347c1e0d4ba9fc8e Mon Sep 17 00:00:00 2001 From: Mohammed Ashour Date: Thu, 14 Dec 2023 19:58:53 +0100 Subject: =?UTF-8?q?[python/en]=20adding=20an=20example=20for=20closures=20?= =?UTF-8?q?in=20python=20where=20we=20use=20the=20`nonlocal`=20=E2=80=A6?= =?UTF-8?q?=20(#4033)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * adding an example for closures in python where we use the `nonlocal` keyword Adding an example for the case of nested functions with closure scopes, when we use the python 3s keyword 'nonlocal' to point to the variables in the outer functions * Formatting Comments --- python.html.markdown | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 49b46711..967c2bd7 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -655,6 +655,22 @@ def create_adder(x): add_10 = create_adder(10) add_10(3) # => 13 +# Closures in nested functions: +# We can use the nonlocal keyword to work with variables in nested scope which shouldn't be declared in the inner functions. +def create_avg(): + total = 0 + count = 0 + def avg(n): + nonlocal total, count + total += n + count += 1 + return total/count + return avg +avg = create_avg() +avg(3) # => 3.0 +avg(5) # (3+5)/2 => 4.0 +avg(7) # (8+7)/2 => 5.0 + # There are also anonymous functions (lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 -- cgit v1.2.3 From e268272771f19189c758280b5b27aad39c94fef1 Mon Sep 17 00:00:00 2001 From: bkkavin <70782359+bkkavin@users.noreply.github.com> Date: Mon, 18 Dec 2023 21:00:36 +0530 Subject: typo in learn x in y minutes python page (#4812) --- python.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python.html.markdown') diff --git a/python.html.markdown b/python.html.markdown index 967c2bd7..d863bcc3 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -669,7 +669,7 @@ def create_avg(): avg = create_avg() avg(3) # => 3.0 avg(5) # (3+5)/2 => 4.0 -avg(7) # (8+7)/2 => 5.0 +avg(7) # (8+7)/3 => 5.0 # There are also anonymous functions (lambda x: x > 2)(3) # => True -- cgit v1.2.3