程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python

編輯:Python

Preface

          Study Python Content !     Learning links on the official website

List of articles

  • Preface
  • One 、 brief introduction
    • Python Characteristics of language
  • Two 、Python Interpreter
    • File mode
    • Interactive mode
  • 3、 ... and 、 operation
  • Four 、 list
  • 5、 ... and 、if sentence
  • 6、 ... and 、for sentence
  • 7、 ... and 、 function
  • 8、 ... and 、 data structure
  • Nine 、 modular
  • Ten 、 Input and output
  • 11、 ... and 、 abnormal
  • Twelve 、 class

One 、 brief introduction

Python Characteristics of language

  1. python A statement in can perform many complex operations ( Grammatical sugar )
  2. Use Indent To distinguish code blocks .C++ and java It's through {} To distinguish between
  3. Variables need not be declared , It can be used directly
  4. Easy to expand

Two 、Python Interpreter

Version is Python3.10

File mode

  1. perform python file (.py ending )
    Input python3 Will go directly to a python Interpreter ,python The interpreter can be used to directly execute a python file (python Can be like other languages , Put it in a file to write ), It's like writing shell Script .

    function python There are two ways to code files :
    1. python3 file name .py
    2. ./ file name .py, The file needs to have executable permissions , If not implemented :chmod +x file name .py

Interactive mode

  1. Interactive execution (ipython3 Support highlighting )
    • With notes #, The comment statement is on a separate line , Or two spaces after a statement
    • The execution of a single sentence , Support auto completion ( Press two tab key )
    • The up and down keys can switch the previously executed statements
    • sign out , By input exit() Or shortcut key ctrl+d




3、 ... and 、 operation

  1. Numbers

    • / : The default is floating-point division ,//: to be divisible by , yes Rounding down (-1 // 3 ( Is minus one third ), Rounded down to -1).C++ The integral division of is rounding to zero (-1 / 3 Is minus one third , Round to zero )
    • **: Multiplication
    • Variables do not have to define types , Just use it directly .n = 20, Note that if the variable is not assigned a value, it cannot be used directly
    • Exchange two variables :a, b = b, a
    • In interactive mode _ Represents the value of the previous expression
  2. character string

    • character string :python String and C++ In the same way , The difference lies in python Both single and double quotation marks can represent strings , There is no difference between .python The string in cannot be modified

    • Subscript :

      • python The strings and lists in are both accessible from front to back , You can also visit from back to front .
      • Subscript plus - Represents a number from right to left , From right to left When counting, subscript from 1 Start . No addition -, Express From left to right Count , Subscript from 0 Start
    • section

      • The interval is a Left closed right away The range of ,word[0:2]
      • Omit the previous time , The default is 0, Omit the following , The default is string length .word[:2] word[4:]
      • Support negative numbers .word[-2:] word[-5,4]
      • Support addition .word[:2] + word[2:]
      • Direct operation subscript cannot be out of bounds , But the slice can cross the boundary
    • len: You can find the length of all types

Four 、 list

  1. analogy C++ In the array . Use brackets ([]) Express , Use commas for each element (,) separate , The type of each element in the array can be different

    a = [1, 4, 9]
    b = [1, 2.0, 'yjx', [2,3]]
    x, y, z = a
    
  2. You can access elements by subscript , Support slicing operation . Element supports modification , Unlike strings .x[0] = 4,x[1:3] = ['a', 'b']

  3. Shallow copy

  4. Add operation is supported , The effect is to splice the two arrays together

  5. Additive elements :a.append(6) perhaps a += [7], Add elements at the end of the list

  6. len(a): Ask for a list a The length of ,sroted(a): Sort list

  7. x[:] = [],[]: empty . Empty an array

  8. Two dimensional array : Lists are nested , It's a two-dimensional array ,x = [[1,2], [3,4]]

  9. a, b = 0, 1 python Support compound assignment : The first term is assigned to the first variable , The second term is assigned to the second variable , And so on …

5、 ... and 、if sentence

>>> x = int(input("Please enter an integer: ")) # Read in an integer , adopt int Function to convert a string to an integer 
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...

6、 ... and 、for sentence

python Medium for loop : There's a bunch of things , adopt for Loop through enumerations one by one , Arithmetic operators are not supported , Can't directly implement things like C++ Medium for (Int i = 0; i < 10; i ++) Such operation

  1. Loop through a list

     words = ['cat', 'window', 'defenestrate']
    for w in words:
    print(w, len(w))
    
  2. Loop through a dictionary

  3. use range To implement a common for loop
    range(): Will return a Left closed right away The range of

    for i in range(0, 10)
    print(i)
    

    range Reverse order can be achieved :range(9, -1, -1), The third parameter is tolerance
    When there is only one parameter :range(10): The default is equivalent to range(0, 10)

7、 ... and 、 function

  1. python If the return value is not written , The default is to return a None( Be similar to C++ Medium NULL)
  2. python You can define functions with duplicate names in , The next function with the same name will overwrite the previous one
  3. Function parameters do not need to write variable types ,python Will automatically determine the type of variable
  4. Variables that set default values must be continuous
  5. Functions can be assigned directly :f = g, among g and f It's all functions
  6. Unpack :*, Expand the elements in the list into several variables separated by commas , Parameters assigned to the function , Call... As an argument to a function . Unpack a list with *, Unpacking a dictionary is to use **

8、 ... and 、 data structure

  1. list

    • List derivation : Like inversion :
      b = [i *i for i in range(10)] # b Every element in it is i*i,i Is the enumeration [0,9]
      
  2. Tuples

    • a(1, 2, 3), Notice the use of parentheses , The list is in square brackets . Similar to list operation , The only difference is that the elements in the list can be modified , Elements in tuples cannot be modified
    • You can assign a tuple to a variable :b = (1, 2, 3), Brackets can be omitted :b = 1, 2, 3. You can also assign a tuple to several variables in reverse :x, y, z = b, among x = 1 y = 2 z = 3 ( Unpacking operation )
    • In exchange for :y, x = x, y
  3. aggregate (set)
    Analogy to C++ Of set

    • Definition : a = se(), a = {1, 2, 3},{} It can represent either a collection or a dictionary , The distinction mainly depends on what is stored in it key-value Yes or a separate value , If it is key-val Yes, that's the dictionary , If it is a single value, then it is aggregate
    • Additive elements :a.add(1). Only one of the same elements is reserved , If the newly inserted element appears in the collection , Then the new element will not be inserted into the collection
    • effect : It is generally used to judge the duplicate of a list ‘
      a = {
      1,2,2,3,5}
      set(a) # The result is the set after de duplication 
      a = list(set(a)) # The result after de duplication is still a list type 
      
  4. Dictionaries (dict)

    • Definition tel = {'jack':4096,'sape':4139}
    • modify :tel['jack'] = 8888

Nine 、 modular

  1. Why modules are needed ? answer : It is difficult to debug a large project if all the contents are written into one file , You need to split a huge project into several modules . Adopt tree structure in project development , Each folder represents a module .

  2. Introduce a self defined module , Reference... In other documents
    from File path (. spaced ) import file / function / class , When introducing multiple , For each , separate

  3. When introducing a function and renaming

    • Why do I need a duplicate name : When functions with the same name in different files are introduced into one file, conflicts will occur
    • from File path import function 1 as Alias , function 2 as Alias
  4. python A large number of modules have been implemented in , Directly after installation import Just come in

Ten 、 Input and output

  1. It can be used print Formatted string ,% (): Pass in the corresponding parameter , It can be like C++ Same format output
  2. Read and write files
    • Write content into a file
    • Read from a file
      • fin.read() Read all contents of the file

      • fin.readlines() Read all lines , Will return a list

      • Read in line by line

11、 ... and 、 abnormal

effect : When you open a website 502 When it's wrong ,502 An error is an exception in the program , Will catch the exception , Users will not see 502 You will jump to a 404 page

def divide(x, y):
try: # Try to execute the contents of this code block 
res = x/y
except Exception as e: # If there is an anomaly , Do the following 
print(str(e)) ## Direct output exception , There is no error in the procedure , The program is still running normally , If you do not use exception handling , After the operation, the subsequent program will not be executed 
else: # If nothing unusual happens , Content that does not execute exception handling , Will execute else Contents of Li 
print("result is", res)
finally: # The following will be executed regardless of whether an exception occurs , It is usually used to close the database 
print("executing finally clause")

Twelve 、 class

  1. Definition
    __self__init(self): Intrinsic function , Be similar to C++ Middle constructor , Be careful self Be sure to write , Arguments can also be passed into the constructor .python The member variables in are written in the function ,C++ The member variables in are written outside the function .python Classes and functions are used in the same way
    a = Car(): Instantiate an object ,update: Member functions ,a: Member variables



2. Inherit ( Parenthesis )


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved