diff options
Diffstat (limited to 'python.html.markdown')
| -rw-r--r-- | python.html.markdown | 73 | 
1 files changed, 42 insertions, 31 deletions
| diff --git a/python.html.markdown b/python.html.markdown index da04d381..88e0deb1 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -14,7 +14,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 2.7 specifically, but should be applicable -to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial. +to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/).  ```python @@ -46,7 +46,7 @@ to Python 2.x. For Python 3.x, take a look at the Python 3 tutorial.  2.0     # This is a float  11.0 / 4.0  # => 2.75 ahhh...much better -# 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 @@ -101,6 +101,8 @@ not False  # => True  # Strings can be added too!  "Hello " + "world!"  # => "Hello world!" +# Strings can be added without using '+' +"Hello " "world!"  # => "Hello world!"  # ... or multiplied  "Hello" * 3  # => "HelloHelloHello" @@ -139,12 +141,8 @@ bool("")  # => False  ## 2. Variables and Collections  #################################################### -# Python has a print statement, in all 2.x versions but removed from 3. +# Python has a print statement  print "I'm Python. Nice to meet you!" -# Python also has a print function, available in versions 2.7 and 3... -# but for 2.7 you need to add the import (uncommented): -# from __future__ import print_function -print("I'm also Python! ")  # No need to declare variables before assigning to them.  some_var = 5    # Convention is to use lower_case_with_underscores @@ -193,14 +191,14 @@ li[2:]  # => [4, 3]  li[:3]  # => [1, 2, 4]  # Select every second entry  li[::2]   # =>[1, 4] -# Revert the list +# Reverse a copy of the list  li[::-1]   # => [3, 4, 2, 1]  # Use any combination of these to make advanced slices  # li[start:end:step]  # Remove arbitrary elements from a list with "del"  del li[2]   # li is now [1, 2, 3] - +r  # You can add lists  li + other_li   # => [1, 2, 3, 4, 5, 6]  # Note: values for li and for other_li are not modified. @@ -314,11 +312,11 @@ some_var = 5  # Here is an if statement. Indentation is significant in python!  # prints "some_var is smaller than 10"  if some_var > 10: -    print("some_var is totally bigger than 10.") +    print "some_var is totally bigger than 10."  elif some_var < 10:    # This elif clause is optional. -    print("some_var is smaller than 10.") +    print "some_var is smaller than 10."  else:           # This is optional too. -    print("some_var is indeed 10.") +    print "some_var is indeed 10."  """ @@ -329,8 +327,8 @@ prints:      mouse is a mammal  """  for animal in ["dog", "cat", "mouse"]: -    # You can use % to interpolate formatted strings -    print("%s is a mammal" % animal) +    # You can use {0} to interpolate formatted strings. (See above.) +    print "{0} is a mammal".format(animal)  """  "range(number)" returns a list of numbers @@ -342,7 +340,19 @@ prints:      3  """  for i in range(4): -    print(i) +    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. @@ -354,7 +364,7 @@ prints:  """  x = 0  while x < 4: -    print(x) +    print x      x += 1  # Shorthand for x = x + 1  # Handle exceptions with a try/except block @@ -377,7 +387,7 @@ else:   # Optional clause to the try/except block. Must follow all except blocks  # Use "def" to create new functions  def add(x, y): -    print("x is %s and y is %s" % (x, y)) +    print "x is {0} and y is {1}".format(x, y)      return x + y    # Return values with a return statement  # Calling functions with parameters @@ -406,8 +416,8 @@ keyword_args(big="foot", loch="ness")   # => {"big": "foot", "loch": "ness"}  # You can do both at once, if you like  def all_the_args(*args, **kwargs): -    print(args) -    print(kwargs) +    print args +    print kwargs  """  all_the_args(1, 2, a=3, b=4) prints:      (1, 2) @@ -429,14 +439,14 @@ def pass_all_the_args(*args, **kwargs):      print varargs(*args)      print keyword_args(**kwargs) -# 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 @@ -487,7 +497,7 @@ class Human(object):      # An instance method. All methods take "self" as the first argument      def say(self, msg): -        return "%s: %s" % (self.name, msg) +        return "{0}: {1}".format(self.name, msg)      # A class method is shared among all instances      # They are called with the calling class as the first argument @@ -503,10 +513,10 @@ class Human(object):  # Instantiate a class  i = Human(name="Ian") -print(i.say("hi"))     # prints out "Ian: hi" +print i.say("hi")     # prints out "Ian: hi"  j = Human("Joel") -print(j.say("hello"))  # prints out "Joel: hello" +print j.say("hello")  # prints out "Joel: hello"  # Call our class method  i.get_species()   # => "H. sapiens" @@ -526,12 +536,12 @@ Human.grunt()   # => "*grunt*"  # You can import modules  import math -print(math.sqrt(16))  # => 4 +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 @@ -577,7 +587,7 @@ xrange_ = xrange(1, 900000000)  # will double all numbers until a result >=30 found  for i in double_numbers(xrange_): -    print(i) +    print i      if i >= 30:          break @@ -606,24 +616,25 @@ def say(say_please=False):      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 :( +print say()  # Can you buy me a beer? +print say(say_please=True)  # Can you buy me a beer? Please! I am poor :(  ```  ## Ready For More?  ### 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/)  * [The Official Docs](http://docs.python.org/2.6/)  * [Hitchhiker's Guide to Python](http://docs.python-guide.org/en/latest/)  * [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/)  ### 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) - | 
