Let's talk about Python's coding style
This article brings you relevant knowledge about python, which mainly introduces the basic coding specifications of Python, including declaring the coding format, indentation rules, comment parts and use of blank lines, etc. ,I hope everyone has to help.
Recommended learning: python tutorial
Python coding specification
Coding specification
It exists in various programming languages, and it may not be very intuitive in some languages.
If you are a novice learning to write code, then memorizing the coding rules at the beginning will be helpful for future writing specifications. The impact is huge!
Let’s briefly introduce some coding standards that beginners should keep in mind. They are divided into several aspects. Let’s take a look!
Python adopts PEP 8
as the coding standard, where PEP
is the abbreviation of Python Enhancement Proposal
(Python Enhancement Proposal), 8 represents Is a style guide for Python code.
Let’s first look at the code in a picture
Comparing the two pieces of code in the picture above, we can find that the code they contain is exactly the same
but the right The code writing format on the side obviously looks more regular than the code segment on the left, and it will be easier and more enjoyable to read because it follows the most basic Python code writing specifications.
The following is divided into several parts to learn Python coding standards
to make our code more beautiful and beautiful!
Declare encoding format
Generally speaking, declaring encoding format is required in scripts
If The python source code file does not declare the encoding format, and the python interpreter will use ASCII encoding by default
But this has the disadvantage that once non-ASCII encoded characters appear, the python interpreter will report an error
Taking UTF-8 as an example, the following two encoding format declarations are in compliance with the rules.
# -*- coding: utf-8 -*-
# coding = utf-8
Indentation rules
and other programming languages (such as Java, C language) use curly brackets "{}" Different from separating code blocks, Python uses code indentation and colon (:) to distinguish the level between code blocks.
In Python, for class definitions, function definitions, flow control statements, exception handling statements, etc., the colon at the end of the line and the indentation of the next line indicate the start of the next code block , and the end of the indentation indicates the end of this code block.
Note that to indent code in Python, you can use spaces or the Tab key. But whether you type spaces manually or use the Tab key, usually
uses a length of 4 spaces as an indentation amount
(by default, a Tab key represents 4 spaces).For Python indentation rules, beginners can understand it this way. Python requires that each line of code belonging to the same scope must have the same indentation amount, but what is the specific indentation amount? , there are no hard and fast rules.
Correct sample code:
a=1if a==1: print("正确") # 缩进4个空白占位else: # 与if对齐 print("错误") # 缩进4个空白占位
Wrong sample code:
a=1if a==1: print("正确") else: print("错误") print("end") # 改正只需将这行代码前面的空格删除即可
Just remember one thing: Use 4 spaces for indentation uniformly To enter, do not use tabs, and do not mix tabs and spaces
Remember this, generally speaking, indentation will not cause too big a problem!
Comment part
Use # in Python to comment. When we use #, there should be a space after the
## 注释部分 # # 注释部分
When commenting inline , there should be at least two spaces in the middle
print("你好,世界") # 注释
spaces
spaces
General principles of use:
- in binary There is one space on both sides of the operator. The spaces on both sides of the arithmetic operator can be used flexibly, but both sides must be consistent.
- Do not add spaces before commas, semicolons, and colons, but you should add ( after them Unless at the end of the line)
- In the parameter list of the function, there must be a space after the comma
- In the parameter list of the function, the default value is not to add spaces around the equal sign
- Left bracket After that, do not add spaces before the right bracket
- Parameter list, there should be no spaces before the left bracket of index or slice
Normally, on both sides of the operator, function parameters It is recommended to use spaces to separate between and on both sides of commas.
Use blank lines
General principles for using blank lines:
- Encoding format declaration, module import, constant and Two empty lines between global variable declarations, top-level definitions and execution code
- Two empty lines between top-level definitions, one empty line between method definitions
- Within a function or method, you can place necessary Leave a blank line in place to enhance the sense of rhythm, but continuous blank lines should be avoided
模块导入部分
导入总应该放在文件顶部,位于模块注释和文档字符串之后,模块全局变量和常量之前。
导入应该按照从最通用到最不通用的顺序分组,分组之间空一行:
- 标准库导入
- 第三方库导入
- 应用程序指定导入
每个 import 语句只导入一个模块,尽量避免一次导入多个模块
#推荐import osimport sys #不推荐import os,sys
命名规范
命名规范这一块的大家应该都比较熟悉了,但是不同的编程语言之间的明明规范也是有所区别的~
Python命名建议遵循的一般性原则:
- 模块尽量使用小写命名,首字母保持小写,尽量不要用下划线
- 类名使用驼峰(CamelCase)命名风格,首字母大写,私有类可用一个下划线开头
- 函数名一律小写,如有多个单词,用下划线隔开
- 私有函数可用一个下划线开头
- 变量名尽量小写, 如有多个单词,用下划线隔开
- 常量采用全大写,如有多个单词,使用下划线隔开
引号用法
Python中,输出语句中使用单双引号都是可以正确的,但是也有相应的编码规范
所以我们也不要随心所欲的添加引号,最好是遵循下面的规范!
引号使用的一般性原则:
- 自然语言使用双引号
- 机器标识使用单引号
- 正则表达式使用双引号
- 文档字符串 (docstring) 使用三个双引号
分号用法
Python跟其他几个主流编程语言的分号使用区别很大
Python的代码末尾不需要加分号,而Java和C#等都需要添加
不要在行尾添加分号,也不要用分号将两条命令放在同一行,例如:
# 不推荐print("Hello") ; print("World")
推荐学习:python详细教程
The above is the detailed content of Let's talk about Python's coding style. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
