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 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