positional argument: positional argument
day01
python():
There is no title ';', but a carriage return is used instead, so after a sentence ends, another sentence must be returned
There are also no curly braces {}, and use tab to indicate that within the method, and no tab to indicate the end of the method
The colon ':' is mainly to avoid confusion like if a<3 : a=2
def define method
variable
There is no need to define the type, it must be initialized and assigned; there is no character type char, which is merged into the string type
Dynamic type: determine the type of variable during runtime, python determines the type of a variable when it is first assigned a value;
Strongly typed: there is a mandatory type definition, an integer, which must never be treated as a string unless explicit type conversions are made
Variable assignment, can be multiple at the same time, such as a,b = 2,3;c,d = a,b
Single-line comment #, multi-line comment '''... ''' or """..."""
Strings, single quotation marks '' and double quotation marks "" are equivalent, and can perform '+' operation and '*' operation; single-line retains the format r'...', multi-line '''...''' (and comments same symbols)
Using the j
or J
suffix, imaginary numbers can be assigned, but there must be a real number before j/J, such as 2+1j, and cannot be written as 2+j; this can be distinguished from the variable j
The length of the list is variable, it can store various types of variables/constants, and it can be changed with append(); it can also be combined with other lists through '+' to form a new list
Slice[a:b] is a very convenient tool, the left and right slice positions can be variables, but a must be less than b, otherwise it is empty[].
range
range(start, stop, step) returns a range object, list(range(5)) returns [0,1,2,3,4]; list(range(1, 4)) returns [1, 2,3];
list(range(1,5,2)) returns [1,3]
break is to end the entire loop body, continue is to end a single loop
Formal parameters (positional parameter a, default parameter b=1)
The default value in the formal parameter, def abc(a,b=4,c=[]), where b and c are the default value parameters , so the actual parameter can be like this, abc(5) and let b, c default
There is a positional parameter a in the formal parameter, and the default parameter b=3, the default parameter must be after, that is, abc(a,b=3), but not the other way around
Note: The default value is only initialized once, when the default value is a mutable object (such as a list, dictionary or an instance of most classes), it will not be released after the method is executed
def f(a,b=[]): L.append(a) return L, after calling f((1), f(2)), output [1], [1,2] respectively
Formal parameters can receive tuples and dictionaries, one star (*): indicates that the received parameters are processed as tuples; two stars (**): indicates that the received parameters are processed as a dictionary
However, the tuple will treat the following parameters as tuple elements, so use the key parameters to pass the value; while the dictionary will treat the key parameters as dictionary elements,
And the key parameters cannot be placed in front of the positional element (that is, the dictionary parameter), and the direct transmission will make an error. It is not clear why, so there is no solution for the time being;
Actual parameters (key parameter b=3)
The actual parameter cannot define a variable, such as abc(i=5), but it can be a keyword parameter , that is, the letters are the same , it must be abc(a=5), where a=5 is a parameter rather than a definition
The order of keyword arguments in actual parameters is not important, i.e. abc(b=1,a=2)
Unpack the parameter list, that is, add * or ** before the tuple or dictionary variable to complete the unpacking, such as d=[3,4,5], abc(*d) can pass the value to abc(a,b respectively ,c) in
day02
iterable: Iterable objects, such as list, tuple, dict, str, are all iterable (anything that can be looped is Iterable)
Tuple, length and each element cannot be changed, and parentheses or no parentheses, tuple1=(1,2), tuple2=1,2 When an element is followed by a comma, ('a',)
gather
There is no order and cannot be repeated. The set(iterable) method can be used to return the set, or the braces are defined, but the braces cannot be empty when they are defined, because {} is a dictionary
Can perform logical operations & | ^
dictionary
Initialization: a = {'key1':value1}, add: a['key2']=value2; you can also use the dict() method or list comprehension to build a dictionary;
Indexing refers to keys, not positions, keys can be of immutable types, numbers, strings, tuples that do not contain mutable types can be used as keys
The keys() method returns the dict_keys type (iterable, non-list, cannot be indexed) instead of a list, it needs to be indexed after list (dict1.keys());
键:for a in dict.keys():,值:for a in dict.values():,键-值:for a,b in dict.items():,整体:for a in items():
pop(key1) pops up the element corresponding to key1; popitem() pops up the last element, which is unique to the dictionary
List :
Add: append(x), x is a constant; extend(a), a is a list; insert(i, c), i is a position, c can be a constant or a list
delete: remove(x), x is constant and must exist in the list to be removed; pop(i), removes the number at position i and returns the number at position i
del list1[i1:i2], delete according to the index, i1 and i2 are indexes; clear() clears the list
index(x), returns the first index of x; unique sort() method
The lambda keyword creates small anonymous functions, limited to a single expression that returns the sum of two arguments: c =lambda a, b: a+b
map method
map(func, iterable, iterable,...), func is a method, followed by at least one iterable, and the number and order of iterables must be consistent with the formal parameters of func
The return value is: the calculated result of each iterable value passed into func, you can use list() to save these values, list(map(func, iterable, iterable,...))
List Comprehensions - List Comprehensions
Similar to lis(map(func,iterable,…)), like: [(x, y) for x in [1,2,3] for y in [3,1,4] if x != y]
Rule: Consists of a pair of square brackets containing an expression, followed by a for clause, followed by zero or more for or if
clauses
Nesting of list comprehensions, [[row[i] for row in [[1,2],[3,4]]] for i in range(2)], the result is [[1,3],[2 ,4]]
The zip() method, zip([iterable, ...]), compresses the iterable into a tuple, which can be regarded as converting a column to a row, and decompressing zip(*zip()) is to convert the row and column once
enumerate method, list(enumerate(iterable, start)), the result is: [(0,'ab'),(1,'bc'),(2,'ef')]
Compare:
in/not in, is/is not; comparison operators have less precedence than arithmetic operators
Cascading comparison, a < b == c tests whether a is less than b and whether b is equal to c; and/or/not, logical precedence less than comparison operators, and not>and>or
The sort() method is only used on lists to modify the original list, while sorted(iterable) returns a new iterable object for all iterable objects
day03
method
The essence of the method is the object, which can be referenced by variables, def abc():, a=abc, so a() and abc() are equivalent, pay attention to the difference with a=abc()
Methods can also be defined in methods, that is, methods can be nested, but the nested methods cannot be called directly from the outside.
Use of nested methods: ① Only used inside the main method, get/use the calculation results of nested methods inside the method
②For external use, first 'return the nested method', then a=abc() to call the main method and assign it to the variable, then the nested method a() can be called externally, don't forget to add parentheses
splicing
+, limited to the same type, as a string/tuple/list, but not a dictionary/collection;
To output a string + list, you must convert the list to a string, such as print('the list is:'+str([3,4,5,]))
input('prompt information'), user input
module-module
Import the module, import module1 , the calling method must add the module name, module.func1
To import a method or variable from a module, from module1 import func1/var1, you can use func1/var1 directly without adding the module name when calling
In the form of from xx import xx, the variable will be added to the current namespace, so it may lead to overwriting, so it is not recommended to use
Use as to avoid duplicate names, import module1 as md1, from mod import func/var as f/v
package-package , a package is a hierarchical file directory structure that defines a python application execution environment consisting of n modules or n subpackages
namespace namespace , four: Locals-inside the function, Enclosing-outside a function, global variables run by Globals, Builtin built-in module space
LEGB , when the program refers to the name of a variable, it will start searching from the namespace. The search order rule is: LEGB, search layer by layer, and stop searching after finding it
Decorator, which makes the method extensible, such as adding functions to the method, etc.
__name__, whose value is set by the Python interpreter:
If the script file is called as the main program, its value is set to __main__, and if it is imported as a module by other files, its value is its file name
locals(), returns a dictionary of local variables; globals(), returns a dictionary of global variables
vars(object), returns a dictionary of object attributes and attribute values, consistent with the locals() method when there are no parameters
reduce(function, iterable) method, which calculates the elements in the iterator according to the given method
day04
kind
Define the class, "class Car(FatherClass1, FatherClass2): ", the class name does not have to be uppercase, but it is recommended to use uppercase
Inheritance, FatherClass is the parent class, and multiple inheritance is possible, that is, multiple parent class objects are passed in
The instantiation of the class, car1=Car(),
There is a special method __init__(self, a, b) in the class, which is automatically called when instantiated, where self is the instantiation itself, that is, car1
Self does not need to be passed in, just pass in a, b, self can use other names such as me
Note: The properties of a class are mutable objects (like lists, dictionaries and most other types) that are initialized only once, i.e. all instances of the class share this variable
(this is similar to the problem of default values for formal parameters), when immutable primitive types (numbers, strings, tuples), there is no such problem
To avoid this problem, you can put it in the __init__() method, that is, self.a=b, and b receives a mutable object, such as [1,2,3]