From 674284cfcb0fa3194ad854d711288ec9aa5b98e9 Mon Sep 17 00:00:00 2001 From: maniexx Date: Mon, 22 Dec 2014 15:24:09 +0100 Subject: Delete PYMOTW3 due to lack of content --- 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 f6babaff..8bcc85d1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -609,7 +609,6 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [The Official Docs](http://docs.python.org/3/) * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/) -* [Python Module of the Week](http://pymotw.com/3/) * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182) ### Dead Tree -- cgit v1.2.3 From f4bd1bc8b462e09330ae22ae89a72c11354aa8ac Mon Sep 17 00:00:00 2001 From: suuuzi Date: Wed, 4 Feb 2015 15:32:55 -0200 Subject: Python 3: Changing 'the other tutorial' to a link refering the other tutorial --- 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 6b1d3156..0293d7d2 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -13,7 +13,7 @@ executable pseudocode. Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] -Note: This article applies to Python 3 specifically. Check out the other tutorial 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/python/) if you want to learn the old Python 2.7 ```python -- cgit v1.2.3 From 7e7a60d47ce0113e1a5b4ee8642984c60a08f569 Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Tue, 24 Mar 2015 12:29:01 +0200 Subject: Update python3.html.markdown. Changes to spacing and online resources 1. Some changes related to spacing 2. Added an online resource --- python3.html.markdown | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 0293d7d2..e8913267 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -276,7 +276,7 @@ empty_set = set() # Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} -#Can set new variables to a set +# Can set new variables to a set filled_set = some_set # Add one more item to the set @@ -394,7 +394,6 @@ our_iterator.__next__() # Raises StopIteration list(filled_dict.keys()) #=> Returns ["one", "two", "three"] - #################################################### ## 4. Functions #################################################### @@ -410,7 +409,6 @@ add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 # Another way to call functions is with keyword arguments add(y=6, x=5) # Keyword arguments can arrive in any order. - # You can define functions that take a variable number of # positional arguments def varargs(*args): @@ -418,7 +416,6 @@ def varargs(*args): varargs(1, 2, 3) # => (1, 2, 3) - # You can define functions that take a variable number of # keyword arguments, as well def keyword_args(**kwargs): @@ -636,6 +633,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [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) ### Dead Tree -- cgit v1.2.3 From 44c37d5531d42a73b0bde49525e586b413489caf Mon Sep 17 00:00:00 2001 From: Cornel Punga Date: Tue, 24 Mar 2015 19:26:19 +0200 Subject: [python3.html.mardown] Added a short statement about magic methods Terminology related to Python special functions --- python3.html.markdown | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index e8913267..56126ad3 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -498,7 +498,9 @@ class Human(object): # 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 - # namespaces. You should not invent such names on your own. + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called magic 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 -- cgit v1.2.3 From d20eb1fb94c819283e610bbd9f1cf3cea834da46 Mon Sep 17 00:00:00 2001 From: Sriram Sundarraj Date: Thu, 23 Apr 2015 01:48:18 +0530 Subject: Adding strings without + added. --- 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 56126ad3..6c5e1059 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -101,6 +101,8 @@ False or True #=> True # Strings can be added too! But try not to do this. "Hello " + "world!" # => "Hello world!" +# Strings can be added without using '+' +"Hello " "world!" # => "Hello world!" # A string can be treated like a list of characters "This is a string"[0] # => 'T' -- cgit v1.2.3 From 8cfb7ba02f7d53b6b33ff5e776289ee4fcb48618 Mon Sep 17 00:00:00 2001 From: Sriram Sundarraj Date: Thu, 23 Apr 2015 02:06:43 +0530 Subject: [python/en] Range function arguments. Range function with start and stop. --- python3.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 6c5e1059..470eb6e4 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -339,6 +339,18 @@ prints: for i in range(4): print(i) +""" +"range(lower, upper)" returns a list of numbers +from the lower number to the upper number +prints: + 4 + 5 + 6 + 7 +""" +for i in range(4, 8): + print(i) + """ While loops go until a condition is no longer met. prints: -- cgit v1.2.3 From ffc5ac247c52071c3e4e639ecd363c4fca89bec9 Mon Sep 17 00:00:00 2001 From: Geoff Liu Date: Thu, 30 Apr 2015 23:44:09 -0600 Subject: Python3 doc cleanup --- python3.html.markdown | 42 +++++++++++++++++++++--------------------- 1 file changed, 21 insertions(+), 21 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 470eb6e4..a112912f 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -39,7 +39,7 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea # Except division which returns floats by default 35 / 5 # => 7.0 -# Result of integer division truncated down both for positive and negative. +# Result of integer division truncated down both for positive and negative. 5 // 3 # => 1 5.0 // 3.0 # => 1.0 # works on floats too -5 // 3 # => -2 @@ -73,8 +73,8 @@ False or True #=> True # Note using Bool operators with ints 0 and 2 #=> 0 -5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False +0 == False #=> True +2 == True #=> False 1 == True #=> True # Equality is == @@ -145,7 +145,7 @@ bool({}) #=> False # Python has a print function print("I'm Python. Nice to meet you!") -# No need to declare variables before assigning to them. +# No need to declare variables before assigning to them. # Convention is to use lower_case_with_underscores some_var = 5 some_var # => 5 @@ -186,7 +186,7 @@ li[2:] # => [4, 3] li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] -# Revert the list +# Return a reversed copy of the list li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] @@ -196,7 +196,7 @@ del li[2] # li is now [1, 2, 3] # You can add lists # Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] +li + other_li # => [1, 2, 3, 4, 5, 6] # Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] @@ -213,7 +213,7 @@ tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # Raises a TypeError -# You can do all those list thingies on tuples too +# You can do most of the list operations on tuples too len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) @@ -235,15 +235,15 @@ filled_dict = {"one": 1, "two": 2, "three": 3} # Look up values with [] filled_dict["one"] # => 1 -# Get all keys as a list with "keys()". -# We need to wrap the call in list() because we are getting back an iterable. We'll talk about those later. -# Note - Dictionary key ordering is not guaranteed. -# Your results might not match this exactly. +# Get all keys as an iterable with "keys()". We need to wrap the call in list() +# to turn it into a list. We'll talk about those later. Note - Dictionary key +# ordering is not guaranteed. Your results might not match this exactly. list(filled_dict.keys()) # => ["three", "two", "one"] -# Get all values as a list with "values()". Once again we need to wrap it in list() to get it out of the iterable. -# Note - Same as above regarding key ordering. +# Get all values as an iterable with "values()". Once again we need to wrap it +# in list() to get it out of the iterable. Note - Same as above regarding key +# ordering. list(filled_dict.values()) # => [3, 2, 1] @@ -281,7 +281,7 @@ some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} # Can set new variables to a set filled_set = some_set -# Add one more item to the set +# Add one more item to the set filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & @@ -328,7 +328,7 @@ for animal in ["dog", "cat", "mouse"]: print("{} is a mammal".format(animal)) """ -"range(number)" returns a list of numbers +"range(number)" returns an iterable of numbers from zero to the given number prints: 0 @@ -340,7 +340,7 @@ for i in range(4): print(i) """ -"range(lower, upper)" returns a list of numbers +"range(lower, upper)" returns an iterable of numbers from the lower number to the upper number prints: 4 @@ -458,14 +458,14 @@ all_the_args(**kwargs) # equivalent to foo(a=3, b=4) all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) -# Function Scope +# Function Scope x = 5 def setX(num): # Local var x not the same as global variable x x = num # => 43 print (x) # => 43 - + def setGlobalX(num): global x print (x) # => 5 @@ -512,8 +512,8 @@ class Human(object): # 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 - # namespaces. Methods(or objects or attributes) like: __init__, __str__, - # __repr__ etc. are called magic methods (or sometimes called dunder methods) + # namespaces. Methods(or objects or attributes) like: __init__, __str__, + # __repr__ etc. are called magic 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 @@ -600,7 +600,7 @@ def double_numbers(iterable): # double_numbers. # Note range is a generator too. Creating a list 1-900000000 would take lot of # time to be made -# We use a trailing underscore in variable names when we want to use a name that +# 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 -- cgit v1.2.3 From 55f9ff0654f6489aa53e3a799af2dd462fa9c5c8 Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 08:36:51 -0600 Subject: python/en - added two resources --- python3.html.markdown | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index a112912f..9369a3ad 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -645,15 +645,16 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [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/) ### 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) +* [Real Python](https://realpython.com/) -- cgit v1.2.3 From 5b66758d761afceb797ae0f21d5c99351d29361e Mon Sep 17 00:00:00 2001 From: Michael Herman Date: Sun, 5 Jul 2015 21:12:58 -0600 Subject: Update python3.html.markdown --- python3.html.markdown | 2 -- 1 file changed, 2 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 9369a3ad..dd57bf58 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -656,5 +656,3 @@ 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](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) -* [Real Python](https://realpython.com/) - -- cgit v1.2.3 From 8a968db2bc0f596e2e9d865b73d909b02ff774d6 Mon Sep 17 00:00:00 2001 From: Al Sweigart Date: Thu, 23 Jul 2015 11:24:40 -0700 Subject: Added links to the free book "Automate the Boring Stuff with Python" to the "Free Online" section. --- 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 dd57bf58..36298566 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -642,6 +642,7 @@ 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) -- cgit v1.2.3 From ac2dfe7dc782cf1663944c0de48f6bbe810a56d8 Mon Sep 17 00:00:00 2001 From: Genki Marshall Date: Fri, 24 Jul 2015 13:21:01 -0700 Subject: [python3/en] Use `next()` instead of `__next__()` Fixes issue #1148. The reasoning is well explained by the issue. One can also refer to the docs [0], showing it is more idiomatic to use `next()`. [0]: https://www.python.org/dev/peps/pep-3114/ #double-underscore-methods-and-built-in-functions --- python3.html.markdown | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 36298566..9d965fb1 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -394,15 +394,15 @@ our_iterable[1] # Raises a TypeError 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 by calling the __next__ function. -our_iterator.__next__() #=> "one" +# We get the next object with "next()". +next(our_iterator) #=> "one" -# It maintains state as we call __next__. -our_iterator.__next__() #=> "two" -our_iterator.__next__() #=> "three" +# It maintains state as we iterate. +next(our_iterator) #=> "two" +next(our_iterator) #=> "three" # After the iterator has returned all of its data, it gives you a StopIterator Exception -our_iterator.__next__() # Raises StopIteration +next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. list(filled_dict.keys()) #=> Returns ["one", "two", "three"] -- cgit v1.2.3 From 1b767166e112aa4cbd9758ac722f2286b534803f Mon Sep 17 00:00:00 2001 From: Denis Gladkikh Date: Tue, 1 Sep 2015 10:25:04 -0700 Subject: Python3: add finally and with statements --- python3.html.markdown | 7 +++++++ 1 file changed, 7 insertions(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 9d965fb1..fbed77fe 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -374,6 +374,13 @@ 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 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" + +# Instead of try/finally to cleanup resources you can use a with statement +with open("myfile.txt") as f: + for line in f: + print line # Python offers a fundamental abstraction called the Iterable. # An iterable is an object that can be treated as a sequence. -- cgit v1.2.3 From 11749e1ba0ac173dd609bda6928fa8b8c3421803 Mon Sep 17 00:00:00 2001 From: Foo Chuan Wei Date: Sat, 5 Sep 2015 11:10:18 +0800 Subject: Corrected Python3 print() function --- 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 fbed77fe..bd83c90b 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -375,12 +375,12 @@ except (TypeError, NameError): 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" + print ("We can clean up resources here") # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: - print line + print (line) # Python offers a fundamental abstraction called the Iterable. # An iterable is an object that can be treated as a sequence. -- cgit v1.2.3 From 1ccebdf972dd000299f48689e3c1b756761fdb64 Mon Sep 17 00:00:00 2001 From: Foo Chuan Wei Date: Sat, 5 Sep 2015 21:26:22 +0800 Subject: Update python3.html.markdown --- 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 bd83c90b..b3acb122 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -375,12 +375,12 @@ except (TypeError, NameError): 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") + print("We can clean up resources here") # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: - print (line) + print(line) # Python offers a fundamental abstraction called the Iterable. # An iterable is an object that can be treated as a sequence. -- cgit v1.2.3 From 7184d7b61d99d2de93e19edb129ea3d17809be7f Mon Sep 17 00:00:00 2001 From: Zachary Ferguson Date: Fri, 2 Oct 2015 17:24:36 -0400 Subject: Changed [python3/en] Compared is and ==. Noted that tuples of length 1 require an ending comma. Discussed that keys of dictionaries have to be immutable. Added that elements of a set have to be immutable. Included an explanation of returning multiple values with tuple assignments. Added some clarifying remarks to comments. --- python3.html.markdown | 51 ++++++++++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 48 insertions(+), 3 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index b3acb122..d70c5462 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -4,6 +4,7 @@ contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] filename: learnpython3.py --- @@ -36,7 +37,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 by default +# Except division which returns floats, real numbers, by default 35 / 5 # => 7.0 # Result of integer division truncated down both for positive and negative. @@ -51,13 +52,13 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea # Modulo operation 7 % 3 # => 1 -# Exponentiation (x to the yth power) +# Exponentiation (x**y, x to the yth power) 2**4 # => 16 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 -# Boolean values are primitives +# Boolean values are primitives (Note: the capitalization) True False @@ -95,6 +96,16 @@ False or True #=> True 1 < 2 < 3 # => True 2 < 3 < 2 # => False +# (is vs. ==) is checks if two variable refer to the same object, but == checks +# if the objects pointed to have the same values. +a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = a # Point b at what a is pointing to +b is a # => True, a and b refer to the same object +b == a # => True, a's and b's objects are equal +b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b is a # => False, a and b do not refer to the same object +b == a # => True, a's and b's objects are equal + # Strings are created with " or ' "This is a string." 'This is also a string.' @@ -145,6 +156,10 @@ bool({}) #=> False # Python has a print function print("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. +print("I'm Python. Nice to meet you!", end="") + # No need to declare variables before assigning to them. # Convention is to use lower_case_with_underscores some_var = 5 @@ -191,6 +206,9 @@ li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] +# Make a one layer deep copy using slices +li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. + # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] @@ -213,6 +231,12 @@ tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # Raises a TypeError +# Note that a tuple of length one has to have a comma after the last element but +# tuples of other lengths, even zero, do not. +type((1)) # => +type((1,)) # => +type(()) # => + # You can do most of the list operations on tuples too len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) @@ -232,6 +256,12 @@ empty_dict = {} # Here is a prefilled dictionary 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' +valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. + # Look up values with [] filled_dict["one"] # => 1 @@ -278,6 +308,10 @@ empty_set = set() # Initialize a set with a bunch of values. Yeah, it looks a bit like a dict. Sorry. 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. +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 @@ -299,6 +333,7 @@ filled_set | other_set # => {1, 2, 3, 4, 5, 6} 10 in filled_set # => False + #################################################### ## 3. Control Flow and Iterables #################################################### @@ -464,6 +499,16 @@ all_the_args(*args) # equivalent to foo(1, 2, 3, 4) all_the_args(**kwargs) # equivalent to foo(a=3, b=4) all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +# Returning multiple values (with tuple assignments) +def swap(x, y): + return y, x # Return multiple values as a tuple + # (Note: parenthesis have been excluded but can be included) +# return (y, x) # Just as valid as the above example. + +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. # Function Scope x = 5 -- cgit v1.2.3 From 82bdd1b1c8c5eaa49289d9a683bf87ed85b99be9 Mon Sep 17 00:00:00 2001 From: VeerpalB Date: Sun, 4 Oct 2015 19:41:13 -0400 Subject: Add step parameter to range function A description of the step parameter of the range function is added. An example of its use in a for loop is also given. --- python3.html.markdown | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index b3acb122..4696ae1c 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -352,6 +352,18 @@ for i in range(4, 8): print(i) """ +"range(lower, upper, step)" returns an iterable of numbers +from the lower number to the upper number, while incrementing +by step. If step is not indicated, the default value is 1. +prints: + 4 + 6 + 8 +""" +for i in range(4, 8, 2): + print(i) +""" + While loops go until a condition is no longer met. prints: 0 -- cgit v1.2.3 From 52253720456acfef35cbbcf1ea1b3d98816c0961 Mon Sep 17 00:00:00 2001 From: Zachary Ferguson Date: Sun, 4 Oct 2015 19:58:14 -0400 Subject: Fixed whitespaces Fixed the spacing to conform with standards. --- python3.html.markdown | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index d70c5462..7b6edae7 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -4,7 +4,7 @@ contributors: - ["Louie Dinh", "http://pythonpracticeprojects.com"] - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] - - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["Zachary Ferguson", "http://github.com/zfergus2"] filename: learnpython3.py --- @@ -158,7 +158,7 @@ print("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. -print("I'm Python. Nice to meet you!", end="") +print("Hello, World", end="!") # => Hello, World! # No need to declare variables before assigning to them. # Convention is to use lower_case_with_underscores @@ -501,10 +501,9 @@ all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) # Returning multiple values (with tuple assignments) def swap(x, y): - return y, x # Return multiple values as a tuple - # (Note: parenthesis have been excluded but can be included) -# return (y, x) # Just as valid as the above example. - + return y, x # Return multiple values as a tuple without the parenthesis. + # (Note: parenthesis have been excluded but can be included) + x = 1 y = 2 x, y = swap(x, y) # => x = 2, y = 1 -- cgit v1.2.3 From 777423dcc519b2f25bbcf5238c12ee3a0d4c67c9 Mon Sep 17 00:00:00 2001 From: Cadel Watson Date: Wed, 7 Oct 2015 17:01:28 +1100 Subject: Add examples of higher-order functions taking multiple arguments --- 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 971ca0a4..b8fa529c 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -550,10 +550,13 @@ add_10(3) # => 13 # There are also anonymous functions (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 map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] + filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # We can use list comprehensions for nice maps and filters -- cgit v1.2.3 From 960ee4a1856db8eadb96277bb2422edfa8f2a81c Mon Sep 17 00:00:00 2001 From: Gabriel Halley Date: Wed, 7 Oct 2015 23:11:24 -0400 Subject: removing whitespace all over --- python3.html.markdown | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 971ca0a4..acd6187c 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -96,7 +96,7 @@ False or True #=> True 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# (is vs. ==) is checks if two variable refer to the same object, but == checks +# (is vs. ==) is checks if two variable refer to the same object, but == checks # if the objects pointed to have the same values. a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] b = a # Point b at what a is pointing to @@ -256,8 +256,8 @@ empty_dict = {} # Here is a prefilled dictionary 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. +# 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' valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. @@ -423,7 +423,7 @@ 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") - + # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: -- cgit v1.2.3 From 7d8bab656f154d4a58905fa4f0063b3e3824d4cf Mon Sep 17 00:00:00 2001 From: Aayush Ranaut Date: Fri, 9 Oct 2015 18:48:40 -0400 Subject: Range is not a generator --- python3.html.markdown | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 971ca0a4..c77f644e 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -96,7 +96,7 @@ False or True #=> True 1 < 2 < 3 # => True 2 < 3 < 2 # => False -# (is vs. ==) is checks if two variable refer to the same object, but == checks +# (is vs. ==) is checks if two variable refer to the same object, but == checks # if the objects pointed to have the same values. a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] b = a # Point b at what a is pointing to @@ -256,8 +256,8 @@ empty_dict = {} # Here is a prefilled dictionary 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. +# 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' valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. @@ -423,7 +423,7 @@ 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") - + # Instead of try/finally to cleanup resources you can use a with statement with open("myfile.txt") as f: for line in f: @@ -661,8 +661,6 @@ def double_numbers(iterable): # 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. -# Note range is a generator too. Creating a list 1-900000000 would take lot of -# time to be made # 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) -- cgit v1.2.3 From 097c839b7bbf03dd2ee50c9ccabde147e6bf285e Mon Sep 17 00:00:00 2001 From: Gnomino Date: Sun, 11 Oct 2015 13:47:44 +0200 Subject: Changed way of creating classes --- 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 cd1a83cc..5a992b54 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -569,8 +569,8 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] #################################################### -# We subclass from object to get a class. -class Human(object): +# We use the "class" operator to get a class +class Human: # A class attribute. It is shared by all instances of this class species = "H. sapiens" -- cgit v1.2.3 From f77199b780a1c41df00c828dc70703fba15716ec Mon Sep 17 00:00:00 2001 From: evuez Date: Tue, 13 Oct 2015 15:09:38 +0200 Subject: Add some stuff to lists, tuples, dicts and sets Lists: added `remove`, `insert` and `index` Tuples: added extended unpacking Dictionaries: added new unpacking from Python 3.5 Sets: added ^, <=, >= operators --- python3.html.markdown | 67 ++++++++++++++++++++++++++++++++++++--------------- 1 file changed, 47 insertions(+), 20 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 87fa0b70..85f16858 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -68,15 +68,15 @@ not False # => True # Boolean Operators # Note "and" and "or" are case-sensitive -True and False #=> False -False or True #=> True +True and False # => False +False or True # => True # Note using Bool operators with ints -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True # Equality is == 1 == 1 # => True @@ -123,10 +123,10 @@ b == a # => True, a's and b's objects are equal # You can repeat the formatting arguments to save some typing. "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" # You can use keywords if you don't want to count. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" # If your Python 3 code also needs to run on Python 2.5 and below, you can also # still use the old style of formatting: @@ -145,8 +145,8 @@ None is None # => True # All other values are True bool(0) # => False bool("") # => False -bool([]) #=> False -bool({}) #=> False +bool([]) # => False +bool({}) # => False #################################################### @@ -212,6 +212,17 @@ li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. # Remove arbitrary elements from a list with "del" del li[2] # li is now [1, 2, 3] +# Remove first occurrence of a value +li.remove(2) # li is now [1, 3] +li.remove(2) # Raises a ValueError as 2 is not in the list + +# Insert an element at a specific index +li.insert(1, 2) # li is now [1, 2, 3] again + +# Get the index of the first item found +li.index(2) # => 3 +li.index(4) # Raises a ValueError as 4 is not in the list + # You can add lists # Note: values for li and for other_li are not modified. li + other_li # => [1, 2, 3, 4, 5, 6] @@ -244,11 +255,13 @@ tup[:2] # => (1, 2) 2 in tup # => True # You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +# You can also do extended unpacking +a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 # Tuples are created by default if you leave out the parentheses d, e, f = 4, 5, 6 # Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 +e, d = d, e # d is now 5 and e is now 4 # Dictionaries store mappings @@ -296,12 +309,17 @@ filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 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.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} #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 +# From Python 3.5 you can also use the additional unpacking options +{'a': 1, **{'b': 2}} # => {'a': 1, 'b': 2} +{'a': 1, **{'a': 2}} # => {'a': 2} + + # Sets store ... well sets empty_set = set() @@ -326,7 +344,16 @@ filled_set & other_set # => {3, 4, 5} filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} + +# Do set symmetric difference with ^ +{1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} + +# Check if set on the left is a superset of set on the right +{1, 2} >= {1, 2, 3} # => False + +# Check if set on the left is a subset of set on the right +{1, 2} <= {1, 2, 3} # => True # Check for existence in a set with in 2 in filled_set # => True @@ -435,7 +462,7 @@ with open("myfile.txt") as f: filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface +print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface # We can loop over it. for i in our_iterable: @@ -449,17 +476,17 @@ 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()". -next(our_iterator) #=> "one" +next(our_iterator) # => "one" # It maintains state as we iterate. -next(our_iterator) #=> "two" -next(our_iterator) #=> "three" +next(our_iterator) # => "two" +next(our_iterator) # => "three" # After the iterator has returned all of its data, it gives you a StopIterator Exception next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. -list(filled_dict.keys()) #=> Returns ["one", "two", "three"] +list(filled_dict.keys()) # => Returns ["one", "two", "three"] #################################################### -- cgit v1.2.3 From df5d2adbfe788f00cf41c3d20383b917ea35c858 Mon Sep 17 00:00:00 2001 From: evuez Date: Tue, 13 Oct 2015 16:04:02 +0200 Subject: Update contributors --- 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 85f16858..617a4fb6 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -5,6 +5,7 @@ contributors: - ["Steven Basart", "http://github.com/xksteven"] - ["Andre Polykanine", "https://github.com/Oire"] - ["Zachary Ferguson", "http://github.com/zfergus2"] + - ["evuez", "http://github.com/evuez"] filename: learnpython3.py --- -- cgit v1.2.3 From ed4fbb6aa4b60a67b6756b71a3849bf42200522e Mon Sep 17 00:00:00 2001 From: evuez Date: Tue, 13 Oct 2015 16:53:48 +0200 Subject: Add property to Classes This adds the property decorator (getter, setter, deleter) to the class example. Also update scopes functions to fit PEP8. --- python3.html.markdown | 41 ++++++++++++++++++++++++++++++++++++----- 1 file changed, 36 insertions(+), 5 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 617a4fb6..38758078 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -463,7 +463,7 @@ with open("myfile.txt") as f: filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() -print(our_iterable) # => range(1,10). 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: @@ -552,19 +552,19 @@ x, y = swap(x, y) # => x = 2, y = 1 # Function Scope x = 5 -def setX(num): +def set_x(num): # Local var x not the same as global variable x x = num # => 43 print (x) # => 43 -def setGlobalX(num): +def set_global_x(num): global x print (x) # => 5 x = num # global var x is now set to 6 print (x) # => 6 -setX(43) -setGlobalX(6) +set_x(43) +set_global_x(6) # Python has first class functions @@ -613,6 +613,9 @@ class Human: # Assign the argument to the instance's name attribute self.name = name + # Initialize property + self.age = 0 + # An instance method. All methods take "self" as the first argument def say(self, msg): return "{name}: {message}".format(name=self.name, message=msg) @@ -628,6 +631,23 @@ class Human: def grunt(): return "*grunt*" + # A property is just like a getter. + # It turns the method age() into an read-only attribute + # of the same name. + @property + def age(self): + return self._age + + # This allows the property to be set + @age.setter + def age(self, age): + self._age = age + + # This allows the property to be deleted + @age.deleter + def age(self): + del self._age + # Instantiate a class i = Human(name="Ian") @@ -647,6 +667,17 @@ j.get_species() # => "H. neanderthalensis" # Call the static method Human.grunt() # => "*grunt*" +# Update the property +i.age = 42 + +# Get the property +i.age # => 42 + +# Delete the property +del i.age +i.age # => raises an AttributeError + + #################################################### ## 6. Modules -- cgit v1.2.3 From 46ef132ce697f4c44bcdea5e9e4121f82ff53333 Mon Sep 17 00:00:00 2001 From: evuez Date: Tue, 13 Oct 2015 17:05:18 +0200 Subject: Add resources to the "Free Online" section These have been valuable resources to me, but I'm not sure whether it fits this section or not. --- 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 87fa0b70..a54e7f13 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -715,6 +715,8 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [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) +* [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) ### Dead Tree -- cgit v1.2.3 From 8166438016b7028149c00649a2a33480c6701306 Mon Sep 17 00:00:00 2001 From: evuez Date: Tue, 13 Oct 2015 17:11:40 +0200 Subject: Add PEP8 to "Free Online" --- 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 a54e7f13..404f08cf 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -717,6 +717,7 @@ print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( * [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) * [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/) ### Dead Tree -- cgit v1.2.3 From 518a383de1cfbe61d7758170755fba0888a4c9e4 Mon Sep 17 00:00:00 2001 From: Dillon J Byrne Date: Tue, 13 Oct 2015 20:03:46 -0500 Subject: Cleaned up formatting and clarified output Unified the formatting throughout the document, clarified the output of a few lines, and tried to make it easier to visually separate comments from code when reading. --- python3.html.markdown | 238 +++++++++++++++++++++++++------------------------- 1 file changed, 119 insertions(+), 119 deletions(-) (limited to 'python3.html.markdown') diff --git a/python3.html.markdown b/python3.html.markdown index 87fa0b70..dd22fc8e 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -33,27 +33,27 @@ Note: This article applies to Python 3 specifically. Check out [here](http://lea 3 # => 3 # Math is what you would expect -1 + 1 # => 2 -8 - 1 # => 7 +1 + 1 # => 2 +8 - 1 # => 7 10 * 2 # => 20 # Except division which returns floats, real numbers, by default 35 / 5 # => 7.0 # Result of integer division truncated down both for positive and negative. -5 // 3 # => 1 -5.0 // 3.0 # => 1.0 # works on floats too --5 // 3 # => -2 --5.0 // 3.0 # => -2.0 +5 // 3 # => 1 +5.0 // 3.0 # => 1.0 # works on floats too +-5 // 3 # => -2 +-5.0 // 3.0 # => -2.0 # When you use a float, results are floats -3 * 2.0 # => 6.0 +3 * 2.0 # => 6.0 # Modulo operation -7 % 3 # => 1 +7 % 3 # => 1 # Exponentiation (x**y, x to the yth power) -2**4 # => 16 +2**4 # => 16 # Enforce precedence with parentheses (1 + 3) * 2 # => 8 @@ -63,20 +63,20 @@ True False # negate with not -not True # => False +not True # => False not False # => True # Boolean Operators # Note "and" and "or" are case-sensitive -True and False #=> False -False or True #=> True +True and False # => False +False or True # => True # Note using Bool operators with ints -0 and 2 #=> 0 --5 or 0 #=> -5 -0 == False #=> True -2 == True #=> False -1 == True #=> True +0 and 2 # => 0 +-5 or 0 # => -5 +0 == False # => True +2 == True # => False +1 == True # => True # Equality is == 1 == 1 # => True @@ -98,13 +98,13 @@ False or True #=> True # (is vs. ==) is checks if two variable refer to the same object, but == checks # if the objects pointed to have the same values. -a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] -b = a # Point b at what a is pointing to -b is a # => True, a and b refer to the same object -b == a # => True, a's and b's objects are equal -b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] -b is a # => False, a and b do not refer to the same object -b == a # => True, a's and b's objects are equal +a = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b = a # Point b at what a is pointing to +b is a # => True, a and b refer to the same object +b == a # => True, a's and b's objects are equal +b = [1, 2, 3, 4] # Point a at a new list, [1, 2, 3, 4] +b is a # => False, a and b do not refer to the same object +b == a # => True, a's and b's objects are equal # Strings are created with " or ' "This is a string." @@ -113,24 +113,24 @@ 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 '+' -"Hello " "world!" # => "Hello world!" +"Hello " "world!" # => "Hello world!" # A string can be treated like a list of characters "This is a string"[0] # => 'T' # .format can be used to format strings, like this: -"{} can be {}".format("strings", "interpolated") +"{} can be {}".format("Strings", "interpolated") # => "Strings can be interpolated" # You can repeat the formatting arguments to save some typing. "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") -#=> "Jack be nimble, Jack be quick, Jack jump over the candle stick" +# => "Jack be nimble, Jack be quick, Jack jump over the candle stick" # You can use keywords if you don't want to count. -"{name} wants to eat {food}".format(name="Bob", food="lasagna") #=> "Bob wants to eat lasagna" +"{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" # If your Python 3 code also needs to run on Python 2.5 and below, you can also # still use the old style of formatting: -"%s can be %s the %s way" % ("strings", "interpolated", "old") +"%s can be %s the %s way" % ("Strings", "interpolated", "old") # => "Strings can be interpolated the old way" # None is an object @@ -139,14 +139,14 @@ None # => None # Don't use the equality "==" symbol to compare objects to None # Use "is" instead. This checks for equality of object identity. "etc" is None # => False -None is None # => True +None is None # => True # None, 0, and empty strings/lists/dicts all evaluate to False. # All other values are True -bool(0) # => False +bool(0) # => False bool("") # => False -bool([]) #=> False -bool({}) #=> False +bool([]) # => False +bool({}) # => False #################################################### @@ -154,11 +154,11 @@ bool({}) #=> False #################################################### # Python has a print function -print("I'm Python. Nice to meet you!") +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. -print("Hello, World", end="!") # => Hello, World! +print("Hello, World", end="!") # => Hello, World! # No need to declare variables before assigning to them. # Convention is to use lower_case_with_underscores @@ -185,7 +185,7 @@ li.pop() # => 3 and li is now [1, 2, 4] li.append(3) # li is now [1, 2, 4, 3] again. # Access a list like you would any array -li[0] # => 1 +li[0] # => 1 # Look at the last element li[-1] # => 3 @@ -194,61 +194,61 @@ 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] +li[1:3] # => [2, 4] # Omit the beginning -li[2:] # => [4, 3] +li[2:] # => [4, 3] # Omit the end -li[:3] # => [1, 2, 4] +li[:3] # => [1, 2, 4] # Select every second entry li[::2] # =>[1, 4] # Return a reversed copy of the list -li[::-1] # => [3, 4, 2, 1] +li[::-1] # => [3, 4, 2, 1] # Use any combination of these to make advanced slices # li[start:end:step] # Make a one layer deep copy using slices -li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. +li2 = li[:] # => li2 = [1, 2, 4, 3] but (li2 is li) will result in false. # Remove arbitrary elements from a list with "del" -del li[2] # li is now [1, 2, 3] +del li[2] # li is now [1, 2, 3] # You can add lists # Note: values for li and for other_li are not modified. -li + other_li # => [1, 2, 3, 4, 5, 6] +li + other_li # => [1, 2, 3, 4, 5, 6] # Concatenate lists with "extend()" -li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] +li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] # Check for existence in a list with "in" -1 in li # => True +1 in li # => True # Examine the length with "len()" -len(li) # => 6 +len(li) # => 6 # Tuples are like lists but are immutable. tup = (1, 2, 3) -tup[0] # => 1 +tup[0] # => 1 tup[0] = 3 # Raises a TypeError # Note that a tuple of length one has to have a comma after the last element but # tuples of other lengths, even zero, do not. -type((1)) # => -type((1,)) # => -type(()) # => +type((1)) # => +type((1,)) # => +type(()) # => # You can do most of the list operations on tuples too -len(tup) # => 3 -tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) -tup[:2] # => (1, 2) -2 in tup # => True +len(tup) # => 3 +tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) +tup[:2] # => (1, 2) +2 in tup # => True # You can unpack tuples (or lists) into variables -a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 +a, b, c = (1, 2, 3) # a is now 1, b is now 2 and c is now 3 # Tuples are created by default if you leave out the parentheses d, e, f = 4, 5, 6 # Now look how easy it is to swap two values -e, d = d, e # d is now 5 and e is now 4 +e, d = d, e # d is now 5 and e is now 4 # Dictionaries store mappings @@ -259,45 +259,45 @@ 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' -valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. +invalid_dict = {[1,2,3]: "123"} # => Raises a TypeError: unhashable type: 'list' +valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. # Look up values with [] -filled_dict["one"] # => 1 +filled_dict["one"] # => 1 # Get all keys as an iterable with "keys()". We need to wrap the call in list() # to turn it into a list. We'll talk about those later. Note - Dictionary key # ordering is not guaranteed. Your results might not match this exactly. -list(filled_dict.keys()) # => ["three", "two", "one"] +list(filled_dict.keys()) # => ["three", "two", "one"] # Get all values as an iterable with "values()". Once again we need to wrap it # in list() to get it out of the iterable. Note - Same as above regarding key # ordering. -list(filled_dict.values()) # => [3, 2, 1] +list(filled_dict.values()) # => [3, 2, 1] # Check for existence of keys in a dictionary with "in" -"one" in filled_dict # => True -1 in filled_dict # => False +"one" in filled_dict # => True +1 in filled_dict # => False # Looking up a non-existing key is a KeyError -filled_dict["four"] # KeyError +filled_dict["four"] # KeyError # Use "get()" method to avoid the KeyError -filled_dict.get("one") # => 1 -filled_dict.get("four") # => None +filled_dict.get("one") # => 1 +filled_dict.get("four") # => None # The get method supports a default argument when the value is missing filled_dict.get("one", 4) # => 1 -filled_dict.get("four", 4) # => 4 +filled_dict.get("four", 4) # => 4 # "setdefault()" inserts into a dictionary only if the given key isn't present filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 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.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} +#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 @@ -306,31 +306,31 @@ 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. -some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} +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. -invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' +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} +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & other_set = {3, 4, 5, 6} -filled_set & other_set # => {3, 4, 5} +filled_set & other_set # => {3, 4, 5} # Do set union with | -filled_set | other_set # => {1, 2, 3, 4, 5, 6} +filled_set | other_set # => {1, 2, 3, 4, 5, 6} # Do set difference with - -{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} +{1, 2, 3, 4} - {2, 3, 5} # => {1, 4} # Check for existence in a set with in 2 in filled_set # => True -10 in filled_set # => False +10 in filled_set # => False @@ -416,12 +416,12 @@ 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 # Pass is just a no-op. Usually you would do recovery here. 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 handled together, if required. +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 +finally: # Execute under all circumstances print("We can clean up resources here") # Instead of try/finally to cleanup resources you can use a with statement @@ -435,11 +435,11 @@ with open("myfile.txt") as f: filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() -print(our_iterable) #=> range(1,10). This is an object that implements our Iterable interface +print(our_iterable) # => range(1,10). This is an object that implements our Iterable interface # We can loop over it. for i in our_iterable: - print(i) # Prints one, two, three + print(i) # Prints one, two, three # However we cannot address elements by index. our_iterable[1] # Raises a TypeError @@ -449,17 +449,17 @@ 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()". -next(our_iterator) #=> "one" +next(our_iterator) # => "one" # It maintains state as we iterate. -next(our_iterator) #=> "two" -next(our_iterator) #=> "three" +next(our_iterator) # => "two" +next(our_iterator) # => "three" # After the iterator has returned all of its data, it gives you a StopIterator Exception -next(our_iterator) # Raises StopIteration +next(our_iterator) # Raises StopIteration # You can grab all the elements of an iterator by calling list() on it. -list(filled_dict.keys()) #=> Returns ["one", "two", "three"] +list(filled_dict.keys()) # => Returns ["one", "two", "three"] #################################################### @@ -469,20 +469,20 @@ list(filled_dict.keys()) #=> Returns ["one", "two", "three"] # Use "def" to create new functions def add(x, y): print("x is {} and y is {}".format(x, y)) - return x + y # Return values with a return statement + return x + y # Return values with a return statement # Calling functions with parameters -add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 +add(5, 6) # => prints out "x is 5 and y is 6" and returns 11 # Another way to call functions is with keyword arguments -add(y=6, x=5) # Keyword arguments can arrive in any order. +add(y=6, x=5) # Keyword arguments can arrive in any order. # You can define functions that take a variable number of # positional arguments def varargs(*args): return args -varargs(1, 2, 3) # => (1, 2, 3) +varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of # keyword arguments, as well @@ -490,7 +490,7 @@ def keyword_args(**kwargs): return kwargs # Let's call it to see what happens -keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} +keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # You can do both at once, if you like @@ -507,33 +507,33 @@ 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 foo(1, 2, 3, 4) -all_the_args(**kwargs) # equivalent to foo(a=3, b=4) -all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) +all_the_args(*args) # equivalent to foo(1, 2, 3, 4) +all_the_args(**kwargs) # equivalent to foo(a=3, b=4) +all_the_args(*args, **kwargs) # equivalent to foo(1, 2, 3, 4, a=3, b=4) # Returning multiple values (with tuple assignments) def swap(x, y): - return y, x # Return multiple values as a tuple without the parenthesis. - # (Note: parenthesis have been excluded but can be included) + return y, x # Return multiple values as a tuple without the parenthesis. + # (Note: parenthesis have been excluded but can be included) 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) # => x = 2, y = 1 +# (x, y) = swap(x,y) # Again parenthesis have been excluded but can be included. # Function Scope x = 5 def setX(num): # Local var x not the same as global variable x - x = num # => 43 - print (x) # => 43 + x = num # => 43 + print (x) # => 43 def setGlobalX(num): global x - print (x) # => 5 - x = num # global var x is now set to 6 - print (x) # => 6 + print (x) # => 5 + x = num # global var x is now set to 6 + print (x) # => 6 setX(43) setGlobalX(6) @@ -549,20 +549,20 @@ add_10 = create_adder(10) add_10(3) # => 13 # There are also anonymous functions -(lambda x: x > 2)(3) # => True -(lambda x, y: x ** 2 + y ** 2)(2, 1) # => 5 +(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 -map(add_10, [1, 2, 3]) # => [11, 12, 13] -map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] +map(add_10, [1, 2, 3]) # => [11, 12, 13] +map(max, [1, 2, 3], [4, 2, 1]) # => [4, 2, 3] -filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] +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 -[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] +[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 @@ -609,15 +609,15 @@ j = Human("Joel") print(j.say("hello")) # prints out "Joel: hello" # Call our class method -i.get_species() # => "H. sapiens" +i.get_species() # => "H. sapiens" # Change the shared attribute Human.species = "H. neanderthalensis" -i.get_species() # => "H. neanderthalensis" -j.get_species() # => "H. neanderthalensis" +i.get_species() # => "H. neanderthalensis" +j.get_species() # => "H. neanderthalensis" # Call the static method -Human.grunt() # => "*grunt*" +Human.grunt() # => "*grunt*" #################################################### @@ -630,8 +630,8 @@ print(math.sqrt(16)) # => 4 # 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.0 +print(floor(3.7)) # => 3.0 # You can import all functions from a module. # Warning: this is not recommended @@ -639,7 +639,7 @@ from math import * # You can shorten module names import math as m -math.sqrt(16) == m.sqrt(16) # => True +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 @@ -698,7 +698,7 @@ def say(say_please=False): return msg, say_please -print(say()) # Can you buy me a beer? +print(say()) # Can you buy me a beer? print(say(say_please=True)) # Can you buy me a beer? Please! I am poor :( ``` -- cgit v1.2.3 From a8b32c362bccedf01aa7bac0b77eff8f16c88482 Mon Sep 17 00:00:00 2001 From: Ankit Aggarwal Date: Wed, 14 Oct 2015 21:16:18 +0530 Subject: Added instructions for input operations in Python3 --- 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 f3f4dd37..a1125c73 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -160,6 +160,10 @@ print("I'm Python. Nice to meet you!") # => I'm Python. Nice to meet you! # Use the optional argument end to change the end character. 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. # Convention is to use lower_case_with_underscores some_var = 5 -- cgit v1.2.3 From 646eb2a2a19c4cecc20f680c959dd42da1a2961f Mon Sep 17 00:00:00 2001 From: Leslie Zhang Date: Sat, 7 Nov 2015 16:57:44 +0800 Subject: Correct math.sqrt(16) math.sqrt(16) returns 4.0 instead of 4 --- 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 2398e7ac..1f9d0e42 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -689,7 +689,7 @@ i.age # => raises an AttributeError # You can import modules import math -print(math.sqrt(16)) # => 4 +print(math.sqrt(16)) # => 4.0 # You can get specific functions from a module from math import ceil, floor -- cgit v1.2.3