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 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 From 30e364f4108fc077343a8722f3d80150f0d250fe Mon Sep 17 00:00:00 2001 From: Louis Christopher Date: Sat, 21 Nov 2015 19:28:59 +0530 Subject: Fixed erroneous output stated in a comment range( start = lower limit, End is < Upper limit , Step) The upper limit is never printed. Fixed the error. --- 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 1f9d0e42..3ba57738 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -425,7 +425,6 @@ 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) -- cgit v1.2.3 From 3c4a2ff91c6d52ccc928e1c26a28e1fdcbc7c064 Mon Sep 17 00:00:00 2001 From: Louis Christopher Date: Sat, 21 Nov 2015 19:44:23 +0530 Subject: Fixed erroneous output and added a little clarity on the matter list.index(argument) would return the index of the item in the list that first matched the argument It will not return the value stored at the index of the argument as it was prior. Added some more clarity to the subject as well. --- 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 3ba57738..8cc03320 100644 --- a/python3.html.markdown +++ b/python3.html.markdown @@ -224,8 +224,8 @@ 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 +# Get the index of the first item found matching the argument +li.index(2) # => 1 li.index(4) # Raises a ValueError as 4 is not in the list # You can add lists -- cgit v1.2.3