From 879337f9be2ef3c6ea2b01d34d2a21ad325c6cc4 Mon Sep 17 00:00:00 2001 From: DaKnOb Date: Fri, 9 Oct 2015 13:43:57 +0300 Subject: Add Python Order Of Module Import for Python 3 --- python3.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index b3acb122..f21604e4 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -591,6 +591,11 @@ math.sqrt(16) == m.sqrt(16) # => True import math dir(math) +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. #################################################### ## 7. Advanced -- cgit v1.2.3 From d2d89cfa9742ef437e45885498677038563d56f5 Mon Sep 17 00:00:00 2001 From: Ankit Aggarwal Date: Mon, 19 Oct 2015 11:47:24 +0530 Subject: Adding documentation on ternary operator --- python3.html.markdown | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 2398e7ac..6d657395 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -174,6 +174,10 @@ some_var # => 5 # See Control Flow to learn more about exception handling. some_unknown_var # Raises a NameError +# if can be used as an expression +# Equivalent of C's '?:' ternary operator +"yahoo!" if 3 > 2 else 2 # => "yahoo!" + # Lists store sequences li = [] # You can start with a prefilled list -- cgit v1.2.3 From 9dca295c055502d333e2ab1f4a1f9ae6f39f4b9e Mon Sep 17 00:00:00 2001 From: Alfredo Canziani Date: Wed, 30 Mar 2016 11:17:12 -0400 Subject: Update python3.html.markdown `map` requires `list` in order to convert the mapping to its list. E.g. `` to `[11, 12, 13]`. --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index ea29fdba..7864ae3f 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -589,8 +589,8 @@ add_10(3) # => 13 # TODO - Fix for iterables # There are built-in higher order functions -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] +list(map(add_10, [1, 2, 3])) # => [11, 12, 13] +list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] -- cgit v1.2.3 From 6248cd1f84401548b80b48c9f1c4b55502c20095 Mon Sep 17 00:00:00 2001 From: Alfredo Canziani Date: Wed, 30 Mar 2016 11:24:05 -0400 Subject: Update python3.html.markdown The same happens for `filter`. ```pythob filter(lambda x: x > 5, [3, 4, 5, 6, 7]) list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) [6, 7] ``` --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 7864ae3f..c2454076 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -592,7 +592,7 @@ add_10(3) # => 13 list(map(add_10, [1, 2, 3])) # => [11, 12, 13] list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +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 -- cgit v1.2.3 From f75cb997b0135a2ab8341c2043dfc0b78d3f2535 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 30 Mar 2016 13:04:32 -0700 Subject: Update python3.html.markdown Remove TODO --- python3.html.markdown | 1 - 1 file changed, 1 deletion(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index c2454076..2e37fccb 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -587,7 +587,6 @@ add_10(3) # => 13 (lambda x: x > 2)(3) # => True (lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 -# TODO - Fix for iterables # There are built-in higher order functions list(map(add_10, [1, 2, 3])) # => [11, 12, 13] list(map(max, [1, 2, 3], [4, 2, 1])) # => [4, 2, 3] -- cgit v1.2.3 From 5affe64801a241c2307a3b2ec6950d1dc41f531b Mon Sep 17 00:00:00 2001 From: ven Date: Thu, 16 Jun 2016 15:19:43 +0200 Subject: String length by #1742 --- python3.html.markdown | 3 +++ 1 file changed, 3 insertions(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 2e37fccb..0f5da8f1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -119,6 +119,9 @@ b == a # => True, a's and b's objects are equal # A string can be treated like a list of characters "This is a string"[0] # => 'T' +# You can find the length of a string +len("This is a string") # => 16 + # .format can be used to format strings, like this: "{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" -- cgit v1.2.3 From e72c849556dd7ae9cd1333229b4c007a7229225f Mon Sep 17 00:00:00 2001 From: Alexandre Constantino Date: Sun, 26 Jun 2016 14:22:47 +0100 Subject: Python3/en: multiple inheritance (#2217) * Add __name__ check to make testing easier * Update say to call print. Add more usage examples * Move Modules section before Classes Makes more sense for when explaining inheritance * Add multiple inheritance example * Add examples for multiple inheritance * Add instance check examples * Fix multiple inheritance example * Add note on the __name__ variable --- python3.html.markdown | 197 +++++++++++++++++++++++++++++++++++++------------- 1 file changed, 147 insertions(+), 50 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 0f5da8f1..7f3702e6 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -601,10 +601,47 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] [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] + #################################################### -## 5. Classes +## 5. Modules #################################################### +# You can import modules +import math +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 + +# You can import all functions from a module. +# Warning: this is not recommended +from math import * + +# You can shorten module names +import math as m +math.sqrt(16) == m.sqrt(16) # => True + +# Python modules are just ordinary python files. You +# can write your own, and import them. The name of the +# module is the same as the name of the file. + +# You can find out which functions and attributes +# defines a module. +import math +dir(math) + +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. + + +#################################################### +## 6. Classes +#################################################### # We use the "class" operator to get a class class Human: @@ -627,7 +664,11 @@ class Human: # An instance method. All methods take "self" as the first argument def say(self, msg): - return "{name}: {message}".format(name=self.name, message=msg) + print ("{name}: {message}".format(name=self.name, message=msg)) + + # Another instance method + def sing(self): + return 'yo... yo... microphone check... one two... one two...' # A class method is shared among all instances # They are called with the calling class as the first argument @@ -658,71 +699,127 @@ class Human: del self._age -# Instantiate a class -i = Human(name="Ian") -print(i.say("hi")) # prints out "Ian: hi" +# When a Python interpreter reads a source file it executes all its code. +# This __name__ check makes sure this code block is only executed when this +# module is the main program. +if __name__ == '__main__': + # Instantiate a class + i = Human(name="Ian") + 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 + + # Call our class method + i.say(i.get_species()) # "Ian: H. sapiens" + # Change the shared attribute + Human.species = "H. neanderthalensis" + i.say(i.get_species()) # => "Ian: H. neanderthalensis" + j.say(j.get_species()) # => "Joel: H. neanderthalensis" + + # Call the static method + print(Human.grunt()) # => "*grunt*" + print(i.grunt()) # => "*grunt*" + + # Update the property for this instance + i.age = 42 + # Get the property + i.say(i.age) # => 42 + j.say(j.age) # => 0 + # Delete the property + del i.age + # i.age # => this would raise an AttributeError -j = Human("Joel") -print(j.say("hello")) # prints out "Joel: hello" -# Call our class method -i.get_species() # => "H. sapiens" +#################################################### +## 6.1 Multiple Inheritance +#################################################### -# Change the shared attribute -Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" +# Another class definition +class Bat: -# Call the static method -Human.grunt() # => "*grunt*" + species = 'Baty' -# Update the property -i.age = 42 + def __init__(self, can_fly=True): + self.fly = can_fly -# Get the property -i.age # => 42 + # This class also has a say method + def say(self, msg): + msg = '... ... ...' + return msg -# Delete the property -del i.age -i.age # => raises an AttributeError + # And its own method as well + def sonar(self): + return '))) ... (((' +if __name__ == '__main__': + b = Bat() + print(b.say('hello')) + print(b.fly) -#################################################### -## 6. Modules -#################################################### +# from "filename-without-extension" import "function-or-class" +from human import Human +from bat import Bat -# You can import modules -import math -print(math.sqrt(16)) # => 4.0 +# Batman inherits from both Human and Bat +class Batman(Human, Bat): -# 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 + # Batman has its own value for the species class attribute + species = 'Superhero' -# You can import all functions from a module. -# Warning: this is not recommended -from math import * + def __init__(self, *args, **kwargs): + # Typically to inherit attributes you have to call super: + #super(Batman, self).__init__(*args, **kwargs) + # 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". + Human.__init__(self, 'anonymous', *args, **kwargs) + Bat.__init__(self, *args, can_fly=False, **kwargs) + # override the value for the name attribute + self.name = 'Sad Affleck' -# You can shorten module names -import math as m -math.sqrt(16) == m.sqrt(16) # => True + def sing(self): + return 'nan nan nan nan nan batman!' -# Python modules are just ordinary python files. You -# can write your own, and import them. The name of the -# module is the same as the name of the file. -# You can find out which functions and attributes -# defines a module. -import math -dir(math) +if __name__ == '__main__': + sup = Batman() + + # Instance type checks + if isinstance(sup, Human): + print('I am human') + if isinstance(sup, Bat): + print('I am bat') + if type(sup) is Batman: + print('I am Batman') + + # Get the Method Resolution search Order used by both getattr() and super(). + # This attribute is dynamic and can be updated + print(Batman.__mro__) # => (, , , ) + + # Calls parent method but uses its own class attribute + print(sup.get_species()) # => Superhero + + # Calls overloaded method + print(sup.sing()) # => nan nan nan nan nan batman! + + # Calls method from Human, because inheritance order matters + sup.say('I agree') # => Sad Affleck: I agree + + # Call method that exists only in 2nd ancestor + print(sup.sonar()) # => ))) ... ((( + + # Inherited class attribute + sup.age = 100 + print(sup.age) + + # Inherited attribute from 2nd ancestor whose default value was overriden + print('Can I fly? ' + str(sup.fly)) + -# If you have a Python script named math.py in the same -# folder as your current script, the file math.py will -# be loaded instead of the built-in Python module. -# This happens because the local folder has priority -# over Python's built-in libraries. #################################################### ## 7. Advanced -- cgit v1.2.3 From e053806775d18e14bb5de2adcdf8369d6566ce45 Mon Sep 17 00:00:00 2001 From: "J. Ryan Rembert" Date: Sun, 3 Jul 2016 01:47:57 -0700 Subject: [python/en] Set, dict, and generator comprehensions (#2298) * Add set and dict comprehensions for python 2 and 3 * Clean up formatting and generator explanation * Include documentation for generator comprehensions --- python3.html.markdown | 38 ++++++++++++++++++++++++-------------- 1 file changed, 24 insertions(+), 14 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 7f3702e6..6b3486a6 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -601,6 +601,10 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] [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] +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} + #################################################### ## 5. Modules @@ -816,7 +820,7 @@ if __name__ == '__main__': sup.age = 100 print(sup.age) - # Inherited attribute from 2nd ancestor whose default value was overriden + # Inherited attribute from 2nd ancestor whose default value was overridden. print('Can I fly? ' + str(sup.fly)) @@ -825,29 +829,35 @@ if __name__ == '__main__': ## 7. Advanced #################################################### -# Generators help you make lazy code +# Generators help you make lazy code. def double_numbers(iterable): for i in iterable: yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration. This means values bigger than 15 wont be processed in -# double_numbers. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword -range_ = range(1, 900000000) -# will double all numbers until a result >=30 found -for i in double_numbers(range_): +# Generators are memory-efficient because they only load the data needed to +# process the next value in the iterable. This allows them to perform +# operations on otherwise prohibitively large value ranges. +# NOTE: `range` replaces `xrange` in Python 3. +for i in double_numbers(range(1, 900000000)): # `range` is a generator. print(i) if i >= 30: break +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: + print(x) # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list) # => [-1, -2, -3, -4, -5] + # Decorators -# in this example beg wraps say -# Beg will call say. If say_please is True then it will change the returned -# message +# In this example `beg` wraps `say`. If say_please is True then it +# will change the returned message. from functools import wraps -- cgit v1.2.3 From 678fa3b97468a903fc256d95c58f54db5a531a64 Mon Sep 17 00:00:00 2001 From: Patrick Callahan Date: Thu, 1 Sep 2016 02:28:23 -0400 Subject: Remove Python 2 resources from Python 3 page (#2350) There were several resources here that teach Python 2, but not Python 3. I removed them so that a reader will only see resources that apply to Python 3. --- python3.html.markdown | 5 ----- 1 file changed, 5 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 6b3486a6..09b041b8 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -887,12 +887,9 @@ 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) -* [Learn Python The Hard Way](http://learnpythonthehardway.org/book/) -* [Dive Into Python](http://www.diveintopython.net/) * [Ideas for Python Projects](http://pythonpracticeprojects.com) * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) * [Python Course](http://www.python-course.eu/index.php) * [First Steps With Python](https://realpython.com/learn/python-first-steps/) * [A curated list of awesome Python frameworks, libraries and software](https://github.com/vinta/awesome-python) @@ -903,5 +900,3 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python](http://www.amazon.com/gp/product/1441413022/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=1441413022&linkCode=as2&tag=homebits04-20) -* [Python Essential Reference](http://www.amazon.com/gp/product/0672329786/ref=as_li_tf_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0672329786&linkCode=as2&tag=homebits04-20) -- cgit v1.2.3 From 7beaa529b912ccda6e26eee85acae50e79c6d6d5 Mon Sep 17 00:00:00 2001 From: Patrick Callahan Date: Thu, 1 Sep 2016 17:27:33 -0400 Subject: [python3/en] Adding "Dive Into Python 3" (#2353) The previous version of this file had the original Dive Into Python, which was written with Python 2 in mind. It has come to my attention that the author of the original has published an updated version designed for Python 3, so I added this version back in. --- python3.html.markdown | 2 ++ 1 file changed, 2 insertions(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 09b041b8..dc534f74 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -896,7 +896,9 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [30 Python Language Features and Tricks You May Not Know About](http://sahandsaba.com/thirty-python-language-features-and-tricks-you-may-not-know.html) * [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) * [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) +* [Dive Into Python 3](http://www.diveintopython3.net/index.html) ### Dead Tree * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) +* [Dive Into Python 3](https://www.amazon.com/gp/product/1430224150?ie=UTF8&tag=diveintomark-20&creativeASIN=1430224150) -- cgit v1.2.3 From 48ca03c3f9cfa1dc18ece421e98bf62072d519f0 Mon Sep 17 00:00:00 2001 From: PhoenixYip Date: Tue, 6 Sep 2016 16:38:47 +0800 Subject: correction for the set comprehension in py3 (#2358) --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index dc534f74..5298553f 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -602,7 +602,7 @@ list(filter(lambda x: x > 5, [3, 4, 5, 6, 7])) # => [6, 7] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] # You can construct set and dict comprehensions as well. -{x for x in 'abcddeef' if x in 'abc'} # => {'d', 'e', 'f'} +{x for x in 'abcddeef' if x not in 'abc'} # => {'d', 'e', 'f'} {x: x**2 for x in range(5)} # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} -- cgit v1.2.3 From 2067ad6a5203d7799f734f5f956b10473dd56e00 Mon Sep 17 00:00:00 2001 From: Patrick Callahan Date: Tue, 6 Sep 2016 12:57:47 -0400 Subject: [Eng/Python3] add new book: "Learn Python 3.0 VISUALLY" (#2360) * add new book * sanitized link --- python3.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 5298553f..a56960a7 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -902,3 +902,4 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) * [Dive Into Python 3](https://www.amazon.com/gp/product/1430224150?ie=UTF8&tag=diveintomark-20&creativeASIN=1430224150) +* [Learn Python 3.0 VISUALLY](https://www.amazon.com/Learn-Python-3-0-VISUALLY-Interactive-ebook/dp/B00YI58B9U/) -- cgit v1.2.3 From 048163b7bff3406db6eee8b8ac0de38dedbb3b4a Mon Sep 17 00:00:00 2001 From: Subhrajyoti Sen Date: Wed, 21 Sep 2016 20:37:24 +0530 Subject: Update python3.html.markdown (#2381) --- python3.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index a56960a7..764262d9 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -897,6 +897,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [Official Style Guide for Python](https://www.python.org/dev/peps/pep-0008/) * [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) * [Dive Into Python 3](http://www.diveintopython3.net/index.html) +* [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) ### Dead Tree -- cgit v1.2.3 From 5bebeff0c32bb1ff1edbe7d1fdc68c82cbf44e11 Mon Sep 17 00:00:00 2001 From: ven Date: Tue, 4 Oct 2016 15:40:48 +0200 Subject: Update python3.html.markdown --- python3.html.markdown | 6 ------ 1 file changed, 6 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 764262d9..341f0a39 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -898,9 +898,3 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [Python 3 Computer Science Circles](http://cscircles.cemc.uwaterloo.ca/) * [Dive Into Python 3](http://www.diveintopython3.net/index.html) * [A Crash Course in Python for Scientists](http://nbviewer.jupyter.org/gist/anonymous/5924718) - -### Dead Tree - -* [Programming Python](http://www.amazon.com/gp/product/0596158106/ref=as_li_qf_sp_asin_tl?ie=UTF8&camp=1789&creative=9325&creativeASIN=0596158106&linkCode=as2&tag=homebits04-20) -* [Dive Into Python 3](https://www.amazon.com/gp/product/1430224150?ie=UTF8&tag=diveintomark-20&creativeASIN=1430224150) -* [Learn Python 3.0 VISUALLY](https://www.amazon.com/Learn-Python-3-0-VISUALLY-Interactive-ebook/dp/B00YI58B9U/) -- cgit v1.2.3 From 8905c0c5bc7f6a7947a4fd0bcef8cf085ed08366 Mon Sep 17 00:00:00 2001 From: Srinivas Gorur-Shandilya Date: Thu, 20 Oct 2016 09:57:55 -0400 Subject: [python3] updated docs on division for python3 (#2473) * updated docs on division for python3 prev. docs were confusing, did not show how to actually divide. * modified language about python division * fixed grammar --- python3.html.markdown | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 341f0a39..43e90299 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -38,7 +38,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea 8 - 1 # => 7 10 * 2 # => 20 -# Except division which returns floats, real numbers, by default +# Except division which defaults to rounding down 35 / 5 # => 7.0 # Result of integer division truncated down both for positive and negative. @@ -47,8 +47,12 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 -# When you use a float, results are floats -3 * 2.0 # => 6.0 +# When one of the inputs is a float, result is a float +10.0 / 3 # => 3.3333333333333335 + +# to force this behavior on integers, use +from __future__ import division +10 / 3 # => 3.3333333333333335 # Modulo operation 7 % 3 # => 1 -- cgit v1.2.3 From e68bf145bce6386972777745205d362f6e6d3f27 Mon Sep 17 00:00:00 2001 From: Harry Moreno Date: Thu, 20 Oct 2016 17:08:44 -0400 Subject: Add python3 class notes (#2479) * explain that you can place the human and bat classes into seperate files * explain how to import specific functions from other files --- python3.html.markdown | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 43e90299..9ce7790b 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -765,8 +765,13 @@ if __name__ == '__main__': print(b.say('hello')) print(b.fly) +# To take advantage of modularization by file you could place the classes above in their own files, +# say, human.py and bat.py +# to import functions from other files use the following format # from "filename-without-extension" import "function-or-class" + +# superhero.py from human import Human from bat import Bat -- cgit v1.2.3 From e837e25a70384d33fc3083d9f2382c31591f548e Mon Sep 17 00:00:00 2001 From: Foo Chuan Wei Date: Wed, 9 Nov 2016 13:16:06 -0500 Subject: [python3/en] Edit python3 division (#2560) The result of division is always a float. e.g. 35/5 = 7.0 10 / 3 = 3.3333333333333335 10.0 / 3 = 3.3333333333333335 10 / 3.0 = 3.3333333333333335 --- python3.html.markdown | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 9ce7790b..839d66fd 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -37,8 +37,6 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 - -# Except division which defaults to rounding down 35 / 5 # => 7.0 # Result of integer division truncated down both for positive and negative. @@ -47,13 +45,9 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 -# When one of the inputs is a float, result is a float +# The result of division is always a float 10.0 / 3 # => 3.3333333333333335 -# to force this behavior on integers, use -from __future__ import division -10 / 3 # => 3.3333333333333335 - # Modulo operation 7 % 3 # => 1 -- cgit v1.2.3 From d0918b2576abcefcfca1f439e3b03511f1be0b89 Mon Sep 17 00:00:00 2001 From: kakakaya Date: Wed, 30 Nov 2016 21:01:27 +0900 Subject: [python3/en] Add empty tuple to "False if evaluated" list (#2587) --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 839d66fd..04d103f4 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -143,13 +143,13 @@ None # => None "etc" is None # => False None is None # => True -# None, 0, and empty strings/lists/dicts all evaluate to False. +# None, 0, and empty strings/lists/dicts/tuples all evaluate to False. # All other values are True bool(0) # => False bool("") # => False bool([]) # => False bool({}) # => False - +bool(()) # => False #################################################### ## 2. Variables and Collections -- cgit v1.2.3 From c701931feebc96d8b4215dd66e268fab2c1bbacf Mon Sep 17 00:00:00 2001 From: kakakaya Date: Sat, 3 Dec 2016 19:46:32 +0900 Subject: [python3/en] fixed "StopIterator", no such Exception (#2591) * [python3/en] Add empty tuple to "False if evaluated" list * [python3/en] Fixed "StopIterator Exception" - no such exception --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 04d103f4..3821d84f 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -491,7 +491,7 @@ next(our_iterator) # => "one" next(our_iterator) # => "two" next(our_iterator) # => "three" -# After the iterator has returned all of its data, it gives you a StopIterator Exception +# After the iterator has returned all of its data, it gives you a StopIteration Exception next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. -- cgit v1.2.3 From 05e4c41cb3e912e19867f9c5adcdaa1b087722f3 Mon Sep 17 00:00:00 2001 From: ghostduck Date: Sat, 28 Jan 2017 17:38:26 +0800 Subject: [python3/en] Add examples to Bool operators with ints (#2639) --- python3.html.markdown | 3 +++ 1 file changed, 3 insertions(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 3821d84f..02745117 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -71,11 +71,14 @@ True and False # => False False or True # => True # Note using Bool operators with ints +# False is 0 and True is 1 +# Don't mix up with bool(ints) and bitwise and/or (&,|) 0 and 2 # => 0 -5 or 0 # => -5 0 == False # => True 2 == True # => False 1 == True # => True +-5 != False != True #=> True # Equality is == 1 == 1 # => True -- cgit v1.2.3 From 870e2fbf6dccfe9d769bf3d6ccae402d698322df Mon Sep 17 00:00:00 2001 From: Adrian Sieber Date: Fri, 10 Feb 2017 07:58:10 +0000 Subject: Fix omitting end / beginning in ranges (#2649) --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 02745117..596b53e6 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -208,9 +208,9 @@ li[4] # Raises an IndexError # You can look at ranges with slice syntax. # (It's a closed/open range for you mathy types.) li[1:3] # => [2, 4] -# Omit the beginning -li[2:] # => [4, 3] # Omit the end +li[2:] # => [4, 3] +# Omit the beginning li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] -- cgit v1.2.3 From 56a18f79cfdd8df12572327cd8810c9101a1ed00 Mon Sep 17 00:00:00 2001 From: lilhandsbgdreams Date: Thu, 16 Feb 2017 02:41:16 -0600 Subject: [python3/en] Fix two "getter" output examples (#2658) --- python3.html.markdown | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 596b53e6..b701d558 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -729,8 +729,8 @@ if __name__ == '__main__': # Update the property for this instance i.age = 42 # Get the property - i.say(i.age) # => 42 - j.say(j.age) # => 0 + i.say(i.age) # => "Ian: 42" + j.say(j.age) # => "Joel: 0" # Delete the property del i.age # i.age # => this would raise an AttributeError -- cgit v1.2.3 From eba9d9ffe54de39ebceb07769d1151ac3d0f5e14 Mon Sep 17 00:00:00 2001 From: Andrew Lee Date: Wed, 1 Mar 2017 01:15:36 +0900 Subject: Updated mistake in Python3/en tutorial (#2678) A fix on static method section (around line 728). Specifically, i.grunt() should raise an error since grunt() is a static method and 'i' is an instance of the class. --- python3.html.markdown | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index b701d558..6a2a7ccd 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -724,8 +724,11 @@ if __name__ == '__main__': # Call the static method print(Human.grunt()) # => "*grunt*" - print(i.grunt()) # => "*grunt*" - + + # Cannot call static method with instance of object + # because i.grunt() will automatically put "self" (the object i) as an argument + print(i.grunt()) # => TypeError: grunt() takes 0 positional arguments but 1 was given + # Update the property for this instance i.age = 42 # Get the property -- cgit v1.2.3 From 82c3ce4e8c4fc17a30290f87698ca5d25e113312 Mon Sep 17 00:00:00 2001 From: Ankush Aggarwal Date: Tue, 28 Mar 2017 01:21:18 -0700 Subject: add underscore to property (#2691) property is exposed using setter and getters --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 6a2a7ccd..a74ddd7d 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -665,7 +665,7 @@ class Human: self.name = name # Initialize property - self.age = 0 + self._age = 0 # An instance method. All methods take "self" as the first argument def say(self, msg): -- cgit v1.2.3 From e901344c04c49d63d5687dc9e1615935acb1ed13 Mon Sep 17 00:00:00 2001 From: Adam Bard Date: Wed, 5 Apr 2017 12:02:35 -0700 Subject: [Python] Slightly tweak ** example 2^4 == 4^2, 2^3 seems a bit less ambiguous as an example for exponentiation. --- python3.html.markdown | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index a74ddd7d..cb53eaf8 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -52,7 +52,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea 7 % 3 # => 1 # Exponentiation (x**y, x to the yth power) -2**4 # => 16 +2**3 # => 8 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 -- cgit v1.2.3 From 9ccd1ee05ade8f2b76d8c473f34695b775330d31 Mon Sep 17 00:00:00 2001 From: Ned Batchelder Date: Thu, 18 May 2017 06:40:25 -0400 Subject: Some improvements to Python 3 (#2713) --- python3.html.markdown | 49 ++++++++++++++++++++++++------------------------- 1 file changed, 24 insertions(+), 25 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index cb53eaf8..f25d9228 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -9,7 +9,7 @@ contributors: filename: learnpython3.py --- -Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular +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. @@ -23,7 +23,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea """ Multiline strings can be written using three "s, and are often used - as comments + as documentation. """ #################################################### @@ -114,7 +114,7 @@ b == a # => True, a's and b's objects are equal # Strings can be added too! But try not to do this. "Hello " + "world!" # => "Hello world!" -# Strings can be added without using '+' +# String literals (but not variables) can be concatenated without using '+' "Hello " "world!" # => "Hello world!" # A string can be treated like a list of characters @@ -162,14 +162,14 @@ bool(()) # => False print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! # By default the print function also prints out a newline at the end. -# Use the optional argument end to change the end character. +# Use the optional argument end to change the end string. print("Hello, World", end="!") # => Hello, World! # Simple way to get input data from console input_string_var = input("Enter some data: ") # Returns the data as a string # Note: In earlier versions of Python, input() method was named as raw_input() -# No need to declare variables before assigning to them. +# There are no declarations, only assignments. # Convention is to use lower_case_with_underscores some_var = 5 some_var # => 5 @@ -206,6 +206,7 @@ li[-1] # => 3 li[4] # Raises an IndexError # You can look at ranges with slice syntax. +# The start index is included, the end index is not # (It's a closed/open range for you mathy types.) li[1:3] # => [2, 4] # Omit the end @@ -277,7 +278,7 @@ d, e, f = 4, 5, 6 e, d = d, e # d is now 5 and e is now 4 -# Dictionaries store mappings +# Dictionaries store mappings from keys to values empty_dict = {} # Here is a prefilled dictionary filled_dict = {"one": 1, "two": 2, "three": 3} @@ -323,7 +324,7 @@ filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 # Adding to a dictionary filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} -#filled_dict["four"] = 4 #another way to add to dict +filled_dict["four"] = 4 # another way to add to dict # Remove keys from a dictionary with del del filled_dict["one"] # Removes the key "one" from filled dict @@ -343,9 +344,6 @@ some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' valid_set = {(1,), 1} -# Can set new variables to a set -filled_set = some_set - # Add one more item to the set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} @@ -381,8 +379,9 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Let's just make a variable some_var = 5 -# Here is an if statement. Indentation is significant in python! -# prints "some_var is smaller than 10" +# Here is an if statement. Indentation is significant in Python! +# Convention is to use four spaces, not tabs. +# This prints "some_var is smaller than 10" if some_var > 10: print("some_var is totally bigger than 10.") elif some_var < 10: # This elif clause is optional. @@ -470,7 +469,7 @@ with open("myfile.txt") as f: # Python offers a fundamental abstraction called the Iterable. # An iterable is an object that can be treated as a sequence. -# The object returned the range function, is an iterable. +# The object returned by the range function, is an iterable. filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() @@ -494,7 +493,7 @@ next(our_iterator) # => "one" next(our_iterator) # => "two" next(our_iterator) # => "three" -# After the iterator has returned all of its data, it gives you a StopIteration Exception +# After the iterator has returned all of its data, it raises a StopIteration exception next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. @@ -566,13 +565,13 @@ x = 5 def set_x(num): # Local var x not the same as global variable x x = num # => 43 - print (x) # => 43 + print(x) # => 43 def set_global_x(num): global x - print (x) # => 5 + print(x) # => 5 x = num # global var x is now set to 6 - print (x) # => 6 + print(x) # => 6 set_x(43) set_global_x(6) @@ -628,12 +627,12 @@ from math import * import math as m math.sqrt(16) == m.sqrt(16) # => True -# Python modules are just ordinary python files. You +# Python modules are just ordinary Python files. You # can write your own, and import them. The name of the # module is the same as the name of the file. # You can find out which functions and attributes -# defines a module. +# are defined in a module. import math dir(math) @@ -648,7 +647,7 @@ dir(math) ## 6. Classes #################################################### -# We use the "class" operator to get a class +# We use the "class" statement to create a class class Human: # A class attribute. It is shared by all instances of this class @@ -656,9 +655,9 @@ class Human: # Basic initializer, this is called when this class is instantiated. # Note that the double leading and trailing underscores denote objects - # or attributes that are used by python but that live in user-controlled + # 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 magic methods (or sometimes called dunder methods) + # __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 @@ -687,8 +686,8 @@ class Human: return "*grunt*" # A property is just like a getter. - # It turns the method age() into an read-only attribute - # of the same name. + # It turns the method age() into an read-only attribute of the same name. + # There's no need to write trivial getters and setters in Python, though. @property def age(self): return self._age @@ -768,7 +767,7 @@ if __name__ == '__main__': # To take advantage of modularization by file you could place the classes above in their own files, # say, human.py and bat.py -# to import functions from other files use the following format +# To import functions from other files use the following format # from "filename-without-extension" import "function-or-class" # superhero.py -- cgit v1.2.3 From e78e41ce3038b23288ced37e81c019074ad60db4 Mon Sep 17 00:00:00 2001 From: Alfonso Millan Date: Thu, 29 Jun 2017 01:36:01 -0700 Subject: Update python3.html.markdown (#2776) --- python3.html.markdown | 1 + 1 file changed, 1 insertion(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index f25d9228..5aa61b65 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -345,6 +345,7 @@ invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' valid_set = {(1,), 1} # Add one more item to the set +filled_set = some_set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & -- cgit v1.2.3