diff options
Diffstat (limited to 'python.html.markdown')
-rw-r--r-- | python.html.markdown | 138 |
1 files changed, 94 insertions, 44 deletions
diff --git a/python.html.markdown b/python.html.markdown index 9057dde2..ace3f794 100644 --- a/python.html.markdown +++ b/python.html.markdown @@ -3,24 +3,25 @@ language: python contributors: - ["Louie Dinh", "http://ldinh.ca"] - ["Amin Bandali", "http://aminbandali.com"] + - ["Andre Polykanine", "https://github.com/Oire"] filename: learnpython.py --- -Python was created by Guido Van Rossum in the early 90's. It is now one of the most popular +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] 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! +to Python 2.x. For Python 3.x, take a look at the [Python 3 tutorial](http://learnxinyminutes.com/docs/python3/). ```python # Single line comments start with a number symbol. """ Multiline strings can be written - using three "'s, and are often used + using three "s, and are often used as comments """ @@ -45,7 +46,7 @@ to Python 2.x. Look for another tour of Python 3 soon! 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 @@ -54,12 +55,23 @@ to Python 2.x. Look for another tour of Python 3 soon! # Modulo operation 7 % 3 # => 1 +# Exponentiation (x to the yth power) +2**4 # => 16 + # Enforce precedence with parentheses (1 + 3) * 2 # => 8 -# Boolean values are primitives -True -False +# Boolean Operators +# Note "and" and "or" are case-sensitive +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 # negate with not not True # => False @@ -89,6 +101,11 @@ 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" # A string can be treated like a list of characters "This is a string"[0] # => 'T' @@ -124,11 +141,8 @@ bool("") # => False ## 2. Variables and Collections #################################################### -# Python has a print function, available in versions 2.7 and 3... -print("I'm Python. Nice to meet you!") -# and an older print statement, in all 2.x versions but removed from 3. -print "I'm also Python!" - +# Python has a print statement +print "I'm Python. Nice to meet you!" # No need to declare variables before assigning to them. some_var = 5 # Convention is to use lower_case_with_underscores @@ -158,6 +172,10 @@ li.append(3) # li is now [1, 2, 4, 3] again. # Access a list like you would any array li[0] # => 1 +# Assign new values to indexes that have already been initialized with = +li[0] = 42 +li[0] # => 42 +li[0] = 1 # Note: setting it back to the original value # Look at the last element li[-1] # => 3 @@ -173,16 +191,17 @@ 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. +li + other_li # => [1, 2, 3, 4, 5, 6] +# Note: values for li and for other_li are not modified. # Concatenate lists with "extend()" li.extend(other_li) # Now li is [1, 2, 3, 4, 5, 6] @@ -243,17 +262,25 @@ 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 +# note that filled_dict.get("four") is still => None +# (get doesn't set the value in the dictionary) + +# set the value of a key with a syntax similar to lists +filled_dict["four"] = 4 # now, filled_dict["four"] => 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 -# Sets store ... well sets +# Sets store ... well sets (which are like lists but can contain no duplicates) empty_set = set() # Initialize a "set()" with a bunch of values some_set = set([1, 2, 2, 3, 4]) # some_set is now set([1, 2, 3, 4]) +# order is not guaranteed, even though it may sometimes look sorted +another_set = set([4, 3, 2, 2, 1]) # another_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} @@ -285,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." """ @@ -301,7 +328,7 @@ prints: """ for animal in ["dog", "cat", "mouse"]: # You can use % to interpolate formatted strings - print("%s is a mammal" % animal) + print "%s is a mammal" % animal """ "range(number)" returns a list of numbers @@ -313,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. @@ -325,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 @@ -348,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 %s and y is %s" % (x, y) return x + y # Return values with a return statement # Calling functions with parameters @@ -359,7 +398,7 @@ add(y=6, x=5) # Keyword arguments can arrive in any order. # You can define functions that take a variable number of -# positional arguments +# positional args, which will be interpreted as a tuple if you do not use the * def varargs(*args): return args @@ -367,7 +406,7 @@ varargs(1, 2, 3) # => (1, 2, 3) # You can define functions that take a variable number of -# keyword arguments, as well +# keyword args, as well, which will be interpreted as a map if you do not use ** def keyword_args(**kwargs): return kwargs @@ -377,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) @@ -386,26 +425,33 @@ all_the_args(1, 2, a=3, b=4) prints: """ # When calling functions, you can do the opposite of args/kwargs! -# Use * to expand tuples and use ** to expand kwargs. +# Use * to expand positional args and use ** to expand keyword args. 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) -# Function Scope +# you can pass args and kwargs along to other functions that take args/kwargs +# by expanding them with * and ** respectively +def pass_all_the_args(*args, **kwargs): + all_the_args(*args, **kwargs) + print varargs(*args) + print keyword_args(**kwargs) + +# Function Scope x = 5 def setX(num): # Local var x not the same as global variable x x = num # => 43 - print (x) # => 43 - + print x # => 43 + def setGlobalX(num): global x - print (x) # => 5 + print x # => 5 x = num # global var x is now set to 6 - print (x) # => 6 + print x # => 6 setX(43) setGlobalX(6) @@ -430,11 +476,11 @@ 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] + #################################################### ## 5. Classes #################################################### - # We subclass from object to get a class. class Human(object): @@ -467,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" @@ -490,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 @@ -504,6 +550,9 @@ from math import * # You can shorten module names import math as m math.sqrt(16) == m.sqrt(16) # => True +# you can also test that the functions are equivalent +from math import sqrt +math.sqrt == m.sqrt == sqrt # => True # Python modules are just ordinary python files. You # can write your own, and import them. The name of the @@ -530,14 +579,15 @@ def double_numbers(iterable): # 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 +# 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) + print i if i >= 30: break @@ -566,8 +616,8 @@ 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? |