Learning python

  • Three kinds of quotes

  1. Single quotes ' ' Indicates a string. Double quotation marks can be placed inside single quotation marks
  2. Double quotation marks "" Represents a string. Single quotation marks can be placed inside double quotation marks
  3. Three quotes "' or" "" Line breaks are supported. The other two do not support line breaks name = ''' 123
  • An escape character for a string

  1. \nA newline
  2. \tHorizontal tabs
  3. \renter
  4. \bBack space
  5. \aRing the bell
  6. \eescape
  7. \fChange the page
  8. \vVertical TAB character
  9. \ 000
  10. \Line continuation operator
  11. \ \Backslash notation
  12. \ 'Single quotes
  13. \"Double quotation marks
  14. \oyyOctal numbers, y represents a character from 0 to 7, for example: \012 represents a newline.
  15. \xyyA hexadecimal number, starting with \x, in which yy stands for a character, for example, \x0a stands for a newline
  16. \otherOther characters are printed in normal format
  • About the variable

  1. X,y,z = 1,2,3

  2. Variable names consist of letters, underscores, and numbers

  3. In administrator mode, enter Python and press Enter. Enter import keyword and press enter. Enter print(keyword. Kwlist) and press enter to display English words that cannot be used as variable names

  4. Key words:  'False','None','True','and','as','assert','break','class','continue','def',   'del','elif','else','except','finally','for','form','global','if','import',        'in','is','lambda','nonlocal','not','or','pass','raise','return','try',                'while','with','yield'

  5. Built-in functions (BIF) also do not have variable names:

'ArithmenticError','AssertionError','AttributeError','BaseException','BlockingIOError','BrokenPipeError','BufferError',' BytesWarning ', 'ChildprocessError, 'ConnectionAbortedError','ConnectionError,'ConnectionRefusedError','ConnectionResetError','DeprecationWarning','EOFError ','ELLipsis','EnvironmentError','Exception','False','FileExistsError','FileNotFoundError','FloatingPointError','FutureWa rning','GeneratorExit','IOError','ImportError','ImportWarning','IndentationError','IndexError','InteruptedError','IsADir ectoryError','KeyError','KeyboardInterrupt','LookupError','MemoryError','ModuleNotFoundError','NameError','None','NotADi rectoryError','NotImplemented','NotImplementedError','OSError','OverflowError','PendingDeprecationWarning','PermissionEr ror','ProcessLookupError','RecursionError','ReferenceError','ResourceWarning','RuntimeError','RuntimeWarning','StopAsync Iteration','StopInteration','SyntaxError','SyntaxWarning','SystemError','SystemExit','TabError','TimeoutError','True','T ypeError','UnboundLocalError','UnicodeDecodeError','UnicodeEncodeError','UnicodeError','UnicodeTranslateError','UnicodeW arning','UserWarning','ValueError','Warning','WindowsError','ZeroDivisionError','__build_class__','__debug__','__doc__', '__import__','__loader__','__name__','__package__','__spec__','abs','all','any','ascii','bin','bool','bytearray','bytes' ,'callable','chr','classmethod','compile','complex','copyright','credits','delattr','dict','dir','divmod','enumerate','e val','exec','exit','filter','float','format',frozenset','getattr','globals','hasattr','hash','help','hex','id','input',' int','in=sinstance','issubclass','iter','len','license','list','locals','map','max','memoryview','min','next','object',' oct','open','ord','pow','print','property','quit','range','repr','reversed','round','set','setattr','slice','sorted','st aticmethod','str','sum','super','tuple','type','vars','zip'

 

  • Input and output

1. A = input (‘ please input: ‘) print(a)Note:Input accepts all strings

2.inputThe inputprintOutput, print

 

  • Math module

import mathenter

math.pienter

Result PI output:3.141592653589793

Dir (math) View module contents

 

  • Numeric types

1. Integer Int Example: 123

Float: 0.001

  • 2.1 High precision floating point calculation 
    • import decimalenter 
      • decimal.Decimal('1.01') – decimal.Decimal('0.9')   Have toDecimal('0.9')
      • Note:You can usedecimalModule to do the exact calculation of floating point numbers, used when passed is astring

3. Boolean bool two values True (value 1) and False (value 0)

 

  • Numerical type calculation

    1. +   –   *   /   %Take more than   * * power operation   //aliquot 

    2. Symbol:! = Not equal == Equal >= Less than or equal to <= Greater than or equal to < Less than > Greater than

    3. With:andsaidandorand“Is true only if both sides are true

    4. Or:orsaidor“Is true as long as one side is true

    5. A:notIt means to take the opposite meaning true becomes false, false becomes true

  • Python operator priority

1. **Index (highest priority)

2. ~ + -Bitwise flip, unary plus and minus (the last two methods are called +@ and -@)

3. % * / / /Multiply, divide, find the remainder and take the exact division

4. + -Addition subtraction

5. >> <<Shift right, shift left operator

6. &A ‘AND’

7. ^ |An operator

8. < = < > > =Comparison operator

9. = =! =Equal operator

10. = %= /= //= -= += *= **=The assignment operator

11. is is notIdentity operator

12. in not inMember operator

13. not and orLogical operator

 

  • Identify the type

1.type()

The comparison operator returns a bool

 

  • String formatting

  1. %    Format placeholders
  2. %d   Format integer ~~ %6d Indicates the length of the character string
  3. %f   Format floating point (decimal) ~~ %06.2d 0 indicates padding. 2 indicates that only two decimal places are left
  4. %c   Format the ASCLL code ~~ %97 output the corresponding value of the ASCLL code 'a'
  5. %o   Octal output ~~ %8 Octal output '10'
  6. %x   Hex output ~~ %16 Output hex to get '10'
  7. %o   Octal output ~~ %8 Octal output '10'
  8. %e   + +04 = '1.000000e+04'
  9. %r   Object uninitialized ~~ %'123' uninitialized output object gets "'123'"
  10. %s   Formatted string   s=’hello’    t=’kt’   print('%s %s'%(s,t)) output concatenation string to get string 'hello kt'

 

  • The format method of a string

  1. '{a:.2f}'. The format (a = 12.3333)    Keep two decimal places The output of 12.33
  2. '{:.2%}'. The format (0.35)    It's printed as a percent sign The output of 35.00%
  3. '{0:x}'.format(20)    Convert to hexadecimal The output of 14
  4. '{b:0<10}'= 12.3. The format (a, b = 13.35)    Left-align and fill with the number 0 The output of 13.3500000
  5. '{a:*^10}'= 12.3. The format (a, b = 13.35)    Align center Output 12.3 * * * * * *
  6. '{{hello {} }}'.format(‘python’)    Escape the braces { hello python }
  7. 'f= 'hello {0}'.format f(‘python’)    Call as a function Output 'hello python'
    • Strings are usually immutable but usablereplaceThe () method replaces the string, but does not modify it. It simply returns a new object, as all string methods do

    • Mutable objects: list, dict, and set

    • Immutable objects: values, STR, tuples

  1. upper()All caps
  2. lower()All lowercase
  3. capitalize()Uppercase
  4. title()Capitalized word, title form
  5. strip()Remove the space on both sides
  6. Split () String splits (‘ string ‘, times)
  7. join()Joining together
  8. strip()Remove the space on both sides
  9. Find () finds the index value of an element in the string. If no element is found, -1 is returned
  • The string provides a method of determination inside

  1. isalpha()It’s all letters
  2. isdigit()It’s all numbers
  3. islower()Judgments are all lower case
  4. isupper()The judgment is all caps
  • Encoding of strings

  1. encode(encoding= '' )Encodes a string to the specified encoding
  2. decode( '' )In switching back
  • Python contains the following functions:

  1. cmp(list1, list2)Compare the elements of two lists
  2. len()Number of list elements
  3. max()Returns the maximum number of list elements
  4. min()Returns the minimum value of a list element
  5. list()Converts tuples to lists

 

  • Conditional statements

1.if else

ifPrint ()else:
  print()

ifElif: print()else:
  print()
Copy the code

2. Ternary operation

  print(True if a>5 else False)
Copy the code

3. The while loop

a = 1
while a<5:
  print(a)
  a +=1Execute in sequence until the loop endselse:
print('End of loop') ifwhileIf the following condition is True, the inner condition is addedbreakTo terminate the loop, usebreakA terminated loop is not executedelseThe content of thecontinueIt just jumps out of the current loop and executes the next loopCopy the code

4. The for loop

for i in 'python': print(I) Loop The length of the string len determines the loop numberCopy the code

P, y, T, H, o, n

for i in range(10):
  print(i,end=', ') 
Copy the code

The result is 0,1,2,3,4,5,6,7,8,9

The range function can take a range of integersRange (start, end, step size)
End in print sets the string to be printed after each value is printed. The default is newline
      • Iterable: strings, lists, tuples, dictionaries, collections
for i in range(1.6.2):
  print(i,end=' ') 
  i = 'python'
  print(i,The '*')
Copy the code

The result is 1 python * 3python*  5python*

for i in range(1.20) :if i % 2= =0 or i % 3= =0:
    continue
  else:
  print(i,end=', ')
Copy the code

The result is 1,5,7,11,13,17,19

forCirculation andwhileLoops can be usedbreakandcontinue   It can also be connectedelse, when the loop isbreakAt the end of,elseDo not perform

for i in range(1.20) :if i % 2= =0 or i % 3= =0:
    continue
  elif i % 15= =0:
    break
  else:
  print(i,end=', ')
else:
  print('End of loop')
Copy the code

The result is 1,5,7,11,13,17,19, and the cycle ends

List = [] Lists can hold almost any Python object

  • Take all even numbers up to 100:

  • 1. for i in range(101): if i % 2 == 0: print(i)

  • 2. list_a = [] for i in range(101): if i % 2 == 0: list_a.append(i)

  • List_b = [I for I in range(101) if I % 2 == 0]

I is the value stored in the list for I in range(101)for loop to get the value if I % 2 == 0If judgment to filter the value [] enclosed in brackets to indicate the list

  • List the list

    • List = [Start: end: step]

Three ways to add:append(‘ single add ‘);extend([‘ batch Add ‘,’ batch Add ‘]);insert(1,’ add at specified location ‘)

There are three ways to delete:pop(‘ remove one at a time ‘);remove([‘ remove specified element ‘]);claer(‘ One-time empty ‘)

Other methods of listing:count(‘ number of statistical elements ‘);reverse([‘ reverse list order, not sort ‘]);sort(‘ Sort the elements in the list using Timsort ‘);copy(‘ copy ‘);

  • Tuples:

  (a)The inside of the fortuples, like a list, can also index values, but elementsYou can't change it. Once you're sure, you can't change it. If the tuple has only one element(1)Again, keep up with the comma,Otherwise it will be treated as an elementRather thantuples

unpacking: Tuples can be assigned to more than one variable at a time, as long as the number of variables does not exceed the length of the variable*A sign can take multiple elements and form a list

Ex. :

A = b = (1) ([' hello, 'the python,'! ']) = c ([6,8,10]) tuple_d = a, c print *, b * (tuple_d)Copy the code

Results for ((1), ‘hello,’ python ‘, ‘! ‘,6,8,10) can be checked with type (tuple_d)

  • Dictionary:

Dictionaries are defined as key-value pairs

1. dict_a = {} An empty dictionary

2. dict_b = dict(a=1,b=2) Use the dict function to define a dictionary

3. dict_c = {‘a’:1,’b’:2} It's the same as dict_b

Add, delete, modify and check the dictionary

  • throughkeyTo the values,keyIf it does not exist, an error is reported
  • throughget()Method to evaluate,keyDoes not exist, and no error will be reported
  • throughsetdefault()Method to find whenkeyIf it exists, returnvaluesValue if key does not existAdd key-value pairs
  • throughupdate()Methods can be updatedkeyThe value of, ifkeyThere is no,Add key-value pairs
  • keys()Method to get all of themkey
  • values()Method to get all of themvalues
  • items()Method to get all of themKey/value pair
  • pop()Method to delete the specifiedkey
  • popitem()Method to delete the last one in the dictionaryKey/value pair
  • clear()Method to delete all elements in a dictionary

Operation of set

  • Intersection: used by the same elements in two setsset()said&
  • Union: The combination of different elements of two sets|
  • Difference set: Two sets minus the same elements in both sets-

Create an empty collection must be usedset()Rather than{}Because the{}Is used to create an empty dictionary.

Collection of add delete change check

  • Add () adds elements
  • Update () adds parameters that can be lists, tuples, dictionaries, etc
  • Pop () randomly removes an element from the collection
  • Remove () removes elements

Judgment of set

1. isdisjoint()Checks whether two collections contain the same element, returning True if none, False otherwise.

2. issubset()Determines whether the specified collection is a subset of the method parameter collection.

3. issuperset()Determines whether the method’s set of parameters is a subset of the specified set