diff options
Diffstat (limited to 'python.html.markdown')
| -rw-r--r-- | python.html.markdown | 140 | 
1 files changed, 100 insertions, 40 deletions
| diff --git a/python.html.markdown b/python.html.markdown index 42a52bcf..55f56071 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -8,20 +8,22 @@ contributors:  filename: learnpython.py  --- -Python was created by Guido Van Rossum in the early 90s. It is now one of the most popular -languages in existence. I fell in love with Python for its syntactic clarity. It's basically -executable pseudocode. +Python was created by Guido Van Rossum in the early 90s. It is now one of the +most popular languages in existence. I fell in love with Python for its +syntactic clarity. It's basically executable pseudocode. -Feedback would be highly appreciated! You can reach me at [@louiedinh](http://twitter.com/louiedinh) or louiedinh [at] [google's email service] +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 2.7 specifically, but should be applicable -to Python 2.x. Python 2.7 is reachong end of life and will stop beeign maintained in 2020, -it is though recommended to start learnign Python with Python 3. -For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). +to Python 2.x. Python 2.7 is reaching end of life and will stop being +maintained in 2020, it is though recommended to start learning Python with +Python 3. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). -It is also possible to write Python code which is compatible with Python 2.7 and 3.x at the same time, -using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports -allow you to write Python 3 code that will run on Python 2, so check out the Python 3 tutorial. +It is also possible to write Python code which is compatible with Python 2.7 +and 3.x at the same time, using Python [`__future__` imports](https://docs.python.org/2/library/__future__.html). `__future__` imports +allow you to write Python 3 code that will run on Python 2, so check out the +Python 3 tutorial.  ```python @@ -32,6 +34,7 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt      as comments  """ +  ####################################################  ## 1. Primitive Datatypes and Operators  #################################################### @@ -63,7 +66,7 @@ allow you to write Python 3 code that will run on Python 2, so check out the Pyt  # to carry out normal division with just one '/'.  from __future__ import division  11/4    # => 2.75  ...normal division -11//4   # => 2 ...floored division   +11//4   # => 2 ...floored division  # Modulo operation  7 % 3 # => 1 @@ -123,11 +126,19 @@ not False  # => True  # A string can be treated like a list of characters  "This is a string"[0]  # => 'T' -# % can be used to format strings, like this: -"%s can be %s" % ("strings", "interpolated") +# You can find the length of a string +len("This is a string")  # => 16 + +#String formatting with % +#Even though the % string operator will be deprecated on Python 3.1 and removed +#later at some time, it may still be good to know how it works. +x = 'apple' +y = 'lemon' +z = "The items in the basket are %s and %s" % (x,y)  # A newer way to format strings is the format method.  # This method is the preferred way +"{} is a {}".format("This", "placeholder")  "{0} can be {1}".format("strings", "formatted")  # You can use keywords if you don't want to count.  "{name} wants to eat {food}".format(name="Bob", food="lasagna") @@ -144,8 +155,16 @@ None is None  # => True  # very useful when dealing with primitive values, but is  # very useful when dealing with objects. -# None, 0, and empty strings/lists all evaluate to False. -# All other values are True +# Any object can be used in a Boolean context. +# The following values are considered falsey: +#    - None +#    - zero of any numeric type (e.g., 0, 0L, 0.0, 0j) +#    - empty sequences (e.g., '', (), []) +#    - empty containers (e.g., {}, set()) +#    - instances of user-defined classes meeting certain conditions +#      see: https://docs.python.org/2/reference/datamodel.html#object.__nonzero__ +# +# All other values are truthy (using the bool() function on them returns True).  bool(0)  # => False  bool("")  # => False @@ -175,6 +194,7 @@ some_other_var  # Raises a name error  # Equivalent of C's '?:' ternary operator  "yahoo!" if 3 > 2 else 2  # => "yahoo!" +  # Lists store sequences  li = []  # You can start with a prefilled list @@ -234,7 +254,7 @@ li.remove(2)  # Raises a ValueError as 2 is not in the list  li.insert(1, 2)  # li is now [1, 2, 3, 4, 5, 6] again  # Get the index of the first item found -li.index(2)  # => 3 +li.index(2)  # => 1  li.index(7)  # Raises a ValueError as 7 is not in the list  # Check for existence in a list with "in" @@ -257,8 +277,9 @@ tup[:2]   # => (1, 2)  # 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 +d, e, f = 4, 5, 6       # you can leave out the parentheses  # Tuples are created by default if you leave out the parentheses -d, e, f = 4, 5, 6 +g = 4, 5, 6             # => (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 @@ -280,6 +301,9 @@ filled_dict.keys()   # => ["three", "two", "one"]  filled_dict.values()   # => [3, 2, 1]  # Note - Same as above regarding key ordering. +# Get all key-value pairs as a list of tuples with "items()" +filled_dicts.items()    # => [("one", 1), ("two", 2), ("three", 3)] +  # Check for existence of keys in a dictionary with "in"  "one" in filled_dict   # => True  1 in filled_dict   # => False @@ -427,6 +451,7 @@ with open("myfile.txt") as f:      for line in f:          print line +  ####################################################  ## 4. Functions  #################################################### @@ -444,15 +469,14 @@ add(y=6, x=5)   # Keyword arguments can arrive in any order.  # You can define functions that take a variable number of -# positional args, which will be interpreted as a tuple if you do not use the * +# positional args, which will be interpreted as a tuple by using *  def varargs(*args):      return args  varargs(1, 2, 3)   # => (1, 2, 3) -  # You can define functions that take a variable number of -# keyword args, as well, which will be interpreted as a dict if you do not use ** +# keyword args, as well, which will be interpreted as a dict by using **  def keyword_args(**kwargs):      return kwargs @@ -525,6 +549,10 @@ filter(lambda x: x > 5, [3, 4, 5, 6, 7])   # => [6, 7]  [add_10(i) for i in [1, 2, 3]]  # => [11, 12, 13]  [x for x in [3, 4, 5, 6, 7] if x > 5]   # => [6, 7] +# You can construct set and dict comprehensions as well. +{x for x in 'abcddeef' if x in 'abc'}  # => {'d', 'e', 'f'} +{x: x**2 for x in range(5)}  # => {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} +  ####################################################  ## 5. Classes @@ -643,34 +671,67 @@ math.sqrt == m.sqrt == sqrt  # => True  import math  dir(math) +# If you have a Python script named math.py in the same +# folder as your current script, the file math.py will +# be loaded instead of the built-in Python module. +# This happens because the local folder has priority +# over Python's built-in libraries. +  ####################################################  ## 7. Advanced  #################################################### -# Generators help you make lazy code +# Generators +# A generator "generates" values as they are requested instead of storing +# everything up front + +# The following method (*NOT* a generator) will double all values and store it +# in `double_arr`. For large size of iterables, that might get huge!  def double_numbers(iterable): +    double_arr = [] +    for i in iterable: +        double_arr.append(i + i) + +# Running the following would mean we'll double all values first and return all +# of them back to be checked by our condition +for value in double_numbers(range(1000000)):  # `test_non_generator` +    print value +    if value > 5: +        break + +# We could instead use a generator to "generate" the doubled value as the item +# is being requested +def double_numbers_generator(iterable):      for i in iterable:          yield i + i -# A generator creates values on the fly. -# Instead of generating and returning all values at once it creates one in each -# iteration.  This means values bigger than 15 wont be processed in -# double_numbers. -# Note xrange is a generator that does the same thing range does. -# Creating a list 1-900000000 would take lot of time and space to be made. -# xrange creates an xrange generator object instead of creating the entire list -# like range does. -# We use a trailing underscore in variable names when we want to use a name that -# would normally collide with a python keyword -xrange_ = xrange(1, 900000000) - -# will double all numbers until a result >=30 found -for i in double_numbers(xrange_): -    print i -    if i >= 30: +# Running the same code as before, but with a generator, now allows us to iterate +# over the values and doubling them one by one as they are being consumed by +# our logic. Hence as soon as we see a value > 5, we break out of the +# loop and don't need to double most of the values sent in (MUCH FASTER!) +for value in double_numbers_generator(xrange(1000000)):  # `test_generator` +    print value +    if value > 5:          break +# BTW: did you notice the use of `range` in `test_non_generator` and `xrange` in `test_generator`? +# Just as `double_numbers_generator` is the generator version of `double_numbers` +# We have `xrange` as the generator version of `range` +# `range` would return back and array with 1000000 values for us to use +# `xrange` would generate 1000000 values for us as we request / iterate over those items + +# Just as you can create a list comprehension, you can create generator +# comprehensions as well. +values = (-x for x in [1,2,3,4,5]) +for x in values: +    print(x)  # prints -1 -2 -3 -4 -5 to console/terminal + +# You can also cast a generator comprehension directly to a list. +values = (-x for x in [1,2,3,4,5]) +gen_to_list = list(values) +print(gen_to_list)  # => [-1, -2, -3, -4, -5] +  # Decorators  # in this example beg wraps say @@ -678,7 +739,6 @@ for i in double_numbers(xrange_):  # message  from functools import wraps -  def beg(target_function):      @wraps(target_function)      def wrapper(*args, **kwargs): @@ -689,13 +749,11 @@ def beg(target_function):      return wrapper -  @beg  def say(say_please=False):      msg = "Can you buy me a beer?"      return msg, say_please -  print say()  # Can you buy me a beer?  print say(say_please=True)  # Can you buy me a beer? Please! I am poor :(  ``` @@ -712,6 +770,8 @@ print say(say_please=True)  # Can you buy me a beer? Please! I am poor :(  * [Python Module of the Week](http://pymotw.com/2/)  * [A Crash Course in Python for Scientists](http://nbviewer.ipython.org/5920182)  * [First Steps With Python](https://realpython.com/learn/python-first-steps/) +* [LearnPython](http://www.learnpython.org/) +* [Fullstack Python](https://www.fullstackpython.com/)  ### Dead Tree | 
