Python was designed by Guido van Rossum in the early 1990s. It is one of the most commonly used programming languages today. Its syntax is simple and elegant, almost executable pseudo code.
I don't understand in learning Python and recommend to join the communication group
No.: 864573496
There are like-minded partners in the group, who help each other and help each other,
There are good video learning tutorials and PDF in the group!
Note: this tutorial is based on Python 3. Source code download: https://learnxinyminutes.com/docs/files/learnpython3-cn.py
#A single line comment begins with a well character "" "three quotes for multiline strings Parcels are also often used to make long Line notes """
1. Original data type and operator
# integer 3 # => 3 # There's nothing unexpected about arithmetic 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 # Except for division, it will be automatically converted to floating-point number 35 / 5 # => 7.0 5 / 3 # => 1.6666666666666667 # Integer division results in rounding down 5 // 3 # => 1 5.0 // 3.0 × floating point -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 # The result of floating-point operation is also floating-point 3 * 2.0 # => 6.0 # Modulo Division 7 % 3 # => 1 # The y power of x 2**4 # => 16 # Use parentheses to determine priority (1 + 3) * 2 # => 8 # Boolean value True False # Using not to take non not True # => False not False # => True # Logical operators, note that and and or are lowercase True and False # => False False or True # => True # Integers can also be treated as Booleans 0 and 2 # => 0 -5 or 0 # => -5 0 == False # => True 2 == True # => False 1 == True # => True # Use = = to judge equality 1 == 1 # => True 2 == 1 # => False # Use! = to judge unequal 1 != 1 # => False 2 != 1 # => True # Comparative size 1 < 10 # => True 1 > 10 # => False 2 <= 2 # => True 2 >= 2 # => True # Size comparison can be connected! 1 < 2 < 3 # => True 2 < 3 < 2 # => False # Both single and double references can be used for strings "This is a string" 'It's also a string' # Concatenate strings with a plus sign "Hello " + "world!" # => "Hello world!" # Strings can be treated as character lists "This is a string"[0] # => 'T' # format string with. format "{} can be {}".format("strings", "interpolated") # Parameters can be repeated to save time "{0} be nimble, {0} be quick, {0} jump over the {1}".format("Jack", "candle stick") # => "Jack be nimble, Jack be quick, Jack jump over the candle stick" # If you don't want a number parameter, you can use the keyword "{name} wants to eat {food}".format(name="Bob", food="lasagna") # => "Bob wants to eat lasagna" # If you want to run your Python 3 program under Python 2.5, you can also use the old formatting syntax "%s can be %s the %s way" % ("strings", "interpolated", "old") # None is an object None # => None # Do not use = =, use is when comparing with None. Is is used to compare whether two variables point to the same object. "etc" is None # => False None is None # => True # None, 0, empty string, empty list and empty dictionary are all False # All other values are True bool(0) # => False bool("") # => False bool([]) # => False bool({}) # => False
2. Variables and sets
# Print is a built-in print function print("I'm Python. Nice to meet you!") # Do not declare in advance before assigning a value to a variable # Traditional variable names are lowercase, with underscores separating words some_var = 5 some_var # => 5 # Accessing an unassigned variable throws an exception # Refer to process control section to learn exception handling some_unknown_var # Throw NameError # Save sequence with list li = [] # You can also assign elements to a list when you create it other_li = [4, 5, 6] # append to the end of the list li.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 is now [1, 2, 4, 3] # Delete from the end of the list with pop li.pop() # =>3 and li is now [1, 2, 4] # Put 3 back li.append(3) # li changes back to [1, 2, 4, 3] # List access is the same as array li[0] # => 1 # Take out the last element li[-1] # => 3 # Out of bounds access will cause IndexError li[4] # Throw IndexError # List has cutting syntax li[1:3] # => [2, 4] # Take tail li[2:] # => [4, 3] # Take the head li[:3] # => [1, 2, 4] # Take one from another li[::2] # =>[1, 4] # Inverted list li[::-1] # => [3, 4, 2, 1] # You can build a cut with any combination of three parameters # li [start: end: step] # Delete any element with del del li[2] # li is now [1, 2, 3] # Lists can be added # Note: the values of li and other ABCD are the same li + other_li # => [1, 2, 3, 4, 5, 6] # Splicing lists with extend li.extend(other_li) # li is now [1, 2, 3, 4, 5, 6] # Use in to test whether the list contains values 1 in li # => True # Take list length with len len(li) # => 6 # Tuples are immutable sequences tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # Throw TypeError # Most of the operation tuples allowed in the list are OK len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True # You can unpack the meta combination list and assign it to variables a, b, c = (1, 2, 3) # Now a is 1, b is 2, c is 3 # Parentheses around tuples can be omitted d, e, f = 4, 5, 6 # It's so easy to swap the values of two variables e, d = d, e # Now d is 5, e is 4 # Using dictionary to express mapping relation empty_dict = {} # Dictionary initialized filled_dict = {"one": 1, "two": 2, "three": 3} # Use [] value filled_dict["one"] # => 1 # Use keys to get all the keys. # Because keys returns an iterative object, the result is packaged in the list here. We'll talk about iterations in detail. # Note: the order of dictionary keys is variable, and your results may be different from the following. list(filled_dict.keys()) # => ["three", "two", "one"] # Use values to get all the values. Just like keys, they can be wrapped in a list in different order. list(filled_dict.values()) # => [3, 2, 1] # in to test whether a dictionary contains a key "one" in filled_dict # => True 1 in filled_dict # => False # Accessing a key that does not exist will result in a KeyError filled_dict["four"] # KeyError # Use get to avoid KeyError filled_dict.get("one") # => 1 filled_dict.get("four") # => None # The get method can return the default value when the key does not exist filled_dict.get("one", 4) # => 1 filled_dict.get("four", 4) # => 4 # The setdefault method inserts a new value only if the key does not exist filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 filled_dict.setdefault("five", 6) # filled_dict["five"] or 5 # Dictionary assignment filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} filled_dict["four"] = 4 # Another method of assignment # Delete with del del filled_dict["one"] # Delete one from filled_dict # Express set with set empty_set = set() # Initializes a collection with a syntax similar to that of a dictionary. some_set = {1, 1, 2, 2, 3, 4} # Some set is now {1, 2, 3, 4} # You can assign a set to a variable filled_set = some_set # Adding elements to a collection filled_set.add(5) # Filled set is now {1, 2, 3, 4, 5} # Cross intersection other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} # Merge and gather filled_set | other_set # => {1, 2, 3, 4, 5, 6} # - complement set {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} # in tests whether the collection contains elements 2 in filled_set # => True 10 in filled_set # => False
3. Process control and iterator
# Define any variable first some_var = 5 # This is an if statement. Note that indentation makes sense in Python # Printed "some" VaR is smaller than 10 " if some_var > 10: print("some_var More than 10") elif some_var < 10: # elif sentences are optional print("some_var Smaller than 10") else: # else is also optional print("some_var That's 10.") """ //Traversing a list with a for loop statement //Print: dog is a mammal cat is a mammal mouse is a mammal """ for animal in ["dog", "cat", "mouse"]: print("{} is a mammal".format(animal)) """ "range(number)"Returns the number list from 0 to the given number //Print: 0 1 2 3 """ for i in range(4): print(i) """ while Cycle until conditions are not met //Print: 0 1 2 3 """ x = 0 while x < 4: print(x) x += 1 # Shorthand for x = x + 1 # Using try/except block to deal with exception try: # Throw an exception with raise raise IndexError("This is an index error") except IndexError as e: pass # pass is no operation, but the error should be handled here except (TypeError, NameError): pass # Can handle errors of different classes at the same time else: # else statements are optional and must follow all except print("All good!") # This sentence will only run when there is no error after the try runs # Python provides a basic abstraction called Iterable. An iterative object can be treated as a sequence # The object. For example, the objects returned by the above range can be iterated. filled_dict = {"one": 1, "two": 2, "three": 3} our_iterable = filled_dict.keys() print(our_iterable) # =>Dict_keys (['one ','two','three ']), an object that implements an iterative interface # Iteratable objects can be traversed for i in our_iterable: print(i) # Print one, two, three # But not random access our_iterable[1] # Throw TypeError # Iteratable objects know how to generate iterators our_iterator = iter(our_iterable) # An iterator is an object that remembers the location of traversal # Use next to get the next element our_iterator.__next__() # => "one" # Remember the location when you call next again our_iterator.__next__() # => "two" our_iterator.__next__() # => "three" # When all elements of the iterator are taken out, StopIteration is thrown our_iterator.__next__() # Throw StopIteration # You can use list to retrieve all the elements of an iterator at once list(filled_dict.keys()) # => Returns ["one", "two", "three"]
4. function
# Define new functions with def def add(x, y): print("x is {} and y is {}".format(x, y)) return x + y # Return with return statement # Calling function add(5, 6) # =>Print "x is 5 and y is 6" and return to 11 # You can also call functions with key arguments add(y=6, x=5) # Keyword parameters can be in any order # We can define a variable parameter function def varargs(*args): return args varargs(1, 2, 3) # => (1, 2, 3) # We can also define a keyword variable parameter function def keyword_args(**kwargs): return kwargs # Let's look at the results: keyword_args(big="foot", loch="ness") # => {"big": "foot", "loch": "ness"} # These two variable parameters can be mixed def all_the_args(*args, **kwargs): print(args) print(kwargs) """ all_the_args(1, 2, a=3, b=4) prints: (1, 2) {"a": 3, "b": 4} """ # When calling variable parameter functions, you can do the opposite: expand the sequence with * and expand the dictionary with * *. 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 x = 5 def setX(num): # The x of local scope is different from that of global scope x = num # => 43 print (x) # => 43 def setGlobalX(num): global x print (x) # => 5 x = num # Now the x of the global domain is assigned print (x) # => 6 setX(43) setGlobalX(6) # Functions are first class citizens in Python 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 (lambda x: x > 2)(3) # => True # Built in higher order functions map(add_10, [1, 2, 3]) # => [11, 12, 13] filter(lambda x: x > 5, [3, 4, 5, 6, 7]) # => [6, 7] # Using list derivation can simplify mapping and filtering. The return value of the list derivation is another list. [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. category
# Define a class that inherits the object class Human(object): # Class property, shared by all instances of this class. species = "H. sapiens" # Constructor, called when the instance is initialized. Note the double underline around the name to indicate the genus # Properties or methods have special meaning for Python, but allow users to define them themselves. You shouldn't use this when you name yourself # Format. def __init__(self, name): # Assign the argument to the instance's name attribute self.name = name # Instance method. The first parameter is always self, which is the instance object def say(self, msg): return "{name}: {message}".format(name=self.name, message=msg) # Class method, shared by all instances of this class. The first parameter is this class object. @classmethod def get_species(cls): return cls.species # Static method. There is no binding for an instance or class at the time of the call. @staticmethod def grunt(): return "*grunt*" # Construct an instance i = Human(name="Ian") print(i.say("hi")) # Printed "Ian: hi" j = Human("Joel") print(j.say("hello")) # Printed "Joel: hello" # Call a class method i.get_species() # => "H. sapiens" # Change a common class property Human.species = "H. neanderthalensis" i.get_species() # => "H. neanderthalensis" j.get_species() # => "H. neanderthalensis" # Call static method Human.grunt() # => "*grunt*"
6. module
# Import module with import import math print(math.sqrt(16)) # => 4.0 # You can also import individual values from a module from math import ceil, floor print(ceil(3.7)) # => 4.0 print(floor(3.7)) # => 3.0 # All values in a module can be imported # Warning: not recommended from math import * # So abbreviate module name import math as m math.sqrt(16) == m.sqrt(16) # => True # Python module is actually a common Python file. You can write it yourself and import it, # The name of the module is the name of the file. # You can list all the values in a module like this import math dir(math)
7. Advanced usage
# Using generators to write lazy operations conveniently def double_numbers(iterable): for i in iterable: yield i + i # The generator calculates the next value only if it needs to. They generate only one value per cycle, not all # It's all worth it. # # The return value of range is also a generator, otherwise a list of 1 to 900000000 will take a lot of time and memory. # # If you want to use a Python keyword as a variable name, you can add an underscore to distinguish it. range_ = range(1, 900000000) # When a result of > = 30 is found, it will stop # This means that 'double' numbers' will not generate numbers greater than 30. for i in double_numbers(range_): print(i) if i >= 30: break # Decorators # In this case, beg decorates say # Beg will call say first. If the returned say ﹣ please is true, beg changes the returned string. from functools import wraps def beg(target_function): @wraps(target_function) def wrapper(*args, **kwargs): msg, say_please = target_function(*args, **kwargs) if say_please: return "{} {}".format(msg, "Please! I am poor :(") return msg return wrapper @beg def say(say_please=False): msg = "Can you buy me a beer?" 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 :(