Python basic knowledge of the whole network the most complete 1 (detail knowledge)

1. Note the syntax point

  • 0. Note:
 1.单行注释:   #      
 2.多行注释:    
         '''              """ 
                 或
         '''              """
 3.不换行输出
   print(index, end=" ")
  • 1. dir ( builtins ) : See all the components BIF
  • 2. Help (input) : View of the specific information input
  • 3. String : r preceded by a string into a native, i.e., does not escape; e.g. str = r "hello"
  • 4. Logical Operators and : and or not
  • 5. Boolean value : True False the first letter is capitalized
  • 6. operator :
    the Python in:
 10/8 = 1.25   10//8 = 1         2 ** 3 = 823次方

priority

  • 7. judge sentences : if and elif: the equivalent of us are familiar with if and else if

  • 8. The ternary operator : demo = x if x> y else y That is: if condition true false else

  • 9. for loop :

for demo in arrs
     print(demo)
  • 10. The ARR [. 1:. 3] : Returns an array subscript 1 to 3 (not including three) elements, that is, only to return arr [1], arr [2 ]

  • 11. The arr *. 3 : three copies of the arr without altering their

  • 12. fragment :

arr = arr2 []: to copy arr2 arr, the following will not change with changes arr2 process (arr = arr2) arr copied directly make changes with changes arr2

  • 13. tuple (tuple) : Wear yoke array (array elements can not be changed):
元组的创建: arr = (1,2,3,4,5,6)                 #小括号
       ()  (1,) (1,2,3)  1,2,3  以上四种都属于元组  (1)int类型
元组添加元素(类似于字符串)
       arr = (1,2,3,4)
       arr = arr[:2] + (5,) + arr[2:]
       结果: arr = (1,2,5,3,4)

t[1:3] # 这里 1:3 是 i>=1 and i<3 的区间

# Tuple 可以转换成 list, 反之亦然。
转换方式为:
t = list( t )
反之:
arr = tuple( arr )
  • 14. The global variables :

Internal function call to declare global variables: global count;

  • 15. Closure :
def Fun1(x):
      def Fun2(y):
            return x * y;
      return Fun2;

调用: Fun1(x)(y)  
  • 16. The closure within the package global variables :
def Fun1():
     x = 5
     def Fun2():
           nonlocal x                #声明使用的是外函数的变量
           x *= x
           return x
     return Fun2()
  • 17. The anonymous function (the lambda) :
g = lambda x : 2 * x + 1            #冒号前面是参数,后面是语句
相当于: 
      def g(x):
            return 2 * x +1
  • 18. recursion (recursion) :
    set the maximum number of recursion:
import sys
      sys.setrecursionlimit(100000)
  • 19. Dictionary (the Map) :
# 创建方式1: 
     demo = {1:"one", 2:"two", 3:"three"}
     # 获取"two": 
           demo[2]
# 创建方式2(dict()):  
     demo = dict((('F',10),('G',20),('H',30)))       # 中间一层括号是元组
     # 相当于: demo = {'F':10, 'G':20', 'H':30 }
# 创建方式3:  
     demo = dict(abc='你好', xyz='优秀')
     # 相当于: demo = { 'abc':'你好', 'xyz':'优秀'}
     # 获取'你好': 
           demo['abc']
     # 添加一组数据: 
           demo['ijk']= '当然'
  • 20. iterator ( Fibs.py ) :
    1. ITER (): the __iter __ () : object invokes ITER () of the object obtained iterator
    Note : __ two underscores, rather than an underscore
    2. Next (): the __next __ () : call next () iterator will return the next value:
    Example:
string = "FishC"
     it = iter(string)
     next(it)           #此处返回'F'
     #next()没有元素时会抛出StopIteration异常

Example: cyclic output string:

while true:
     try:
           each =next(string)
     exceptStopIteration:
           break
     print(each)
# for in循环是靠iter()迭代机制实现的
  • 21. The generator (the yield) : in fact, an implementation of an iterative
    Example:
def libs():
     a = 0
     b = 0
     while True:
          a,b = b,a + b
          yield a           #返回a并停止
  • 22. List derived formula :
    Example:
a = [i for i in range(100) if not(i%2) and i%3]
      #结果: 100以内所有能整出2但不能整除3的数
  • 23. Dictionary derivation :
    Example:
b = { i : i % 2 == 0 for i in range(10) }
       结果: 0-10以内所有数字与数字是否为偶数的对应关系的字典:: { 0 : True , 1 :False ,, 9 : False }
  • 24. A set of derivation :
    Example:
c = { i for i in [ 1 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 3 , 2 , 1 ]}
      结果: { 1 , 2 ,3 , 4 , 5 , 6 , 7 , 8 }   #不会出现重复的数字
  • 25. tuple derived formula : is a group generated iterator, the output data can be an iterative

  • 26. The channel coding configuration :
    provided sitecumtomize.py site-packages file folder, and writes:

import sys
sys.setdefaultencoding(‘gd2312’)

Such python is automatically installed when it will load this file, set the default code, spelling path path process can not go wrong

2. Type Conversion

  • 1. STR-> int Example:
a='520'  b = int(a)  即 b = 520    (str即字符串类型)
  • 2. INT-> STR Example:
a = 5.99  b = str(a)  即 b = '5.99'
a = 5e19  b = str(a) 即 b = '5e+19'

3. Exception Handling

(1) Exception Type Summary

Exception type summary
Exception type summary

(2) .try-except statement

usage:

try:
     检测范围
except Exception[asreason]:
     出现异常(Exception)后的处理代码

Example 1:

try:
     Sum = 1 + '1'
     f = open('我是一个文件.txt')       #此时文件不存在    
except OSError as reason:
     print('文件出错啦T_T\n错误的原因是' + str(reason))
except TypeError as reason:
     print('类型出错啦T_T\n错误的原因是' + str(reason))

Example 2:

try:
     Sum = 1 + '1'
     f = open('我是一个文件.txt')        
except OSErrorTypeError:
     print('出错啦T_T')

(3) .try-finally statement

usage:

try:
     检测范围
except Exception[asreason]:
     出现异常(Exception)后的处理代码
finally:
     无论如何都会被执行的代码

(4) .raise raises an exception

usage:

raise 异常名称
raise 异常名称:提示信息

(5) .with statement

usage:

with open('我是一个文件.txt') as f:
     for each_line in f:
          print(each_line)
# 如果文件存在,with语句会自动调用f.close()

4. module! Module!

  • 1.if __name__ == ‘__main__’:

If the statement is run the program itself after execution condition
statements if the external module as the program, the condition is not performed

  • 2. Search Path : Best storage path: 'C: \ python \ lib \ site-packages'
    Add search path:
import sys
sys.path.append("路径…")
  • 3. package (Package Penalty for) :
    Create a package:

1. Create a folder to store related modules, ie the name of the file name of the package
2. Create a module __init__.py file in the folder, the content may be empty
3. related modules into the file folder
4. import: import module name as the field application.

Guess you like

Origin blog.csdn.net/affluent6/article/details/91533443