[zero basics of Python to introduction] a prerequisite for Python preparatory knowledge -- basic coding specification of Python

Silly little y Typing Code 2021-11-25 10:48:23
zero basics python introduction prerequisite

 Please add a picture description


Python Coding standards

Coding standards It exists in all kinds of programming languages , Maybe some languages are not very intuitive

If you are a novice, learn to write code , So from the beginning Memorize coding rules It will have a great impact on the future compilation of specifications !

Here is a brief introduction to several coding specifications that beginners should keep in mind , It is divided into several aspects to introduce , Let's have a look !

Python use PEP 8 As coding specification , among PEP yes Python Enhancement Proposal(Python Enhancement proposal ) Abbreviation ,8 It stands for Python Code style guide .

Let's take a look at the code in a picture
 Insert picture description here
Compare with the picture above Two pieces of code in can find , They contain exactly the same code

But the coding format on the right obviously looks more regular than the code snippet on the left , It will also be easier to read 、 Carefree , Because it follows the most basic Python Code specification .

The following is divided into several parts to learn Python Code specification of , Make our code more beautiful 、 beautiful !

️‍ Declaration encoding format

  • Generally speaking , The declaration encoding format is required in the script

  • If python The source code file There is no declared encoding format ,python The interpreter will default to ASCII code

  • But one disadvantage of this is , In case of non ASCII Encoded character ,python The interpreter will report an error

  • With UTF-8 For example , The following two kinds of encoding format statements are in line with the rules .

# -*- coding: utf-8 -*-
# coding = utf-8

️‍ Indent rules

  • And other programming languages ( Such as Java、C Language ) Use braces “{}” Separate code blocks are different ,Python Using code indents and colons ( : ) To distinguish the layers between blocks of code .

  • stay Python in , For class definitions 、 Function definition 、 Flow control statement 、 Exception handling statements, etc , The colon at the end of the line and the indent of the next line , Indicates the beginning of the next block of code , The end of the indentation indicates the end of the code block .

  • Be careful ,Python Indent the code in , You can use spaces or Tab Key implementation . But whether it's manual typing spaces , Or use Tab key , Usually use 4 Space length as an indent ( By default , One Tab The key means 4 A space ).

  • about Python Indent rules , Beginners can understand ,Python Require lines of code that belong to the same scope , They must be indented by the same amount , But the exact amount of indentation , No hard and fast rules .

Correct sample code :

if a==1:
print(" correct ") # Indent 4 Empty space 
else: # And if alignment 
print(" error ") # Indent 4 Empty space 

Error example code :

if a==1:
print(" correct ")
print(" error ")
print("end") # To correct, just delete the space in front of this line of code 

Just remember a little : Unified use 4 Space to indent , Do not use tab, No more tab Mixed with Spaces

Remember that , Generally speaking, indentation will not cause too much problem !

️‍ Comment part

Python Use in # Annotate , We are using # When ,# There should be a space behind the number

 # Comment part 
# Comment part 

When commenting in the line , At least two spaces should be added in the middle

print(" Hello , The world ") # notes 

️‍ Space

Space General principles used :

  • One space on each side of a binary operator , The spaces on both sides of arithmetic operators can be used flexibly , But make sure both sides are consistent
  • Don't use commas 、 A semicolon 、 A colon is preceded by a space , But they should be followed by ( Except at the end of the line )
  • Function's argument list , There should be a space after the comma
  • Function's argument list , The default value is equal sign without spaces
  • After the left bracket , Don't add space before the right parenthesis
  • parameter list , There should be no space in front of the left bracket of the index or slice

Usually , On both sides of the operator 、 Between function arguments and both sides of commas , It is recommended to use spaces to separate .

️‍ Blank line use

Blank line General principles used :

  • Code format statement 、 Module import 、 Constant and global variable declarations 、 There are two lines between the top-level definition and the execution code
  • There are two empty lines between the top-level definitions , Empty a line between method definitions
  • Inside a function or method , You can empty a line where necessary to enhance the sense of rhythm , But we should avoid continuous empty lines

Using the necessary blank lines can increase the readability of the code , Usually defined at the top level ( Such as the definition of a function or class ) There are two lines in between , There is a blank line between the method definitions , In addition, a line can be left blank in the position used to separate certain functions .

️‍ Module import part

The import should always be at the top of the file , After module comments and document strings , Before module global variables and constants .

Imports should be grouped from the most common to the least common , Leave a line blank between groups :

  • Standard library import
  • Third party library import
  • The application specifies the import

Every import Statement imports only one module , Try to avoid importing multiple modules at once

# recommend 
import os
import sys
# Not recommended 
import os,sys

️‍ Naming specification

Everyone should be familiar with the naming convention , But the explicit specifications of different programming languages are also different ~

Python General principles for naming recommendations :

  • Modules should be named in lowercase as much as possible , Keep the initials in lowercase , Try not to underline
  • Class names use humps (CamelCase) Naming style , title case , Private classes can start with an underscore
  • All function names are lowercase , If there are more than one word , Separate... With underscores
  • Private functions can start with an underline
  • Try to lower the variable name , If there are more than one word , Separate... With underscores
  • Constants are in uppercase , If there are more than one word , Use an underline to separate

️‍ Quotation mark usage

Python in , Single and double quotation marks can be used correctly in the output statement , But there are also corresponding coding specifications

So let's not add quotation marks at will , It is best to follow the following specifications !

General principles for the use of quotation marks :

  • Natural language uses double quotation marks
  • The machine identification uses single quotation marks
  • Regular expressions use double quotes
  • docstring (docstring) Use three double quotes

️‍ Semicolon usage

Python It is very different from the semicolon used in several other mainstream programming languages
Python You don't need a semicolon at the end of your code , and Java and C# And so on

Don't add a semicolon to the end of a line , And don't use semicolons to put two commands on the same line , for example :

# Not recommended 
print("Hello") ; print("World")


About beginners Python The basic coding specification probably needs special attention !

We followed the coding rules from the beginning , Develop a good coding habit , It is also a good start for learning programming !

 Please add a picture description

本文为[Silly little y Typing Code]所创,转载请带上原文链接,感谢

  1. Python basic syntax -- Boolean operation, break, continue, pass
  2. Python basic syntax -- loop
  3. Python first experience - efficient office, data analysis, crawler
  4. Modulenotfounderror: no module named 'Django summernote details
  5. Key points for Django to make personal blog website
  6. Path setting of templates in Django settings
  7. Leetcode 1611. Minimum one bit operations to make integers Zero (Python)
  8. Directory C: \ users \ a \ desktop \ Django_ The blog master is registered as the GIT root, but no git repository details are found there
  9. Django. Core. Exceptions. Improveconfigured: application labels aren't unique, duplicates: admin
  10. How to verify that Django has created the project details correctly
  11. How to create a database when using Django to construct a website
  12. The solution of using Django framework to create project in Windows system
  13. Running Python virtual environment on win10 system to execute ll_ Env \ scripts \ activate: unable to load file elaboration scheme
  14. Detailed explanation of constructing virtual environment with Django in Python 3
  15. Python implementation of affine cipher
  16. RC4 Python implementation
  17. Simple: Python_ Automatic body temperature clock
  18. 用python把两个csv中的日期的列提出年,做出新的一列,再把两个csv表格按照新做出的日期这列和ID号合并为一个表。
  19. python中类实例化后,其对象无法被其他模块调用方法
  20. [JSON] - Python creates JSON file format
  21. Utilisez Python pour proposer l'année de la colonne de date dans les deux CSV, faire une nouvelle colonne, puis combiner les deux tableaux CSV en un seul tableau avec la colonne de date et le numéro d'identification.
  22. 关于#python#的问题,请各位专家解答!
  23. ***
  24. ***
  25. 關於#python#的問題,請各比特專家解答!
  26. S'il vous plaît répondre aux questions de Python!
  27. About the import of Python class
  28. Magic Python property decorator: 1 line of code makes Python methods become properties in seconds
  29. Python 音频调整音量(附代码) | Python工具
  30. Python programming ideas [series of articles]
  31. Python crawler programming idea (67): modify nodes using pyquery
  32. Python crawler programming idea (66): using pyquery to obtain node information
  33. Python crawler programming idea (65): find nodes using pyquery
  34. Python crawler programming idea (64): using CSS selectors in pyquery
  35. Python crawler programming idea (63): basic knowledge of pyquery
  36. Python crawler programming idea (62): project practice: capturing cool dog online red song list
  37. Python crawler programming idea (61): project practice: capturing rental information
  38. Python crawler programming idea (60): get CSS selector code through browser
  39. Python爬虫编程思想(85):在Python中使用非关系型数据库
  40. Volume de réglage audio Python (avec Code) | outils Python
  41. Python crawler programming idea (59): get attribute value and text with beautiful soup CSS selector
  42. Python crawler programming idea (58): nested selection nodes with beautiful soup CSS selectors
  43. Python crawler programming idea (57): basic usage of CSS selector in beautiful soup
  44. Python crawler programming idea (56): find method of beautiful soup method selector
  45. Python crawler programming idea (55): find of beautiful soup method selector_ All method
  46. Python crawler programming idea (54): use beautiful soup to select sibling nodes
  47. Python crawler programming idea (53): use beautiful soup to select the parent node
  48. Django3.0 solves the problem of error reporting in reverse parsing
  49. Precautions for Python crawler
  50. Python 3 crawler series (1) -- climbing blind date websites
  51. Python到底是什么?为什么要学Python?
  52. #yyds干货盘点#Pandas数据清洗实用指南
  53. Python打包exe文件无法运行
  54. Two common ways to save files in Python
  55. #yyds幹貨盤點#Pandas數據清洗實用指南
  56. Yyds Dry Inventory pandas Data Cleaning Practical Guide
  57. PYTHON用LSTM长短期记忆神经网络的参数优化方法预测时间序列洗发水销售数据
  58. Python集成学习:自己编写构建AdaBoost分类模型可视化决策边界及sklearn包调用比较
  59. Python 3 makes a search software
  60. Python 3 simulated microblog login