Basic grammar
#Indent instead of braces #Replace semicolon with newline, or use semicolon, it doesn't matter #Output print(); #Input input(); #Notes #Single line comment """ Multiline comment 1 """ ''' Multiline Note 2 ''' #Declare variable Write letters directly and combine them with numbers and underscores instead of reserved words. # if if true: print("true") else: print("false") # while i = 0; while i <= 1: #do something print("cicle") i+=1 # for languages = ["C", "C++", "Perl", "Python"] for x in languages: print (x) # range The range (5) function returns an array of numbers 0~4 The range (5,9) function returns an array of numbers 5 to 8 The range (0,10,3) function returns a numeric array starting from the number 0 and increasing by 3 until the last number is less than 10 The range (- 10, - 100, - 30) function returns a numeric array starting from - 10 and increasing by - 30 until the last array is greater than - 100 #For+range traverse array with index a = ['Google', 'Baidu', 'Runoob', 'Taobao', 'QQ'] for i in range(len(a)) print(i,a[i]) #While traversing array with index i = 0; length = len(a); while i < a: print(i,a[i]) i+=1 #For+enumerate traverse array with index for i,value in enumerate(a): print(i,value) #List #Python list is similar to java list in nature, but not array. Its size is variable, but the elements of Python list can make different data types flexible #Create a new list list1 = [] list2 = ['bob',1,true] #Add elements list1.append(233) List1. insert (0666) # Insert to position 0, and move the original elements backward in turn #Delete Element List2. pop() # Delete the element at the end list2.pop(0) #Modify element=direct assignment #Access the specified location element list1[2] List1 [- 1] # indicates the last element #Slice (returns a sublist) List2 [0:2] # indicates the element from index 0 to 1 List2 [- 2: - 1] # indicates the penultimate element List2 [: 3] # means from 0 to 2 List2 [1:] # means from 1 to the end #Tuple #Unlike the list, the tuple cannot be modified once it is initialized. #The list uses [] square brackets, and the tuple uses () parentheses #When defining, only one element needs to be added, to avoid ambiguity t = (1,) #Dict #Dict is similar to java map. Key value pair, Python dict is very similar to json syntax #Definition d = {'age':62, 'sex':'male'} #Access value d['age'] #Determine whether the key exists d. Get ('name ') # By default, none is returned d. Get ('name ', - 1) # Return - 1 if it does not exist 'name' in d # returns false when it does not exist #Delete key d.pop('sex') #Set #Similar to the set property of Java, it is also a collection without duplicate elements. #Definition s = set([1,1,2,2,2,3,3,'sex']) #Add Element s.add(4) s. Add (4) # Duplicate element addition will not take effect #Delete Element s. Remove ('sex ') # The parameter is the value of the set element, not the index #Function #Defining Functions def my_function(x): print(x); #Call function
Advanced Features
List Generators and Generators
List Builder
l = [] for x in range(1,11): l.append(x*x) #Or the following cycle i = 1 while i < 11: l.append(i*i) i+=1
[x*x for x in range(1,11)]
[x * x for x in range(1, 11) if x % 2 == 0] # [4, 16, 36, 64, 100]
generator
L = [x * x for x in range(1000000)] print(L[0]) print(L[1])
g = (x * x for x in range(1000000)) next(g) next(g)
g = (x * x for x in range(10)) for x in g: print(x)
def odd(): print('step 1') yield 1 print('step 2') yield(3) print('step 3') yield(5) g = odd() next(g) # step 1 next(g) # step 2 next(g) # step 3 next(g) # StopIteration
for x in odd(): Print (x) # Return 1, 3, 5 in turn
iterator
-
Iterative object: for can be used to traverse, but it cannot be called by next (), and the next value is returned continuously. -
Iterator: You can call next (Iterator) to continuously return the value inside the iterator -
adopt Isinstance ([variable], Iterator) or Isinstance ([variable], Iterable) Determine whether the variable is an iterator or an iterable object -
The list, dict, and str are not iterators in themselves. You can use iter(Iterable) Return iterator object -
The generator itself is an iterator object.
l = [1, 2, 3, 4, 5] lIter = iter(l) Next (lIter) # Return 1
Functional programming
Decorator
def log(func): def wrapper(*args, **kw): Print ("Call function% s()"% func__ name__) return func(*args, **kw) return wrapper @log def now(str): Print ("one test function+% s"% str)
def log(text): def decorator(func): def wrapper(*args, **kw): Print ("Call function% s() at time, test text% s"% (func. __name__, text)) return func(*args, **kw) return wrapper return decorator @Log ("Custom Text") def now(str2): Print ("one test function+% s"% str2)
import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): Print ("Call function% s()"% func__ name__) return func(*args, **kw) return wrapper
object-oriented programming
class
class Student(object): def __init__(self, name, score, sex): self.name = name self.score = score self.__sex = sex; def print_score(self): print('%s: %s' % (self.name, self.score)) st = Student("hewro",120,"male") print(st.name) st.print_sore()
-
The member variable is in the __init__ Rather than declaring variables directly -
The constructor name is __init__ , Python does not support function overloading. Naturally, there can only be one constructor. And the first parameter must be self , you do not need to call this parameter manually when generating an instance. -
To use its own variable inside a class, you need to add it to the first parameter of the function self , very troublesome -
The writing method of inheriting parent class is not extend , but (Parent class) -
There is no keyword in the definition of python's private variable, just two underscores in front of the variable name __ , such as __sex , you cannot print directly std.__sex
About polymorphism
class Animal(object): def run(self): print('Animal is running...') class Dog(Animal): def run(self): print('Dog is running...') class Cat(Animal): def run(self): print('Cat is running...') class Tortoise(Animal): def run(self): print('Tortoise is running slowly...') #The parameters of this function are not actually declared def run_twice(animal): animal.run() animal.run()