A) use the escape character' \' b) print r' c: \ now' using the original character' r'
2) single line comments, using the # sign, such as:
#hello Python multi-line comments, using three single quotes (or three double quotes), such as:'' hello pythonhello world'' or ""hello pythonhello world """a string that spans multiple lines. You can also use three single quotes or three double quotes, such as'''' ...' or ""... """
3) Special symbols, such as double quotation marks, are embedded in the string.
A) Use the escape character' \' b) Enclose the string in single quotation marks. print ('i l"o"ve fis.com )
4) Conditional branch:
If condition: operation with true condition else: operation with false condition If condition: Actionelif condition: Actionelse: ActionPython can effectively avoid "hanging else" conditional expression (boolean-exp symbol) small = x if x
5)while condition:
Operation of the target in the expression: circular example: favorite =' fishc' for i in favorite: print (i, end ='') range (] Create an empty list: empty=[] Add an element to the list: append (): member. append ('flowa')-> Only one can be added. Add extend (): member. extend (['test',' test 1']) at the end-> can only be added as a list. Add insert (): insert (): member. insert (1+0,' Peony') at the end-> The first bit is inserted into the peony list to get the element: use the index index. To remove an element from the mix[ 1] list, do the following: Use remove (). Mix.remove ('little turtle') uses del. Del mix[3]/mix uses pop (). Mix.pop()/mix.pop( 1) list slicing: Use slice. Mix [1:4]/mix [1:]/mix [:4] list operators: >, and,+,*, in/not in list friends: dir (list) mix.count ('turtle') mix.index ('turtle') Mix.reverse () list sorting: use sort. Mix.sort() mix.sort(func, key) mix.sort (inversion = true)
1 1) tuple->; Immutable list
The main differences between linked list and linked list are: a) create and access a tuple: most of them are ()/,; List with []b) tuple invariant value c) Update and delete a tuple: temp = temp [:2]+('test3',) +temp [2:] del tempd) in/not in, relational operator, logical operator, multiplication operator and join operator.
12) string.
Str 1 =' I love fishc.com' A = STR1[:6]+'Insert string' +STR 1 [6:] Capital (): STR2. Uppercase () casefold ()- > all lowercase str2.casefold () center (width)->; Center, there is not enough space to fill count (sub [,start [,end]])-> return sub in the string Endswith (sub [,start [,end]]-> end with sub? Startswith (prefix [,start [,end] ]])-& gt;; Expand the tab with the prefix ([tabsize = 8])- > convert the tab key into a space find (sub [,start [,end]])- > Does sub appear in the string rfind (sub) ... index (sub [,start [,end]])-> Like sub, However, an exception will be generated: index (sub ...) ... is title ()/isupper ()/lJust (width)/lower ()/strip ()/title ()/lower () join (sub): divide the sub-partition (sub) with the character string as the separator: find the substring sub. Divide the string into triples: replace (old, new [,count]) split (sep = none, maxsplit =-1)-> swap case ()-> string case flip zfill (width)-> returns a string with a length of width, which is not enough to fill the space.
13) string format substitution
"{0} Love {1}. {2:.2f}”。 Format ("I", "fishc", 3. 1424)"{a} love {b}. {c}”。 Format(a="i ",b="fishc", c="com")"{0} love {b}. {c}”。 Format("i ",B="fishc", c="com ") Meaning of formatting symbol: %c: formatting character and its ASCII code'% c% c'% (97 97,98,99)% s: formatting string %d: formatting integer %o: formatting unsigned octal number %x: formatting. You can specify the precision after the decimal point %e: Use technology to format a fixed number of points = =% e% g: Use %f or% e = =% g formatting operators according to the size of the value. Auxiliary command: m.n: m is the minimum total width of display, and n is the precision of decimal places-:used for left alignment+:add a plus sign before positive numbers #: display 0 before octal.
14) sequence
* * * Similarity of list, tuple and string: a) All can be indexed; B) the index value starts from zero, and the built-in method: list ()-> help-> Convert to sequence list () A = list () list (iteration) B =' I love fishc. Com' b = list (b) tuple ([iterated])-> converts the iterative object into tuple b = tuple (b) str (obj)->; Converts an obj object into a string len (obj)- > returns the length of obj max (sequence/tuple)/min (sequence/tuple) sum (iterateable [,start = 0])-- > returns the sequence iterateable. . Sum of sorted (sequence/tuple)->; Reverse sort (sequence/tuple)->; Returns a list of iterator objects (in reverse)->; Returns sequence enumeration (sequence/tuple)->; Returns an iterator object list (enumeration)->; Returns an array list zip (a, b)- > merged into a list in tuple form (zip(a, b)).
15) function
Definition: def Myfunction (): print ('This is my first function') Call: parameters of my function () function: def Myfunction(name, age): print (name+age+'test') my function (return value of' gncao',' age') function: return value parameters: parameters when defining the function. Check the function documentation: a) Function name. __doc__ (four underscores) b) help(functionname) keyword parameters: avoid the confusion of the parameter def Myfunction(words, name): ... My function (words =' words 123', Name =' name 123') default parameter: def my function (name =' name 123', Words='words 123') ... collection parameter: add * def test(*params): print ('parameter. Turtle', 2, 4, 5, 6, 7) def test (* params, exp): print ('parameter length is:', len(params), exp) print ('second parameter is:', params [1]) test (65438).
16) function has a return value, but the procedure does not.
17) function variable scope (visibility)
Local: local-> Variables defined inside the function can be used locally and globally: global->; Global Accessibility When you try to modify a global variable in a function, a new local variable with the same name as the global variable is created in the function.
18) embedded functions and closures
Global keyword: def myfun (): global count-> > > global variable count= 10 print(count) embedded function: deffun 1 (): print ('fun1() called ...') def fun2(): print('fun2 () called'). Make the internal function a closure deffunx (x): deffuny (y): return x * y return funy calling method: i=funx(8) i(5) or funx(4)(5) The keyword nonlocal can make the internal function call the external function variable. Def fun 1(): x=5 def fun2 (): non-local x x*=x return x return fun2 ().
19, recursive:
Recursion () deffac (n): if n = =1:return 1 else: return n * fac (n-1) number = int (input ('please enter an integer:')) result = Fac(number). The factorial of print('% d' is: %d'% (number, result)) Iterative method: deffab (n): n1=1:print ('input error') while (n0): n3 = N2+n/kloc-0. =-1: print ('total * * * has %d for bunny birth:'% result) recursive method: deffab (n): if n
20) dictionary (key-value) mapping/sequence example 1: dict 1 = {'Li Ning':' Anything is possible',' Nike':' Just do it', Adidas':' What can't be'} Print (the slogan of' Li Ning' is' Dict 1[' Li Ning']) Example 2: dict 3 = dict (('f', 70), ('i', 105)) Example 3. A built-in method of key dictionary is automatically added: a) dict2 ['key']-> Access dictionary element from keys (s [,v]) b)- Create or query the key dict 1. From keys (( 1, 2,3)) {1:none, 2: none, 3: none} dict 1. from keys (( 1,2,3))。 dict . keys()-& gt; Print out all key values of dict ()-> dict.values ()->; Print out all valueitems () of dict-> dict.items ()-> Print out dict all (key, value) get ()-> dict.get (key)-> Print the value corresponding to key. get (key,' text ')- > print the value corresponding to key. If it does not exist, print the textin operator->; Type dict2clear ()-> dict . clear()-& gt; Clear dictionary data copy ()-> b = a . copy()-& gt; Copy dictionary id (a)- > check id pop (key)-> dict.pop (key)->; Pop up keypopitem ()-> dict . pop item()-& gt; keyset default()-& gt; dict . set default(key)-& gt; Create a new keyupdate ()-> dict.update (dict)-> Update dictionary