Take a piece of code as an example to get started with Python2.7 and python2.7

Source: Internet
Author: User

Take a piece of code as an example to get started with Python2.7 and python2.7

Python was invented by Guido Van rosum in the early 1990s s and is currently one of the most popular programming languages. I fell in love with Python because of its clear and concise syntax, the code is basically executable pseudocode.

Welcome! You can contact me via Twitter @ louiedinh or louiedinh AT gmail.

Note: This article focuses on Python 2.7, but it should be applicable to Python 2. x. Soon I will write such an article for Python 3!

# Single line comment starts with a well character ". We can use three double quotation marks (") or single quotation marks (') to compile multi-line comments """################################ ########################## 1. basic data types and operators ################################### ####################### number 3 ##> 3 # The expected mathematical operations 1 + 1 # => 28-1 # => 710*2 # => 2035/5 # => 7 # division is slightly odd. The integer division will automatically take down the largest integer less than the result 11/4 #=> 2 # There are floating point and floating point Division) 2.0 # This is a floating point number 5.0/2.0 #=> 2.5 amount... more explicit syntax # use parentheses to force priority (1 + 3) * 2 #=> 8 # Boolean value is also basic data TrueFalse # Use not to reverse not True #=> Falsenot False #=> True # equal comparison = 1 = 1 #=> True2 = 1 #=> False # Not equal! = 1! = 1 # => False2! = 1 #=> True # more comparison methods 1 <10 #=> True1> 10 #=> False2 <= 2 #=> True2> = 2 #=> True # comparison operations can be concatenated! 1 <2 <3 # => True2 <3 <2 # => False # You can use "or" create string "This is a string. "'This is also a string. '# strings can also be added! "Hello" + "world! "# =>" Hello world! "# A string can be considered as a character list" This is a string "[0] #=> 'T' # None is an object None #=> None ###### ######################################## ####### 2. variables and data containers #################################### ################ print output is very simple print "I'm Python. nice to meet you! "# VARIABLES some_var = 5 need not be declared before the value assignment # The naming conventions for lowercase _ letters _ and _ underscores are used in some_var #=> 5 # An exception occurs when a variable that has not been assigned a value is accessed. try: some_other_var1_t NameError: print "Raises a name error" # When assigning values, you can use the 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 some_var # list used to store the data sequence li = [] # You can start with a pre-filled list other_li = [4, 5, 6] # Use append to add data to the end of the list. append (1) # li is now [1] li. append (2) # li is now [1, 2] li. append (4) # li is now [1, 2, 4] li. append (3) # li It is now [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 deleted data back to li. append (3) # Now li is [1, 2, 4, 3] # access list li [0] #=> 1 # Look at the last element li [-1] #=> 3 # An IndexErrortry is generated for cross-border access: li [4] # throw an IndexError exception; t IndexError: print "Raises an IndexError" # You can use the slice syntax to view the data in a certain range in the list # from a mathematical perspective, this is a closed/open room li [] #=> [2, 4] # omitting the end position li [2:] #=> [4, 3] # omit the starting position li [: 3] #=> [1, 2, 4] # Use del to delete any element del l from the list I [2] # li is now [1, 2, 3] # The list can be added with li + other_li # => [1, 3, 3, 4, 5, 6]-Note: li and other_li have not changed # Use extend to link the list of li. extend (other_li) # Now li is [1, 2, 3, 4, 5, 6] # Use in to check whether an element 1 in li # => True # Use len function to check the list length len (li) #=> 6 # tuples are similar to the list, but cannot be changed. tup = (1, 2, 3) tup [0] #=> 1try: tup [0] = 3 # Throw A TypeError exception when T TypeError: print "Tuples cannot be mutated. "# the same operation len (tup) as the list can be used on tuples #=> 3tup + (4, 5, 6) #=> (1, 2, 3, 4, 5, 6) tup [: 2] # => (1, 2) 2 in tup # => True # You can unpack tuples to variables a, B, c = (1, 2, 3) # Now a is equal to 1, B is equal to 2, c is equal to 3 # If you omit parentheses, The tuples d, e, f = 4, 5 will be created by default, 6 # Check how simple the values of the two variables are: e, d = d, e # d is 5, e is 4 # dictionary storage ing relationship empty_dict ={}# This is a pre-filled dictionary filled_dict = {"one": 1, "two": 2, "three ": 3} # search for the value filled_dict ['one'] #=> 1 # obtain all the keys in the form of a list. filled_dict.keys () #=> ["three ", "two", "one"] # Note-the sequence of dictionary keys is uncertain # Your results may be inconsistent with the above output results # Use in to check whether a dictionary exists Key "one" in filled_dict # => True1 in filled_dict # => False # If you try to use a key that does not exist, a KeyError is thrown. filled_dict ['four '] # => A KeyError is thrown. # Use the get method to avoid KeyErrorfilled_dict.get ("one ") #=> 1filled_dict.get ("four") #=> None # The get method supports a default parameter. If a key does not exist, filled_dict.get ("one", 4) is returned) #=> 1filled_dict.get ("four", 4) #=> 4 # The setdefault method is a secure way to add a new key-value pair to the dictionary filled_dict.setdefault ("five ", 5) # Set filled_dict ["five"] To 5filled_dict.. Setdefault ("five", 6) # filled_dict ["five"] is still 5 # set empty_set = set () # initialize a set filled_set = set ([1, 2, 2, 3, 4]) # filled_set is now set ([1, 2, 3, 4, 5]) # Use & to execute the set intersection operation other_set = set ([3, 4, 5, 6]) filled_set & other_set # => set ([3, 4, 5]) # Run | execute a set and calculate filled_set | other_set # => set ([1, 2, 3, 4, 5, 6]) # Run the set difference operation set ([1, 2, 3, 4])-set ([2, 3, 5]) # => set ([1, 4]) # Use in to check whether a value of 2 in filled_set exists in the set # => True10 I N filled_set #=> False ################################## #################### 3. control Process ###################################### ############## create a variable some_var = 5 # The following is an if statement. Indentation is important in Python. # Print "some_var is smaller than 10" 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. "For loop iteration output on the list: dog is a mammal cat is a mammal mouse is a mammal" for animal in ["dog", "cat ", "mouse"]: # You can use % to interpolation and format the print string "% s is a mammal" % animal "while loop until a condition is not met. Output: 0 1 2 3 "x = 0 while x <4: print x + = 1 # A shorthand for x = x + 1 # Use the try/try t block to handle exceptions # It is effective for Python 2.6 and later versions. try: # Use raise to throw an error: raise IndexError ("This is an index error") failed t IndexError as e: pass # pass means nothing to do. It is usually used for restoration. # For Python 2.7 and earlier versions, try: raise IndexError ("This is an index error") cannot t IndexError, e: # No "", replace pass #################################### ################## 4. function ####################################### ############# use def to create a function def add (x, y): print "x is % s and y is % s" % (x, y) return x + y # return value using a return statement # Call the add (5, 6) function with Parameters) #=> 11 and output "x is 5 and y is 6" # Another way to call a function is to use the keyword parameter. Dd (x = 5, y = 6) # keyword parameters can be input in any order # You can define the function def varargs (* args) that accepts variable numbers of location parameters ): return args varargs (1, 2, 3) #=> (1, 2, 3) # You can also define the function def keyword_args (** kwargs) that accepts variable number of keyword parameters ): return kwargs # Call this function to see what happens to keyword_args (big = "foot", loch = "ness") #=>{ "big": "foo ", "loch": "ness"} # either of the following parameters can be accepted at a time: 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} "" # In When calling a function, you can also use * And ** 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) # The Python function is the first-class function def create_adder (x): def adder (y): return x + y return adder add_10 = create_adder (10) add_10 (3) #=> 13 # There are also anonymous functions (lamda x: x> 2) (3) # => True # There are some built-in high-level functions map (add_10, [1, 2, 3]) # => [11, 12, 13] filter (lamda x: x> 5, [3, 4, 5, 6, 7]) # => [6, 7] # map and Filter Using list derivation [add_10 (I) for I in [1, 2, 3] # => [11, 13, 13] [x for x in [3, 4, 5, 6, 7] if x> 5] #=> [6, 7] ####################################### ################ 5. class ####################################### ############# create a subclass that inherits from the object to obtain a class Human (object): # class attributes. Share species = "H. sapiens "# basic initialization constructor def _ init _ (self, name): # assign a parameter to the instance's name attribute self. name = name # instance method. All sample methods use self as the first parameter def say (self, msg): return "% s: % s" % (self. name, msg) # The class method is shared by all instances # Call @ classmethod def get_species (cls) with the call class as the first parameter: return cls. species # static method calls do not require a class or instance reference @ 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 "# modifying shared attributes Human. species = "H. neandrethalensis "I. get_species () # => "H. neandrethalensis "j. get_species () # => "H. neandrethalensis "# Call the static method Human. grunt () # => "* grunt *" {% endhighlight %}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.