Invented by Guido Van Rossum in the early 90 's, Python is one of the most popular programming languages, because of its clear and concise syntax I fell in love with Python, whose code is basically executable pseudo-code.
Feedback is welcome! You can contact me via Twitter @louiedinh or louiedinh at Gmail.
Note: This article is intended for Python 2.7, but should be suitable for Python 2.x. Soon I will also write such an article for Python 3!
# single comment Start with a well character "" "We can use three double quotation marks (") or single quotation marks (') to write a multiline comment "" "############################################################ 1. Basic data types and Operators ########################################################## # number 3 #=> 3 # You envision mathematical operations 1 + 1 #=> 28-1 #=> 7 Ten * 2 #=> 2035/5 #=> 7 # Division slightly strange. Dividing integers automatically takes the largest integer less than the result 11/4 #=> 2 # and floating-point and floating-point division (the divisor and the dividend are at least one floating-point number, the result will be floating-point numbers) 2.0 # This is a floating-point number 5.0/2.0 #=> 2.5 ... Syntax more explicit # use parentheses to force precedence (1 + 3) * 2 #=> 8 # Boolean is also basic type data TrueFalse # Use not to negate not true #=> falsenot False #=> true # equality ratio Use ==1 = = 1 #=> True2 = 1 #=> False # Unequal comparison using!=1! = 1 #=> False2! = 1 #=> True # More ways to compare 1 < #=> true 1 > #=> False2 <= 2 #=> True2 >= 2 #=> True # Comparison operation can be threaded! 1 < 2 < 3 #=> True2 < 3 < 2 #=> False # You can use the "or ' Create string" This is a string. "' This is also a string. ' # strings can also be added! "Hello" + "world!" #=> "Hello world!" # string can be viewed as a character list "This is a string" [0] #=> ' T ' # none is an object none #=> None # # # ################################################### 2. Variable and Data container #################################################### # printout is very simple print "I ' m Python. Nice to meet you! "# does not need to declare a variable before Some_var = 5 # convention Using Lowercase _ letters _ and _ underscore naming method Some_var #=> 5 # Accessing a variable that was not assigned before will result in an exception try:some_othe R_varexcept Nameerror:print "raises a name error" # assignment can use conditional expression Some_var = A If a > b else b# if A is greater than B, assign a to some_var,# Otherwise, assign B to the Some_var # list to store the data series Li = []# You can start with a pre-populated list other_li = [4, 5, 6] # Use Append to add data to the end of the list li.append (1) #li现在为 [1]li.appe nd (2) #li现在为 [1, 2]li.append (4) #li现在为 [1, 2, 4]li.append (3) #li现在为 [1, 2, 4, 3] # use POP to delete data from the end of the list Li.pop () #=> 3,li is now [ 1, 2, 4]# Save the data just deleted Li.append (3) # now Li again for [1, 2, 4, 3] # access the list like an array li[0] #=> # See the last element Li[-1] #=> 3 # Cross-border access generates a Indexerrortry:li[4] # throws a Indexerror exception except Indexerror:print "raises an Indexerror" # You can view the data of a range in the list by using the Shard (slice) syntax to Mathematically, this is a closed/open interval li[1:3] #=> [2, 4]# omit end position li[2:] #=> [4, 3]# omit start position li[:3] #=> [1, 2, 4] # use Del to remove any element from the list del Li [2] #li现在为 [1, 2, 3] # list can add Li + other_lI #=> [1, 3, 3, 4, 5, 6]-note: Li and Other_li did not change # to link the list with extend Li.extend (other_li) # now Li is [1, 2, 3, 4, 5, 6] # in to detect if the list There is an element 1 in Li #=> True # with the Len function to detect the list length Len (li) #=> 6 # tuple-like list, but immutable tup = (1, 2, 3) tup[0] #=> 1try:tup[0] = 3 # throws a A TypeError exception except typeerror:print "tuples cannot be mutated." # You can use and list the same operations on tuples Len (tup) #=> 3tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) Tup[:2] #=> (1, 2) 2 in Tup #=> True # You can unpack tuples into variables A, b, C = (1, 2, 3) # now a equals 1,b equals 2,c equals 3# If you omit parentheses, the default It will also create tuples D, E, F = 4, 5, 6# see how simple E, d = d, e #现在d为5, and E for 4 # Dictionary store mappings for two variable interchange values empty_dict = {}# This is a pre-populated dictionary filled_dict = {"One" : 1, "one": 2, "three": 3} # Look for values in [] syntax filled_dict[' one '] #=> 1 # Get all the keys in a list Filled_dict.keys () #=> ["Three", "one", " One "]# note-the Order of the Dictionary keys is indeterminate # Your results may not match the above output # in to detect if a key exists in the dictionary" one "in the Filled_dict #=> True1 in filled_dict #=> fals E # Attempting to use a nonexistent key throws a Keyerror exception filled_dict[' Four ' #=> throws a Keyerror exception # Use the Get method to avoid Keyerrorfilled_dict.get ("one") #= > 1filled_dict.get ("four") #= = None # The Get method supports a default parameter that returns the default parameter value when there is no key filled_dict.get ("one", 4) #=> 1filled_dict.get ("Four", 4) #=> 4 # Setdefa The Ult method is a safe way to add a new key-value pair to the dictionary Filled_dict.setdefault ("Five", 5) #filled_dict ["Five"] set to 5filled_dict.setdefault ("five", 6) #filled_dict ["Five"] is still 5 # set empty_set = set () # Initializes a collection with several values Filled_set = set ([1, 2, 2, 3, 4]) # Filled_set is now set ([1, 2, 3, 4, 5]) # Perform set intersection operation with & other_set = Set ([3, 4, 5, 6]) Filled_set & Other_set #=> Set ([3, 4, 5]) # to | perform set merge operation Filled_set | Other_set #=> Set ([1, 2, 3, 4, 5, 6]) # with-Performs set difference operation set ([1, 2, 3, 4])-Set ([2, 3, 5]) #=> set ([1, 4]) # in to detect if there is a The value 2 in Filled_set #=> True10 in Filled_set #=> False ###################################################### 3. Control Flow #################################################### # Create a variable Some_var = 5 # The following is an if statement. Indenting is significant in Python. # print "Some_var is smaller than" if Some_var > 10:print "Some_var is totally bigger than 10." Elif Some_var < 10:print "Some_var is smaller than 10." Else:print "SomE_var is indeed 10. " The For loop iterates over the list output: Dog is a mammal cat is a mammal mouse are a mammal "" "for Animal in [" Dog "," cat "," Mouse "]: # You can use% to interpolate The fill format string print '%s is a mammal '% animal "" "while loop until a condition is not met. Output: 0 1 2 3 "" "x = 0while x < 4:print x + = 1 # x = x + 1 A shorthand # Use try/except block to handle exceptions # valid try for Python 2.6 and later: # Use raise to throw an error raise the Indexerror ("This is a index error") except Indexerror as E:pass # Pass is nothing to do. Usually used here to do some recovery work # for Python 2.7 and below valid Try:raise Indexerror ("This is an index error") except Indexerror, E: # no "as", comma substitution Pass ###################################################### 4. function #################################################### # using DEF to create a new function def add (x, y): print "x is%s and y is%s"% (x, y) return x + y # Returns a value with a return statement # call the function with a parameter add (5, 6) #=> 11 and Output "X is 5 and y is 6" # Another way to call a function is the keyword argument add (x=5, y=6) # keyword Parameters can be entered in any order # can define a function that accepts a variable number of positional parameters def varargs (*args): Return args varargs (1, 2, 3) #=> (1, 2, 3) # You can also define a function def that accepts a variable number of keyword arguments Keyword_args (**kwarGS): Return Kwargs # Call this function to see what happens Keyword_args (big= "foot", loch= "ness") #=> {"Big": "foo", "Loch": "Ness"} # can also be accepted at once Two parameters def All_the_args (*args, **kwargs): Print args print Kwargs "" "All_the_args (1, 2, a=3, b=4) output: [1, 2] {" A ": 3," B ": 4} "" "# can also be used when calling a function * and **args = (1, 2, 3, 4) Kwargs = {" A ": 3," B ": 4}foo (*args) #等价于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) # Python function is a one-class function Def create_adder (x): def adder (y): Retu RN x + y return adder add_10 = Create_adder (Ten) add_10 (3) #=> 13 # There are also anonymous functions (Lamda x:x > 2) (3) #=> True # There are some built-in high-order letters Number of maps (ADD_10, [1, 2, 3]) #=> [One, A, 13]filter (Lamda x:x > 5, [3, 4, 5, 6, 7]) #=>[6, 7] # You can use list inference to implement mappings and filtering [add_ Ten (i) for i in [1, 2, 3]] #=> [One, a, 13][x for x in [3, 4, 5, 6,7] if x > 5] #=> [6, 7] ###################### ################################ 5. Class #################################################### # Creates a subclass that inherits from object to get a class Human (object): # Class Property. In this class ofShared species = "H. sapiens" # For all samples # Basic initialization construction Method Def __init__ (self, name): # assigns a parameter to the instance's Name property Self.name = name # instance Party Method. All example methods have self as the first parameter def say (self, msg): Return "%s:%s"% (Self.name, msg) # class method is shared by all instances # to invoke the class to invoke the first argument @classmeth Od def get_species (CLS): Return Cls.species # A call to a static method does not require a reference to a class or instance @staticmethod def grunt (): Return "*grunt*" # Instantiate a Class I = Human (name= "Ian") Print I.say ("HI") # output "Ian:hi" J = Human ("Joel") print J.say ("hello") # output "Joel:hello" # Call class Method I.get_species () #=> "H. sapiens" # Modify the Share property Human.species = "H. Neanderthalensis" I.get_species () #=> "H. neander Thalensis "j.get_species () #=>" H. neanderthalensis "# Call static method Human.grunt () #=>" *grunt* "{% endhighlight%}