diff options
Diffstat (limited to 'python.html.markdown')
-rw-r--r-- | python.html.markdown | 94 |
1 files changed, 55 insertions, 39 deletions
diff --git a/python.html.markdown b/python.html.markdown index 2c08e73e..19e2aebe 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -2,19 +2,23 @@ language: python author: Louie Dinh author_url: http://ldinh.ca +filename: learnpython.py --- Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular languages in existence. I fell in love with Python for it's 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] + Note: This article applies to Python 2.7 specifically, but should be applicable to Python 2.x. Look for another tour of Python 3 soon! ```python # Single line comments start with a hash. -""" Multiline comments can we written - using three "'s +""" Multiline strings can be written + using three "'s, and are often used + as comments """ #################################################### @@ -32,11 +36,11 @@ to Python 2.x. Look for another tour of Python 3 soon! # Division is a bit tricky. It is integer division and floors the results # automatically. -11 / 4 #=> 2 +5 / 2 #=> 2 # To fix division we need to learn about floats. 2.0 # This is a float -5.0 / 2.0 #=> 2.5 ahhh...much better +11.0 / 4.0 #=> 2.75 ahhh...much better # Enforce precedence with parentheses (1 + 3) * 2 #=> 8 @@ -77,6 +81,15 @@ 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") + +# A newer way to format strings is the format method. +# This method is the preferred way +"{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") + # None is an object None #=> None @@ -93,16 +106,12 @@ print "I'm Python. Nice to meet you!" some_var = 5 # Convention is to use lower_case_with_underscores some_var #=> 5 -# Accessing a previously unassigned variable is an exception -try: - some_other_var -except NameError: - print "Raises a name error" +# Accessing a previously unassigned variable is an exception. +# See Control Flow to learn more about exception handling. +some_other_var # Raises a name error -# Conditional Expressions can be used when assigning -some_var = a if a > b else b -# If a is greater than b, then a is assigned to some_var. -# Otherwise b is assigned to some_var. +# if can be used as an expression +"yahoo!" if 1 > 2 else 2 #=> "yahoo!" # Lists store sequences li = [] @@ -125,18 +134,15 @@ li[0] #=> 1 li[-1] #=> 3 # Looking out of bounds is an IndexError -try: - li[4] # Raises an IndexError -except IndexError: - print "Raises an IndexError" +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] # Omit the beginning -li[:3] #=> [1, 2, 4] -# Omit the end li[2:] #=> [4, 3] +# Omit the end +li[:3] #=> [1, 2, 4] # Remove arbitrary elements from a list with del del li[2] # li is now [1, 2, 3] @@ -156,10 +162,7 @@ len(li) #=> 6 # Tuples are like lists but are immutable. tup = (1, 2, 3) tup[0] #=> 1 -try: - tup[0] = 3 # Raises a TypeError -except TypeError: - print "Tuples cannot be mutated." +tup[0] = 3 # Raises a TypeError # You can do all those list thingies on tuples too len(tup) #=> 3 @@ -167,7 +170,7 @@ tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) tup[:2] #=> (1, 2) 2 in tup #=> True -# However, you can unpack tuples into variables +# You can unpack tuples into variables 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 @@ -196,13 +199,12 @@ filled_dict.values() #=> [3, 2, 1] "one" in filled_dict #=> True 1 in filled_dict #=> False -# Trying to look up a non-existing key will raise a KeyError -filled_dict["four"] #=> KeyError + # Looking up a non-existing key is a KeyError +filled_dict["four"] # KeyError # Use get method to avoid the KeyError 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 @@ -215,18 +217,23 @@ filled_dict.setdefault("five", 6) #filled_dict["five"] is still 5 # Sets store ... well sets empty_set = set() # Initialize a set with a bunch of values -filled_set = set([1,2,2,3,4]) # filled_set is now set([1, 2, 3, 4]) +some_set = set([1,2,2,3,4]) # filled_set is now set([1, 2, 3, 4]) + +# Since Python 2.7, {} can be used to declare a set +filled_set = {1, 2, 2, 3, 4} # => {1 2 3 4} # Add more items to a set -filled_set.add(5) # filled_set is now set([1, 2, 3, 4, 5]) +filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} # Do set intersection with & -other_set = set([3, 4, 5 ,6]) -filled_set & other_set #=> set([3, 4, 5]) +other_set = {3, 4, 5, 6} +filled_set & other_set #=> {3, 4, 5} + # Do set union with | -filled_set | other_set #=> set([1, 2, 3, 4, 5, 6]) +filled_set | other_set #=> {1, 2, 3, 4, 5, 6} + # Do set difference with - -set([1,2,3,4]) - set([2,3,5]) #=> set([1, 4]) +{1,2,3,4} - {2,3,5} #=> {1, 4} # Check for existence in a set with in 2 in filled_set #=> True @@ -240,7 +247,7 @@ set([1,2,3,4]) - set([2,3,5]) #=> set([1, 4]) # Let's just make a variable some_var = 5 -# Here is an if statement. INDENTATION IS SIGNIFICANT IN PYTHON! +# 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." @@ -320,16 +327,17 @@ def all_the_args(*args, **kwargs): print kwargs """ all_the_args(1, 2, a=3, b=4) prints: - [1, 2] + (1, 2) {"a": 3, "b": 4} """ -# You can also use * and ** when calling a function +# When calling functions, you can do the opposite of varargs/kwargs! +# Use * to expand tuples and use ** to expand kwargs. args = (1, 2, 3, 4) kwargs = {"a": 3, "b": 4} -foo(*args) # equivalent to foo(1, 2, 3, 4) -foo(**kwargs) # equivalent to foo(a=3, b=4) -foo(*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) # Python has first class functions def create_adder(x): @@ -401,3 +409,11 @@ j.get_species() #=> "H. neanderthalensis" Human.grunt() #=> "*grunt*" ``` +## Further Reading + +Still up for more? Try: + +* [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/) |