Python learning

Autumn maple 2020-11-16 10:29:45
python learning


One 、PYTHON The elements in

1. The basic elements

  • Operator : + - * / % wait
  • The order of operations : First, To add and subtract Brackets first
  • Variable : It's a label :, A letter that begins with a non number 、 Numbers 、 Underline composition , Its content can be numerical 、 character string 、 list 、 Tuples and dictionaries .
  • The number , Is the number . Such as a = 100
  • character string , It's a pair of quotation marks 、 Or in single quotation marks , Just put it in quotation marks , It's just a string .    

Such as : b = ”Hello World”
100 Numerical value , and ”100” Is string .      

  • Escape character

\t Express tab                    \n Express in That's ok

  • %s placeholder , use % After the variable replacement

Such as :
a = 100
b = ” HelloWorld ”
print ” point = %s \n \” %s   \” ”  % (a, b)  
Print out :
point=100
” Hello World ”

2. list

for example :

c = [1,2,3,4,5,6,7] 
d = [” Zhang San ”,” Li Si ”,” Wang Wu ”]  
e =[1,2,3,”4”,”5”,d]

  • use List name [ Reference no. ] Index the elements in the list    

d[0] Represents a list d The zero element in “ Zhang San ”

  • Use the list name [ rise : stop ] It means slicing , Cut out the corresponding elements from the list Before closed after opening

c[0:2] Cut out [1,2]
c[ : ] Cut out [1,2,3,4,5,6,7] 

  • Use the list name [ rise : stop : step ] Slice with step size , Step size has direction .

Such as c = [1,2,3,4,5,6,7] , If you cut out [5,4,3,2] use c[4 :0 :-1]  ; Cut out [5,4,3,2,1] use c[4 ::-1] ; Cut out [6,4,2] use c[-2 ::-2]; Start from the second to the last and cut all the way to the end , step -2

  • modify : List name [ Reference no. ] = The new value
  • Delete :del List name [ Reference no. ]  
  • Insert : List name .insert( Insert position index number , The new element )
  • If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming

3. Tuples

Once the definition cannot be changed

f=(1,2,3)

4. Dictionaries

  • There is... In the dictionary { key : value , key : value , key : value } n Key value pairs

   dic={1:”123”,”name”:”zhangsan”,”height”:180}

  • Use the dictionary name [ key ] The values in the index Dictionary     

  dic[”name”] A dictionary dic In the key ”name” Corresponding value ”zhangsan”

  • modify : Dictionary name [ key ] = The new value
  • Delete :del Dictionary name [ key ]  
  • Insert : Dictionary name [ New key ] = The new value

Two 、python grammar

 Python The code is indented with four spaces to represent the hierarchy

  • Loop statement
  1. for Variable in range ( Starting value , End value )       for example :
     
  2. for Variable in List name     Such as :
    M = ['a', 'p', 'o']
    for i in M:
  3. while   Conditions    :
  4. Terminate the cycle with break 
  • turtle modular

import turtle # Import turtle model block

t = turtle.Pen ( ) # use turtle Module Pen class , An example is called t The object of

t.forward ( Pixel point )  # Give Way t How many pixels forward

t.backward ( Pixel point )  # Give Way t How many pixels forward t.left ( angle )         # Give Way t How many angles to turn left t.right ( angle )        # Give Way t How many angles to the right t.reset ( ) # Give Way t complex position

  • function
  1. function (function): Well organized , Reusable , A piece of code used to implement a single or associated function .
    such as input() It's just a function , You can use functions directly , You don't have to redefine how to receive input from the console every time , So the function is to help realize code reuse .

  2. Defined function :def    Function name    ( Parameter table ):
                          Letter Count body   The parameters in brackets can be empty if they are not needed

  3. Using functions : Function name ( Parameter table )   

    Such as :input("please input your class number:")
    Definition :def hi_name(yourname):
                      print ”Hello %s”%yourname Use :hi_name(”zhangsan”)
    Will be output :Hello zhangsan
  4. Function return value : return  
         def add(a,b):
               return a+b
         c=add(5,6)               # c To be an assignment add The return value of 11 
  5. Built-in functions :python Functions that come with the interpreter
    Such as :abs(-10) return return 10 


  • modular

modular (module): It's a Python file , With .py ending , Contains Python Function, etc . First import , Reuse , With modules . Function name call .

for example :
import time
time.asctime ( )
Output :'Tue Jan 1621:51:06 2018'

  • package

Contains multiple modules , Such as :from PIL import Image

  • Variable scope

local variable : Variables defined in functions , It's only in functions , The end of function execution cannot be used again . Global variables , A variable defined before a function , Usually defined at the top of the entire code , Global availability .

If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming

3、 ... and 、 class 、 Object and object-oriented programming

  • class (class): A collection of objects with the same properties and methods . It defines the properties and methods that are common to each object in the collection . Object is an instance of a class . Birds of a feather flock together , Classes are molds that instantiate objects .
  • real example turn : Yes like = class ()  Such as :t = turtle.Pen()
  • object : Is an entity instantiated from a class , The object really exists , Finish the specific work .
  • object-oriented : The programmer modifies the optimization class over and over again , Class instantiates the object , Object calls the function in the class to perform the specific operation .


For example, in the figure above , There are animals 、 Mammals and cats . Animals are a class , They have a common function : breathing 、 Moving and eating . Mammals are also a class , They're a subclass of animals , On the basis of animals, it has the function of feeding milk . Cats are a subclass of mammals , Cats have the function of catching mice on the basis of mammals .

The first letter of a class is often capitalized , such as Animals、Mammals and Cats The initials of are all capitalized . The right side of these classes lists the functions that each class has : Like breathing 、 Moving and eating are the functions of animals , To express in the form of a function in a computer . Feeding is a mammalian function , It's a function of the mammalian class . Catching mice is a function of cats , It's a cat function .

√ The above class is the parent of the following class ; The following class is a subclass of the above class

√ Subclass instantiated objects , You can use functions and variables of itself and its parent class

  • The definition of a class : 

class Class name ( Parent class name ) : 
      pass

If there is a parent class , Write it in brackets after the class name ; If there is no parent class , You can stop writing brackets . Use the key words pass Take a place , After that, we use the concrete function to complete the class . 

give an example :classAnimals:
       pass
classMammals(Animals):
       pass
classCats(Mammals):
       pass

  • When you define a function in a class , The syntax states that the first parameter must be self .
  • init__ function , It runs automatically when a new object is instantiated , Used to assign initial values to new objects .

(1) The cat class is instantiated into a name called kitty The object of ,kitty It has its own characteristics , For example, you have 10 Spots :
kitty = Cats(10)        # Run on instantiation   init  function , to spots assignment , inform kitty Yes 10 Spots
print”kitty.spots” # Print out 10
(2)kitty You can do specific work , Like catching mice :
kitty.catch_mouse()# Object to run functions , You have to use objects . Function name , Call the function in the class
                    # Will run print ”catch mouse” So print it out catch mouse

  • Object calls the function in the class , use object . Function name ;
    Object calls the variables in the class , use object . Variable name .
  • When defining a function within a class , Such as calling functions and variables of its own or parent class , Must use self. guide , Should be written as  self. Function name or  self. Variable name .

Code validation :



  • Add :

Python Although there is no access control keyword in , for example private、protected wait . however , stay Python In the encoding , There are some conventions for access control .

Underline 、 Double underline 、 Double underline description : 

_foo: What begins with a single underscore is protected Variable of type , That is, the protection type can only be accessed by itself and its subclass , Cannot be used for frommodule import *

  foo: Double underscores indicate private types (private) The variable of , Only the class itself can be allowed to access .

  foo__: Double underscores define the special method , similar init() And so on. .

Four 、 File operations

 

  • File write operation

import pickle

open : File variables = open(” File path file name ”, ”wb”)
save :pickle.dump( Variable to be written , File variables )
Turn off : File variables .close()     

Code validation :          

  • File read operation

import pickle

open : File variables = open(” File path file name ”, ”rb”)
take : Put the variable of content =pickle.load( File variables )
Turn off : File variables .close()                      

Code validation :

If you like to program, you can add some Q Group 867067945, You can get free learning materials when you join the group ! The group is full of friends who want to learn programming

版权声明
本文为[Autumn maple]所创,转载请带上原文链接,感谢

  1. 利用Python爬虫获取招聘网站职位信息
  2. Using Python crawler to obtain job information of recruitment website
  3. Several highly rated Python libraries arrow, jsonpath, psutil and tenacity are recommended
  4. Python装饰器
  5. Python实现LDAP认证
  6. Python decorator
  7. Implementing LDAP authentication with Python
  8. Vscode configures Python development environment!
  9. In Python, how dare you say you can't log module? ️
  10. 我收藏的有关Python的电子书和资料
  11. python 中 lambda的一些tips
  12. python中字典的一些tips
  13. python 用生成器生成斐波那契数列
  14. python脚本转pyc踩了个坑。。。
  15. My collection of e-books and materials about Python
  16. Some tips of lambda in Python
  17. Some tips of dictionary in Python
  18. Using Python generator to generate Fibonacci sequence
  19. The conversion of Python script to PyC stepped on a pit...
  20. Python游戏开发,pygame模块,Python实现扫雷小游戏
  21. Python game development, pyGame module, python implementation of minesweeping games
  22. Python实用工具,email模块,Python实现邮件远程控制自己电脑
  23. Python utility, email module, python realizes mail remote control of its own computer
  24. 毫无头绪的自学Python,你可能连门槛都摸不到!【最佳学习路线】
  25. Python读取二进制文件代码方法解析
  26. Python字典的实现原理
  27. Without a clue, you may not even touch the threshold【 Best learning route]
  28. Parsing method of Python reading binary file code
  29. Implementation principle of Python dictionary
  30. You must know the function of pandas to parse JSON data - JSON_ normalize()
  31. Python实用案例,私人定制,Python自动化生成爱豆专属2021日历
  32. Python practical case, private customization, python automatic generation of Adu exclusive 2021 calendar
  33. 《Python实例》震惊了,用Python这么简单实现了聊天系统的脏话,广告检测
  34. "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system in Python
  35. Convolutional neural network processing sequence for Python deep learning
  36. Python data structure and algorithm (1) -- enum type enum
  37. 超全大厂算法岗百问百答(推荐系统/机器学习/深度学习/C++/Spark/python)
  38. 【Python进阶】你真的明白NumPy中的ndarray吗?
  39. All questions and answers for algorithm posts of super large factories (recommended system / machine learning / deep learning / C + + / spark / Python)
  40. [advanced Python] do you really understand ndarray in numpy?
  41. 【Python进阶】Python进阶专栏栏主自述:不忘初心,砥砺前行
  42. [advanced Python] Python advanced column main readme: never forget the original intention and forge ahead
  43. python垃圾回收和缓存管理
  44. java调用Python程序
  45. java调用Python程序
  46. Python常用函数有哪些?Python基础入门课程
  47. Python garbage collection and cache management
  48. Java calling Python program
  49. Java calling Python program
  50. What functions are commonly used in Python? Introduction to Python Basics
  51. Python basic knowledge
  52. Anaconda5.2 安装 Python 库(MySQLdb)的方法
  53. Python实现对脑电数据情绪分析
  54. Anaconda 5.2 method of installing Python Library (mysqldb)
  55. Python implements emotion analysis of EEG data
  56. Master some advanced usage of Python in 30 seconds, which makes others envy it
  57. python爬取百度图片并对图片做一系列处理
  58. Python crawls Baidu pictures and does a series of processing on them
  59. python链接mysql数据库
  60. Python link MySQL database